blob_id stringlengths 40 40 | language stringclasses 1 value | repo_name stringlengths 5 117 | path stringlengths 3 268 | src_encoding stringclasses 34 values | length_bytes int64 6 4.23M | score float64 2.52 5.19 | int_score int64 3 5 | detected_licenses listlengths 0 85 | license_type stringclasses 2 values | text stringlengths 13 4.23M | download_success bool 1 class |
|---|---|---|---|---|---|---|---|---|---|---|---|
4a0b604cfc63627dca6cf75da1e6f78e0c3f2a80 | C++ | MikeLankamp/fpm | /tests/basic_math.cpp | UTF-8 | 3,535 | 2.921875 | 3 | [
"MIT"
] | permissive | #include "common.hpp"
#include <fpm/math.hpp>
TEST(basic_math, abs)
{
using P = fpm::fixed_24_8;
EXPECT_EQ(P(13.125), abs(P(-13.125)));
EXPECT_EQ(P(13.125), abs(P(13.125)));
EXPECT_EQ(P(1), abs(P(-1)));
EXPECT_EQ(P(1), abs(P(1)));
}
TEST(basic_math, fmod)
{
using P = fpm::fixed_24_8;
EXPECT_EQ(P( 1.5), fmod(P( 9.5), P( 2)));
EXPECT_EQ(P(-1.5), fmod(P(-9.5), P( 2)));
EXPECT_EQ(P( 1.5), fmod(P( 9.5), P(-2)));
EXPECT_EQ(P(-1.5), fmod(P(-9.5), P(-2)));
}
TEST(basic_math, remainder)
{
using P = fpm::fixed_24_8;
EXPECT_EQ(P(-0.5), remainder(P( 9.5), P( 2)));
EXPECT_EQ(P( 0.5), remainder(P(-9.5), P( 2)));
EXPECT_EQ(P(-0.5), remainder(P( 9.5), P(-2)));
EXPECT_EQ(P( 0.5), remainder(P(-9.5), P(-2)));
EXPECT_EQ(P( 1), remainder(P( 9), P( 2)));
EXPECT_EQ(P(-1), remainder(P(-9), P( 2)));
EXPECT_EQ(P( 1), remainder(P( 9), P(-2)));
EXPECT_EQ(P(-1), remainder(P(-9), P(-2)));
EXPECT_EQ(P(-1), remainder(P( 11), P( 2)));
EXPECT_EQ(P( 1), remainder(P(-11), P( 2)));
EXPECT_EQ(P(-1), remainder(P( 11), P(-2)));
EXPECT_EQ(P( 1), remainder(P(-11), P(-2)));
EXPECT_EQ(P(-0.9), remainder(P( 5.1), P( 3)));
EXPECT_EQ(P( 0.9), remainder(P(-5.1), P( 3)));
EXPECT_EQ(P(-0.9), remainder(P( 5.1), P(-3)));
EXPECT_EQ(P( 0.9), remainder(P(-5.1), P(-3)));
EXPECT_EQ(P(0), remainder(P(0), P(1)));
}
TEST(basic_math, remquo)
{
// remquo must return at least 3 bits of quotient
constexpr int QUO_MIN_SIZE = 1 << 3;
using P = fpm::fixed_16_16;
int quo = 999999;
EXPECT_EQ(P( 1.5), remquo(P( 9.5), P( 2), &quo));
EXPECT_EQ( 4, quo % QUO_MIN_SIZE);
EXPECT_EQ(P(-1.5), remquo(P(-9.5), P( 2), &quo));
EXPECT_EQ(-4, quo % QUO_MIN_SIZE);
EXPECT_EQ(P( 1.5), remquo(P( 9.5), P(-2), &quo));
EXPECT_EQ(-4, quo % QUO_MIN_SIZE);
EXPECT_EQ(P(-1.5), remquo(P(-9.5), P(-2), &quo));
EXPECT_EQ( 4, quo % QUO_MIN_SIZE);
EXPECT_EQ(P( 1), remquo(P( 9), P( 2), &quo));
EXPECT_EQ( 4, quo % QUO_MIN_SIZE);
EXPECT_EQ(P(-1), remquo(P(-9), P( 2), &quo));
EXPECT_EQ(-4, quo % QUO_MIN_SIZE);
EXPECT_EQ(P( 1), remquo(P( 9), P(-2), &quo));
EXPECT_EQ(-4, quo % QUO_MIN_SIZE);
EXPECT_EQ(P(-1), remquo(P(-9), P(-2), &quo));
EXPECT_EQ( 4, quo % QUO_MIN_SIZE);
EXPECT_EQ(P( 1), remquo(P( 11), P( 2), &quo));
EXPECT_EQ( 5, quo % QUO_MIN_SIZE);
EXPECT_EQ(P(-1), remquo(P(-11), P( 2), &quo));
EXPECT_EQ(-5, quo % QUO_MIN_SIZE);
EXPECT_EQ(P( 1), remquo(P( 11), P(-2), &quo));
EXPECT_EQ(-5, quo % QUO_MIN_SIZE);
EXPECT_EQ(P(-1), remquo(P(-11), P(-2), &quo));
EXPECT_EQ( 5, quo % QUO_MIN_SIZE);
EXPECT_EQ(P( 2.1), remquo(P( 5.1), P( 3), &quo));
EXPECT_EQ( 1, quo % QUO_MIN_SIZE);
EXPECT_EQ(P(-2.1), remquo(P(-5.1), P( 3), &quo));
EXPECT_EQ(-1, quo % QUO_MIN_SIZE);
EXPECT_EQ(P( 2.1), remquo(P( 5.1), P(-3), &quo));
EXPECT_EQ(-1, quo % QUO_MIN_SIZE);
EXPECT_EQ(P(-2.1), remquo(P(-5.1), P(-3), &quo));
EXPECT_EQ( 1, quo % QUO_MIN_SIZE);
EXPECT_EQ(P( 3.375), remquo(P( 97.125), P( 3.75), &quo));
EXPECT_EQ( 1, quo % QUO_MIN_SIZE);
EXPECT_EQ(P(-3.375), remquo(P(-97.125), P( 3.75), &quo));
EXPECT_EQ(-1, quo % QUO_MIN_SIZE);
EXPECT_EQ(P( 3.375), remquo(P( 97.125), P(-3.75), &quo));
EXPECT_EQ(-1, quo % QUO_MIN_SIZE);
EXPECT_EQ(P(-3.375), remquo(P(-97.125), P(-3.75), &quo));
EXPECT_EQ( 1, quo % QUO_MIN_SIZE);
EXPECT_EQ(P(0), remquo(P(0), P(1), &quo));
EXPECT_EQ(0, quo % QUO_MIN_SIZE);
}
| true |
75a9f3f548ef73b94e4c5216480487e2cffe9d34 | C++ | porkallen/leetcode | /C++/Source/ListAndArray/25.cpp | UTF-8 | 1,223 | 3.125 | 3 | [] | no_license | #include "common.h"
class Solution {
public:
ListNode* reverseKGroup(ListNode* head, int k) {
/*
0 -> 1 -> 2 -> 3 -> 4 -> 5
*/
int count = 0;
ListNode tmpNode(-1);
tmpNode.next = head;
ListNode* pre = &tmpNode, *cur = &tmpNode, *next = &tmpNode;
while(cur->next){
cur = cur->next;
count++;
}
while(count >= k){
cur = pre->next;
next = cur->next;
for(int i = 0; i < k ; i++){
cur->next = next->next;
next->next = cur;
pre->next = next;
next = cur->next;
}
pre = cur;
count -= k;
}
return head;
}
};
int main(){
Solution s;
cout << "<Case:" << __FILE__ << ">\n";
cout << "==Output==\n";
#if ENABLE_TREE_TEST_CASE
TreeNode root(3);
root.left = new TreeNode(9);
root.right = new TreeNode(20);
root.right->left = new TreeNode(15);
root.right->right = new TreeNode(7);
root.left->right = new TreeNode(2);
/* 3
/ \
9 20
\ / \
2 15 7
*/
#endif
return 0;
}
| true |
e244722dad8aab581cbb9b72ab0c1372f37c466e | C++ | yuanhuihe/robocar | /source/robocar/main.cpp | UTF-8 | 5,433 | 2.734375 | 3 | [] | no_license |
#include <chrono>
#include <thread>
#include <atomic>
#include <iostream>
#include <vector>
#include <stdio.h> // for fgets()
#include <tuple>
#include <string> // std::string
#include <string.h> // memxxx/strlen()
#include "remote/remote.h"
#include <executive/executive.h>
void showTips(std::vector<Driver::Action*>& actList)
{
std::cout << "*************************************************" << std::endl;
std::cout << "Input definitions:" << std::endl;
std::cout << " -- " << "q" << ": " << "exit this app" << std::endl;
std::cout << " -- " << "s" << ": " << "show this tips again" << std::endl;
std::cout << std::endl;
std::cout << "Format for running an action: " << std::endl;
std::cout << " Run action : 'action index' + 'speed'" << std::endl;
std::cout << " Stop action: 'action index' + 's'" << std::endl;
std::cout << " e.g.: 1 70 ==> run action '1' with speed of '70%'" << std::endl;
std::cout << std::endl;
std::cout << "Actions list:" << std::endl;
for (size_t i = 0; i<actList.size(); i++)
{
std::string name = actList[i]->getName();
std::cout << " -- " << i << ": " << name << std::endl;
}
std::cout << "There are " << actList.size() << " actions can be executed" << std::endl;
std::cout << "*************************************************" << std::endl;
std::cout << std::endl;
}
void tInputCtrlThead(int& code, int& speed)
{
while (code != 'q')
{
char strInput[100];
memset(strInput, 0, sizeof(strInput));
fgets(strInput, 100, stdin);
int s = strlen(strInput);
if (s > 0) strInput[s - 1] = 0;
int ret = sscanf(strInput, "%d %d", &code, &speed);
switch (ret)
{
case 0:
{
// No any number input, maybe 's' or 'q' input
code = strInput[0];
}
break;
case 1:
{
// maybe input action stop command: number + 's'
ret = sscanf(strInput, "%d %c", &code, &speed);
if (ret != 2)
{
ret = sscanf(strInput, "%c %d", &code, &speed);
}
}
break;
case 2:
{
// no input error
}
break;
default:
break;
}
}
}
int main(int /*argc*/, char* /*argv*/[])
{
// time start
std::chrono::steady_clock::time_point start = std::chrono::steady_clock::now();
std::cout << " robocar application " << std::endl;
std::cout << "========================================" << std::endl;
std::cout << " >> Staring remote model ..." << std::endl;
remote Remote::remote;
remote.start();
std::cout << " >> OK" << std::endl;
std::cout << " >> Staring driver system ..." << std::endl;
// get system instance
Driver::ExecutiveSystem* eSys = Driver::ExecutiveSystem::InitSystem();
// load system
eSys->loadSystem();
// ExecutiveB body list
std::vector<Driver::Action*> actionList;
// Enum all actions
Driver::Action* act = eSys->enumFirstAction();
while (act)
{
// save to list
actionList.push_back(act);
// next
act = eSys->enumNextAction();
}
if (actionList.size() == 0)
{
Driver::ExecutiveSystem::ReleaseSystem(&eSys);
std::cout << " >> No executable actions on this system" << std::endl;
return -1;
}
std::cout << " >> OK" << std::endl;
std::cout << " >> System started, reset to standby ..." << std::endl;
// reset to standby state
eSys->resetSystem();
std::cout << " >> OK" << std::endl;
std::cout << " >> Welcom to robocar system <<" << std::endl << std::endl << std::endl;
showTips(actionList);
// controlling by console inputs
int preInput = 0;
int preSpeed = 0;
int inputCode = 0;
int inputSpeed = 0;
std::thread tInputCtrlObj(tInputCtrlThead, std::ref(inputCode), std::ref(inputSpeed));
bool bRunning = true;
while (bRunning)
{
// check input
if (inputCode == preInput && preSpeed == inputSpeed)
{
std::this_thread::sleep_for(std::chrono::duration<int, std::milli>(50));
continue;
}
// execute action
if (inputCode >= 0 && inputCode<(int)actionList.size() && ( preInput != inputCode || preSpeed != inputSpeed))
{
if (inputSpeed != 's')
{
eSys->runAction(actionList[inputCode], inputSpeed);
}
else
{
eSys->stopAction(actionList[inputCode]);
}
}
else if (inputCode == 's')
{
showTips(actionList);
}
else if (inputCode == 'q')
{
break;
}
else
{
std::cout << "Input error" << std::endl;
}
// update input
preInput = inputCode;
preSpeed = inputSpeed;
}
eSys->resetSystem();
// reset motors
eSys->unloadSystem();
// release system
Driver::ExecutiveSystem::ReleaseSystem(&eSys);
tInputCtrlObj.join();
// time end
std::chrono::steady_clock::time_point end = std::chrono::steady_clock::now();
std::chrono::duration<double, std::milli> elapsed = end - start;
std::cout << "runtime " << elapsed.count() << " ms\n";
return 0;
}
| true |
90b9cfc7cdb6ae37b94122f8e96a3a85d8aa8b97 | C++ | CahootsMalone/maxis-mesh-stuff | /C++/Mesh-tools/mesh-replace/main.cpp | UTF-8 | 9,754 | 3 | 3 | [] | no_license | // Replace the mesh/meshes at the specified index/indices in a Maxis mesh file with the specified data.
#include <iostream>
#include <fstream>
#include <string>
#include <set>
#include <vector>
#include <iterator>
#include <algorithm>
#include "cxxopts.hpp"
namespace Helpers
{
int BytesToInt32(const unsigned char* bytes)
{
// Little endian
return (bytes[3] << 24) | (bytes[2] << 16) | (bytes[1] << 8) | bytes[0];
}
int BytesToInt16(const unsigned char* bytes)
{
// Little endian
return (bytes[1] << 8) | bytes[0];
}
void Int32ToBytes(int value, unsigned char* destination)
{
// Little endian
destination[0] = 0xFF & value;
destination[1] = 0xFF & (value >> 8);
destination[2] = 0xFF & (value >> 16);
destination[3] = 0xFF & (value >> 24);
}
void CountStuff(const std::vector<char>& data, int& totalVertexCount, int& faceCount, int& uniqueVertexCount)
{
uniqueVertexCount = BytesToInt16(reinterpret_cast<const unsigned char*>(data.data() + 4 + 4));
faceCount = BytesToInt16(reinterpret_cast<const unsigned char*>(data.data() + 4 + 4 + 2));
totalVertexCount = 0;
for (int i = 0; i < (data.size() - 4); ++i)
{
if (std::strncmp(data.data() + i, "FACE", 4) == 0)
{
totalVertexCount += BytesToInt16(reinterpret_cast<const unsigned char*>(data.data() + i + 4 + 4));
}
}
}
}
bool parse(int argc, char* argv[], std::string& sourcePath, std::vector<int>& index, std::string& replacementPath, std::string& outputPath)
{
try
{
const std::string SOURCE = "source";
const std::string INDEX = "index";
const std::string REPLACEMENT = "replacement";
const std::string OUTPUT = "output";
const std::string HELP = "help";
cxxopts::Options options("mesh-replace", "Replace the mesh/meshes at the specified index/indices in a Maxis mesh file with the specified data.");
options.add_options()
("s," + SOURCE, "Source path. A Maxis mesh file (sim3d#.max).", cxxopts::value<std::string>(), "<path>")
("i," + INDEX, "Index/indices of mesh/meshes to replace.", cxxopts::value<std::vector<int>>(), "<integer>[,<integer>[,<integer>[,...]]]")
("r," + REPLACEMENT, "Path to replacement object data.", cxxopts::value<std::string>(), "<path>")
("o," + OUTPUT, "Output path.", cxxopts::value<std::string>(), "<path>")
("h," + HELP, "Display help.")
;
options.custom_help("(--source <path> --index <integer> --replacement <path> --output <path> | --help)");
cxxopts::ParseResult result = options.parse(argc, argv);
if (result.count(HELP) || result.arguments().size() == 0)
{
std::cout << options.help() << std::endl;
exit(0);
}
if (result.count(SOURCE)) {
sourcePath = result[SOURCE].as<std::string>();
}
else {
std::cout << "Error: No source file specified." << std::endl;
return false;
}
if (result.count(INDEX)) {
index = result[INDEX].as<std::vector<int>>();
}
else {
std::cout << "Error: No indices specified." << std::endl;
return false;
}
if (result.count(REPLACEMENT)) {
replacementPath = result[REPLACEMENT].as<std::string>();
}
else {
std::cout << "Error: No replacement file specified." << std::endl;
return false;
}
if (result.count(OUTPUT)) {
outputPath = result[OUTPUT].as<std::string>();
}
else {
std::cout << "Error: No output file specified." << std::endl;
return false;
}
}
catch (const std::exception& e)
{
std::cout << "Error parsing options: " << e.what() << std::endl;
return false;
}
return true;
}
int main(int argc, char* argv[])
{
std::string pathSource;
std::vector<int> indicesMeshesToReplace;
std::string pathReplacement;
std::string pathOutput;
bool parseSucceeded = parse(argc, argv, pathSource, indicesMeshesToReplace, pathReplacement, pathOutput);
if (!parseSucceeded)
{
std::cout << "ERROR: Unable to parse command-line arguments." << std::endl;
return 0;
}
// Load replacement mesh.
std::vector<char> dataReplacement;
{
std::fstream file;
file.open(pathReplacement, std::fstream::binary | std::fstream::in | std::fstream::out | std::fstream::ate);
if (file.fail())
{
std::cout << "ERROR: Unable to open replacement file at path " << pathReplacement << std::endl;
return 0;
}
file.seekg(0);
// Don't want to use istream_iterator: it skips whitespace by default.
std::copy(std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>(), std::back_inserter(dataReplacement));
file.close();
}
// Load mesh file into which replacement mesh will be inserted.
std::streampos sizeSource;
std::vector<char> data;
{
std::fstream file;
file.open(pathSource, std::fstream::binary | std::fstream::in | std::fstream::out | std::fstream::ate);
if (file.fail())
{
std::cout << "ERROR: Unable to open source file at path " << pathSource << std::endl;
return 0;
}
sizeSource = file.tellg(); // Positioned at end from use of fstream::ate on opening (incidentally, "ate" comes from "at end").
file.seekg(0);
// Don't want to use istream_iterator: it skips whitespace by default.
std::copy(std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>(), std::back_inserter(data));
file.close();
}
// Get initial values for total vertex count, face count, and unique vertex count. (They need to be updated when altering meshes.)
int overalltotalVertexCount = Helpers::BytesToInt32(reinterpret_cast<unsigned char*>(data.data() + 882));
int overallFaceCount = Helpers::BytesToInt32(reinterpret_cast<unsigned char*>(data.data() + 894));
int overallUniqueVertexCount = Helpers::BytesToInt32(reinterpret_cast<unsigned char*>(data.data() + 898));
int repTVC, repFC, repUVC;
Helpers::CountStuff(dataReplacement, repTVC, repFC, repUVC);
// Modify replacement mesh.
char* vertStart = dataReplacement.data() + 4 + 4 + 2 + 2 + 4 + 4 + 4 + 88 + 12;
float rotationAngle = 0 * (3.1415926535 / 180.0); // radians
float scaleFactor = 1;
int count = Helpers::BytesToInt16(reinterpret_cast<unsigned char*>(dataReplacement.data() + 4 + 4));
for (int v = 0; v < count; ++v)
{
int x = Helpers::BytesToInt32(reinterpret_cast<unsigned char*>(vertStart + v * 12 + 0));
int y = Helpers::BytesToInt32(reinterpret_cast<unsigned char*>(vertStart + v * 12 + 4));
int z = Helpers::BytesToInt32(reinterpret_cast<unsigned char*>(vertStart + v * 12 + 8));
int newX = x;
int newY = y;
int newZ = z;
// TODO expose Y rotation and scaling as arguments.
/*
// Rotate about Y axis
newX = cos(rotationAngle) * x + sin(rotationAngle) * z;
newY = y;
newZ = -sin(rotationAngle) * x + cos(rotationAngle) * z;
// Scale.
newX *= scaleFactor;
newY *= scaleFactor;
newZ *= scaleFactor;
*/
Helpers::Int32ToBytes(newX, reinterpret_cast<unsigned char*>(vertStart + v * 12 + 0));
Helpers::Int32ToBytes(newY, reinterpret_cast<unsigned char*>(vertStart + v * 12 + 4));
Helpers::Int32ToBytes(newZ, reinterpret_cast<unsigned char*>(vertStart + v * 12 + 8));
}
// Get offsets for each object in the mesh file.
std::vector<int> objectOffsets;
for (int i = 0; i < ((int)data.size() - 4); ++i)
{
if (std::strncmp(data.data() + i, "OBJX", 4) == 0)
{
objectOffsets.push_back(i);
}
}
for (int index : indicesMeshesToReplace)
{
if (index < 0) {
std::cout << "ERROR: Indices must be greater than 0." << std::endl;
return 0;
}
if (index > objectOffsets.size() - 1) {
std::cout << "ERROR: Specified index " << index << " is invalid: there are only " << objectOffsets.size() << " meshes in " << pathSource << " (valid indices are 0 to " << objectOffsets.size() - 1 << ")." << std::endl;
return 0;
}
}
// Loop below requires that indices be in ascending order.
std::sort(indicesMeshesToReplace.begin(), indicesMeshesToReplace.end());
// Replace meshes in reverse order so list of offsets doesn't have to be regenerated after each replacment.
for (int i = (indicesMeshesToReplace.size() - 1); i >= 0; --i)
{
int curIndex = indicesMeshesToReplace[i];
int curOffset = objectOffsets[curIndex];
int nextOffset;
if (curIndex == objectOffsets.size() - 1)
{
nextOffset = sizeSource;
}
else
{
nextOffset = objectOffsets[curIndex + 1];
}
// Get unique 12-byte value for this mesh.
std::vector<char> signature(data.begin() + curOffset + 112, data.begin() + curOffset + 124);
int curTVC, curFC, curUVC;
Helpers::CountStuff(std::vector<char>(data.begin() + curOffset, data.begin() + nextOffset), curTVC, curFC, curUVC);
// Replace existing mesh with replacement.
data.erase(data.begin() + curOffset, data.begin() + nextOffset);
data.insert(data.begin() + curOffset, dataReplacement.begin(), dataReplacement.end());
// Use 12-byte signature from original mesh.
data.erase(data.begin() + curOffset + 112, data.begin() + curOffset + 124);
data.insert(data.begin() + curOffset + 112, signature.begin(), signature.end());
// Update counts.
overalltotalVertexCount = overalltotalVertexCount - curTVC + repTVC;
overallFaceCount = overallFaceCount - curFC + repFC;
overallUniqueVertexCount = overallUniqueVertexCount - curUVC + repUVC;
}
// Update counts.
Helpers::Int32ToBytes(overalltotalVertexCount, reinterpret_cast<unsigned char*>(data.data() + 882));
Helpers::Int32ToBytes(overallFaceCount, reinterpret_cast<unsigned char*>(data.data() + 894));
Helpers::Int32ToBytes(overallUniqueVertexCount, reinterpret_cast<unsigned char*>(data.data() + 898));
// Export modified mesh file.
std::fstream newFile;
newFile.open(pathOutput, std::fstream::binary | std::fstream::out);
if (newFile.fail())
{
std::cout << "ERROR: Unable to open destination file at path " << pathOutput << std::endl;
return 0;
}
newFile.write(data.data(), data.size());
newFile.close();
return 0;
} | true |
d83e041c6163cc7af941e52b69d8748a427466c9 | C++ | okmd/codingblocks | /11-challenge-strings/10-ultra-fast-mathematicians.cpp | UTF-8 | 431 | 2.796875 | 3 | [] | no_license | #include<iostream>
#include<cstring>
using namespace std;
int main(){
int t,len;
string a,b;
cin>>t;
cin.ignore(); // ignore new line char
while(t--){
a.erase(a.begin(),a.end());
getline(cin,a,' ');
b.erase(b.begin(),b.end());
getline(cin,b);
len = a.length();
while(len--){
a[len] = (a[len]==b[len])?'0':'1';
}
//print
cout<<a<<endl;
}
return 0;
}
/*
if same bit then 0 else 1
*/
| true |
49c241a6f521c06bf4357a4ffcf7a56895a47a1d | C++ | Ave700/GeometryProcessing | /technique.cpp | UTF-8 | 2,877 | 3 | 3 | [] | no_license | #include <string>
#include "technique.h"
Technique::Technique()
{
m_shaderProg = 0;
}
//Destructor
Technique::~Technique()
{
//Delete shader shader objects that were compiled but the object was deleted prior to linking
for (ShaderObjList::iterator it = m_shaderObjList.begin(); it != m_shaderObjList.end(); it++)
{
glDeleteShader(*it);
}
if (m_shaderProg != 0)
{
glDeleteProgram(m_shaderProg);
m_shaderProg = 0;
}
}
bool Technique::Init()
{
m_shaderProg = glCreateProgram();
if (m_shaderProg == 0) {
fprintf(stderr, "Error creating shader program\n");
return false;
}
return true;
}
//method to add shaders to program must call finalize when done
bool Technique::AddShader(GLenum ShaderType, const char* pFilename)
{
std::string s;
if (!ReadFile(pFilename, s)) {
return false;
}
GLuint ShaderObj = glCreateShader(ShaderType);
if (ShaderObj == 0) {
fprintf(stderr, "Error creating shader obj of type %d\n", ShaderType);
return false;
}
//saving shader obj to list and can be deleted by destructor
m_shaderObjList.push_back(ShaderObj);
const GLchar* p[1]; //to store shader text code
p[0] = s.c_str();
GLint Lengths[1] = { (GLint)s.size() };
glShaderSource(ShaderObj, 1, p, Lengths); //both p and Lengths are of len 1 hence the 1 in the call.
glCompileShader(ShaderObj);
//error checking on compile
GLint success;
glGetShaderiv(ShaderObj, GL_COMPILE_STATUS, &success);
if (!success) {
GLchar InfoLog[1024];
glGetShaderInfoLog(ShaderObj, sizeof(InfoLog), NULL, InfoLog);
fprintf(stderr, "Error compiling shader type %d: '%s\n", pFilename, InfoLog);
return false;
}
//finally attached compiled shader obj to program
glAttachShader(m_shaderProg, ShaderObj);
return true;
}
bool Technique::Finalize()
{
GLint Success = 0;
GLchar ErrorLog[1024] = { 0 };
glLinkProgram(m_shaderProg);
glGetProgramiv(m_shaderProg, GL_LINK_STATUS, &Success);
if (Success == 0) {
glGetProgramInfoLog(m_shaderProg, sizeof(ErrorLog), NULL, ErrorLog);
fprintf(stderr, "Error linking shader program: '%s'\n", ErrorLog);
return false;
}
glValidateProgram(m_shaderProg);
glGetProgramiv(m_shaderProg, GL_VALIDATE_STATUS, &Success);
if (!Success) {
glGetProgramInfoLog(m_shaderProg, sizeof(ErrorLog), NULL, ErrorLog);
fprintf(stderr, "Invalid shader program: '%s'\n", ErrorLog);
}
for (ShaderObjList::iterator it = m_shaderObjList.begin(); it != m_shaderObjList.end(); it++) {
glDeleteShader(*it);
}
m_shaderObjList.clear();
return GLCheckError();
}
void Technique::Enable()
{
glUseProgram(m_shaderProg);
}
GLint Technique::GetUniformLocation(const char* pUniformName)
{
GLuint Location = glGetUniformLocation(m_shaderProg, pUniformName);
if (Location == INVALID_UNIFORM_LOCATION)
{
fprintf(stderr, "Warning! Unable to get location of uniform '%s' \n", pUniformName);
}
return Location;
}
| true |
44c2c9556611f2243ef2a2595fd926fc54fe950b | C++ | kiwixz/kae | /include/kae/exception.h | UTF-8 | 860 | 2.578125 | 3 | [
"MIT"
] | permissive | #pragma once
#include <memory>
#include <stdexcept>
#include <string>
#include <string_view>
#include <fmt/format.h>
#include "kae/pp.h"
#define MAKE_EXCEPTION(...) ::kae::Exception(SOURCE_LOCATION, __VA_ARGS__)
#define NOT_IMPLEMENTED throw MAKE_EXCEPTION("not implemented");
namespace kae {
struct Exception : std::runtime_error {
Exception(std::string from, std::string_view what);
template <typename... Args>
Exception(std::string from, std::string_view format, Args&&... args);
const std::string& from() const;
private:
std::shared_ptr<const std::string> from_;
};
[[noreturn]] void terminate() noexcept;
template <typename... Args>
Exception::Exception(std::string from, std::string_view format, Args&&... args) :
Exception{std::move(from), fmt::format(format, std::forward<Args>(args)...)}
{}
} // namespace kae
| true |
73f5fa2c9da1136572d603edc96a51b50fe787ae | C++ | gorilux/distfun | /distfun.hpp | UTF-8 | 35,025 | 2.71875 | 3 | [
"MIT"
] | permissive | /*
distfun.hpp - v0.01 - Vojtech Krs 2019
Implements signed distance functions of basic primitives
Allows conversion a CSG-like tree of primitives to a program
Implements distance program evaluation on CPU and GPU (CUDA)
INSTALLATION:
Add
#define DISTFUN_IMPLEMENTATION
before #include
Add
#define DISTFUN_ENABLE_CUDA
before #include in .cu/.cuh files
USAGE:
1. Construct a tree out of TreeNode, combining parametrized Primitives
2. Call compileProgram on root TreeNode and get DistProgram
3. Allocate DistProgram::staticSize() bytes (CPU or GPU)
4. call commitProgramCPU/GPU to copy program into a previously allocated byte array
5. Use distanceAtPos, distNormal or getNearestPoint to evaluate program at given position
*/
#ifndef DISTFUN_HEADER
#define DISTFUN_HEADER
#ifdef DISTFUN_ENABLE_CUDA
#include <cuda_runtime.h>
#define __DISTFUN__ inline __host__ __device__
#define __DISTFUN_T_ __host__ __device__
#define GLM_FORCE_ALIGNED_GENTYPES
#else
#define __DISTFUN__ inline
#define __DISTFUN_T_
#endif
#define DISTFUN_ARRAY_PLACEHOLDER 1
/*
#ifdef __CUDA_ARCH__
#pragma push
#pragma diag_suppress 2886
#include <glm/glm.hpp>
#include <glm/gtx/norm.hpp>
#pragma pop
#else*/
#pragma warning(push, 0)
#include <glm/glm.hpp>
#include <glm/gtx/norm.hpp>
#pragma warning(pop)
//#endif
#include <array>
#include <memory>
#include <vector>
#include <limits>
namespace distfun {
/*////////////////////////////////////////////////////////////////////////////////////
Math definitions
////////////////////////////////////////////////////////////////////////////////////*/
using vec4 = glm::vec4;
using vec3 = glm::vec3;
using vec2 = glm::vec2;
using mat4 = glm::mat4;
using mat3 = glm::mat3;
using ivec3 = glm::ivec3;
struct sdRay {
vec3 origin;
vec3 dir;
};
struct sdAABB {
__DISTFUN__ sdAABB(vec3 minimum = vec3(std::numeric_limits<float>::max()), vec3 maximum = vec3(std::numeric_limits<float>::lowest())) :
min(minimum),
max(maximum) {
}
vec3 min;// = vec3(std::numeric_limits<float>::max());
vec3 max;// = vec3(std::numeric_limits<float>::lowest());
__DISTFUN__ vec3 diagonal() const { return max - min; }
__DISTFUN__ vec3 center() const { return (min + max) * 0.5f; }
__DISTFUN__ vec3 sideX() const { return vec3(max.x - min.x, 0, 0); }
__DISTFUN__ vec3 sideY() const { return vec3(0, max.y - min.y, 0); }
__DISTFUN__ vec3 sideZ() const { return vec3(0, 0, max.z - min.z); }
__DISTFUN__ float volume() const {
const auto diag = diagonal();
return diag.x * diag.y * diag.z;
}
__DISTFUN__ vec3 corner(int index) const {
switch (index) {
case 0: return min;
case 1: return min + sideX();
case 2: return min + sideY();
case 3: return min + sideZ();
case 4: return max;
case 5: return max - sideX();
case 6: return max - sideY();
case 7: return max - sideZ();
}
return center();
}
__DISTFUN__ sdAABB getOctant(int octant) const
{
switch (octant) {
case 0: return { min, center() };
case 1: return { min + sideX()*0.5f, center() + sideX()*0.5f };
case 2: return { min + sideY()*0.5f, center() + sideY()*0.5f };
case 3: return { min + sideZ()*0.5f, center() + sideZ()*0.5f };
case 4: return { center(), max };
case 5: return { center() - sideX()*0.5f, max - sideX()*0.5f };
case 6: return { center() - sideY()*0.5f, max - sideY()*0.5f };
case 7: return { center() - sideZ()*0.5f, max - sideZ()*0.5f };
}
return sdAABB();
}
__DISTFUN__ sdAABB getSubGrid(const ivec3 & gridSize, const ivec3 & gridIndex) const {
const auto diag = diagonal();
const vec3 cellSize = vec3(diag.x / gridSize.x, diag.y / gridSize.y, diag.z / gridSize.z);
vec3 subgridmin = min + vec3(
gridIndex.x * cellSize.x,
gridIndex.y * cellSize.y,
gridIndex.z * cellSize.z);
return {
subgridmin,
subgridmin + cellSize
};
}
__DISTFUN__ sdAABB intersect(const sdAABB & b) const {
return { glm::max(min, b.min), glm::min(max, b.max) };
}
__DISTFUN__ bool isValid() const {
return min.x < max.x && min.y < max.y && min.z < max.z;
}
__DISTFUN__ bool isInside(vec3 pt) const
{
return pt.x >= min.x && pt.y > min.y && pt.z > min.z &&
pt.x < max.x && pt.y < max.y && pt.z < max.z;
}
};
struct sdBoundingSphere {
vec3 pos;
float radius;
};
/*////////////////////////////////////////////////////////////////////////////////////
Primitive parameters
////////////////////////////////////////////////////////////////////////////////////*/
struct sdPlaneParams { char _empty; };
struct sdSphereParams { float radius; };
struct sdBoxParams { vec3 size; };
struct sdCylinderParams { float radius; float height; };
struct sdBlendParams { float k; };
struct sdEllipsoidParams { vec3 size; };
struct sdConeParam { float h; float r1; float r2; };
struct sdGridParam { const void * ptr; ivec3 size; sdAABB bounds; };
/*////////////////////////////////////////////////////////////////////////////////////
Primitive
////////////////////////////////////////////////////////////////////////////////////*/
struct sdPrimitive {
enum Type {
SD_PLANE,
SD_SPHERE,
SD_BOX,
SD_CYLINDER,
SD_ELLIPSOID,
SD_CONE,
SD_GRID,
SD_OP_UNION,
SD_OP_INTERSECT,
SD_OP_DIFFERENCE,
SD_OP_BLEND
};
union Params {
sdPlaneParams plane;
sdSphereParams sphere;
sdBoxParams box;
sdCylinderParams cylinder;
sdBlendParams blend;
sdEllipsoidParams ellipsoid;
sdConeParam cone;
sdGridParam grid;
};
float rounding;
Type type;
mat4 invTransform;
Params params;
sdBoundingSphere bsphere;
sdPrimitive() :
rounding(0),
type(SD_PLANE),
params{ sdPlaneParams() },
invTransform(mat4(1.0f)),
bsphere{vec3(0),0.0f} {
}
};
/*////////////////////////////////////////////////////////////////////////////////////
Primitive Distance Functions
////////////////////////////////////////////////////////////////////////////////////*/
__DISTFUN__ float sdPlane(const vec3 & p, const sdPlaneParams & param)
{
return p.y;
}
__DISTFUN__ float sdSphere(const vec3 & p, const sdSphereParams & param)
{
return glm::length(p) - param.radius;
}
__DISTFUN__ float sdBox(const vec3 & p, const sdBoxParams & param)
{
vec3 d = glm::abs(p) - param.size;
return glm::min(glm::max(d.x, glm::max(d.y, d.z)), 0.0f) + glm::length(glm::max(d, vec3(0.0f)));
}
__DISTFUN__ float sdCylinder(const vec3 & p, const sdCylinderParams & param)
{
vec2 d = abs(vec2(glm::length(vec2(p.x, p.z)), p.y)) - vec2(param.radius, param.height);
return glm::min(glm::max(d.x, d.y), 0.0f) + glm::length(glm::max(d, 0.0f));
}
__DISTFUN__ float sdEllipsoid(const vec3 & p, const sdEllipsoidParams & param)
{
const auto & r = param.size;
float k0 = glm::length(vec3(p.x / r.x, p.y / r.y, p.z / r.z));
if (k0 == 0.0f)
return glm::min(r.x, glm::min(r.y, r.z));
float k1 = glm::length(vec3(p.x / (r.x*r.x), p.y / (r.y*r.y), p.z / (r.z*r.z)));
return k0*(k0 - 1.0f) / k1;
}
__DISTFUN__ float sdCone(const vec3 & p, const sdConeParam & param)
{
vec2 q = vec2(glm::length(vec2(p.x, p.z)), p.y);
vec2 k1 = vec2(param.r2, param.h);
vec2 k2 = vec2(param.r2 - param.r1, 2.0f*param.h);
vec2 ca = vec2(q.x - glm::min(q.x, (q.y < 0.0f) ? param.r1 : param.r2), abs(q.y) - param.h);
vec2 cb = q - k1 + k2*glm::clamp(glm::dot(k1 - q, k2) / glm::dot(k2, k2), 0.0f, 1.0f);
float s = (cb.x < 0.0f && ca.y < 0.0f) ? -1.0f : 1.0f;
return s*glm::sqrt(glm::min(glm::dot(ca, ca), glm::dot(cb, cb)));
}
__DISTFUN__ size_t sdLinearIndex(const ivec3 & stride, const ivec3 & pos) {
return stride.x * pos.x + stride.y * pos.y + stride.z * pos.z;
}
/*
posInside must be relative to param.bounds.min (in the space of the grid)
*/
__DISTFUN__ float sdGridInside(const vec3 & posInside, const sdGridParam & param) {
vec3 diag = param.bounds.diagonal();
vec3 cellSize = { diag.x / param.size.x,diag.y / param.size.y, diag.z / param.size.z };
ivec3 ipos = posInside * vec3(1.0f / cellSize.x, 1.0f / cellSize.y, 1.0f / cellSize.z);
ipos = glm::clamp(ipos, ivec3(0), param.size);
vec3 fract = posInside - vec3(ipos) * cellSize;
const ivec3 s = ivec3(1, param.size.x, param.size.x * param.size.z);
const size_t i = sdLinearIndex(s, ipos);
const ivec3 maxPos = param.size - ivec3(1);
const float * voxels = reinterpret_cast<const float*>(param.ptr);
float value[8] = {
voxels[sdLinearIndex(s,glm::min(ipos + ivec3(0,0,0), maxPos))],
voxels[sdLinearIndex(s,glm::min(ipos + ivec3(1,0,0), maxPos))],
voxels[sdLinearIndex(s,glm::min(ipos + ivec3(0,1,0), maxPos))],
voxels[sdLinearIndex(s,glm::min(ipos + ivec3(1,1,0), maxPos))],
voxels[sdLinearIndex(s,glm::min(ipos + ivec3(0,0,1), maxPos))],
voxels[sdLinearIndex(s,glm::min(ipos + ivec3(1,0,1), maxPos))],
voxels[sdLinearIndex(s,glm::min(ipos + ivec3(0,1,1), maxPos))],
voxels[sdLinearIndex(s,glm::min(ipos + ivec3(1,1,1), maxPos))]
};
float front = glm::mix(
glm::mix(value[0], value[1], fract.x),
glm::mix(value[2], value[3], fract.x),
fract.y
);
float back = glm::mix(
glm::mix(value[4], value[5], fract.x),
glm::mix(value[6], value[7], fract.x),
fract.y
);
return glm::mix(front, back, fract.z);
}
__DISTFUN__ float sdGrid(const vec3 & p, const sdGridParam & param) {
vec3 clamped = p;
const float EPS = 1e-6f;
bool inside = true;
if (p.x <= param.bounds.min.x) { clamped.x = param.bounds.min.x + EPS; inside = false; }
if (p.y <= param.bounds.min.y) { clamped.y = param.bounds.min.y + EPS; inside = false; }
if (p.z <= param.bounds.min.z) { clamped.z = param.bounds.min.z + EPS; inside = false; }
if (p.x >= param.bounds.max.x) { clamped.x = param.bounds.max.x - EPS; inside = false; }
if (p.y >= param.bounds.max.y) { clamped.y = param.bounds.max.y - EPS; inside = false; }
if (p.z >= param.bounds.max.z) { clamped.z = param.bounds.max.z - EPS; inside = false; }
if (inside) {
return sdGridInside(p - param.bounds.min, param);
}
else {
vec3 posInside = (clamped - param.bounds.min);
#ifdef DISTFUN_GRID_OUTSIDE_GRADIENT
vec3 res = (clamped - p) + sdGradient(posInside, EPS, sdGridInside, param);
return glm::length(res);
#else
return sdGridInside(posInside, param) + glm::length(clamped - p);
#endif
}
}
__DISTFUN__ float sdUnion(float a, float b) {
return glm::min(a, b);
}
__DISTFUN__ float sdIntersection(float a, float b) {
return glm::max(a, b);
}
__DISTFUN__ float sdDifference(float a, float b) {
return glm::max(-a, b);
}
__DISTFUN__ float sdRound(float dist, float r) {
return dist - r;
}
__DISTFUN__ float sdSmoothmin(float a, float b, float k) {
float h = glm::clamp(0.5f + 0.5f*(a - b) / k, 0.0f, 1.0f);
return glm::mix(a, b, h) - k*h*(1.0f - h);
}
/*////////////////////////////////////////////////////////////////////////////////////
Transformations and primitive distance
////////////////////////////////////////////////////////////////////////////////////*/
template <class Func, class ... Args>
__DISTFUN_T_ float sdTransform(
const vec3 & p,
const mat4 & invTransform,
Func f,
Args ... args
) {
return f(vec3(invTransform * vec4(p.x, p.y, p.z, 1.0f)), args ...);
}
__DISTFUN__ vec3 sdTransformPos(
const vec3 & p,
const mat4 & m
) {
return vec3(
m[0][0] * p[0] + m[1][0] * p[1] + m[2][0] * p[2] + m[3][0],
m[0][1] * p[0] + m[1][1] * p[1] + m[2][1] * p[2] + m[3][1],
m[0][2] * p[0] + m[1][2] * p[1] + m[2][2] * p[2] + m[3][2]
);
}
template <class Func, class ... Args>
__DISTFUN_T_ vec3 sdGradient(vec3 pos, float eps, Func f, Args ... args)
{
return vec3(
f(pos + vec3(eps, 0, 0), args ...) - f(pos - vec3(eps, 0, 0), args ...),
f(pos + vec3(0, eps, 0), args ...) - f(pos - vec3(0, eps, 0), args ...),
f(pos + vec3(0, 0, eps), args ...) - f(pos - vec3(0, 0, eps), args ...));
}
template <class Func, class ... Args>
__DISTFUN_T_ vec3 sdNormal(vec3 pos, float eps, Func f, Args ... args)
{
return glm::normalize(sdGradient(pos, eps, f, args...));
}
__DISTFUN__ float sdPrimitiveDistance(
const vec3 & pos,
const sdPrimitive & prim
) {
const vec3 tpos = sdTransformPos(pos, prim.invTransform);
switch (prim.type) {
case sdPrimitive::SD_SPHERE:
return sdSphere(tpos, prim.params.sphere);
case sdPrimitive::SD_ELLIPSOID:
return sdEllipsoid(tpos, prim.params.ellipsoid);
case sdPrimitive::SD_CONE:
return sdCone(tpos, prim.params.cone);
case sdPrimitive::SD_BOX:
return sdRound(sdBox(tpos, prim.params.box), prim.rounding);
case sdPrimitive::SD_CYLINDER:
return sdRound(sdCylinder(tpos, prim.params.cylinder), prim.rounding);
case sdPrimitive::SD_PLANE:
return sdPlane(tpos, prim.params.plane);
case sdPrimitive::SD_GRID:
return sdGrid(tpos, prim.params.grid);
}
return FLT_MAX;
}
__DISTFUN__ float sdPrimitiveDifference(const vec3 & pos, const sdPrimitive & a, const sdPrimitive & b) {
return sdDifference(sdPrimitiveDistance(pos, a), sdPrimitiveDistance(pos, b));
}
__DISTFUN__ vec3 sdGetNearestPoint(const vec3 & pos, const sdPrimitive & prim, float dx = 0.001f) {
float d = sdPrimitiveDistance(pos, prim);
vec3 N = sdNormal(pos, dx, sdPrimitiveDistance, prim);
return pos - d*N;
}
__DISTFUN__ sdAABB sdPrimitiveBounds(
const sdPrimitive & prim,
float pollDistance,
float dx = 0.001f
){
mat4 transform = glm::inverse(prim.invTransform);
vec3 pos = vec3(transform * vec4(vec3(0.0f), 1.0f));
vec3 exPt[6] = {
pos + pollDistance * vec3(-1,0,0),
pos + pollDistance * vec3(0,-1,0),
pos + pollDistance * vec3(0,0,-1),
pos + pollDistance * vec3(1,0,0),
pos + pollDistance * vec3(0,1,0),
pos + pollDistance * vec3(0,0,1)
};
sdAABB boundingbox;
boundingbox.min = {
sdGetNearestPoint(exPt[0], prim, dx).x,
sdGetNearestPoint(exPt[1], prim, dx).y,
sdGetNearestPoint(exPt[2], prim, dx).z
};
boundingbox.max = {
sdGetNearestPoint(exPt[3], prim, dx).x,
sdGetNearestPoint(exPt[4], prim, dx).y,
sdGetNearestPoint(exPt[5], prim, dx).z
};
return boundingbox;
}
/*////////////////////////////////////////////////////////////////////////////////////
Tree (CPU only)
////////////////////////////////////////////////////////////////////////////////////*/
struct sdTreeNode {
sdPrimitive primitive;
std::array<std::shared_ptr<sdTreeNode>, 2> children;
sdTreeNode() : children{ nullptr,nullptr }{
}
bool isLeaf() const {
return !children[0] && !children[1];
}
};
bool sdIsLeaf(const sdTreeNode & node);
int sdTreeDepth(const sdTreeNode & node);
/*////////////////////////////////////////////////////////////////////////////////////
Program
////////////////////////////////////////////////////////////////////////////////////*/
//Evaluation order
struct sdInstruction {
enum Type {
REG_OBJ,
REG_REG,
OBJ
};
sdInstruction(Type type = OBJ) :
itype(type)
{}
using RegIndex = char;
/*
Register DEST receives result of op on register reg and Primitive prim.
Op is parametrized by _p0
DEST <- reg op(_p0) prim
*/
struct AddrRegObj {
RegIndex reg;
sdPrimitive prim;
float _p0;
};
/*
Register DEST receives result of Primitive prim.
DEST <- prim
*/
struct AddrObj {
sdPrimitive prim;
};
/*
Register DEST receives result of op on register reg[0] and reg[1].
Op is parametrized by _p0
DEST <- reg[0] op(_p0) reg[1]
*/
struct AddrRegReg {
RegIndex reg[2];
float _p0;
};
union Addr {
Addr() { memset(this, 0, sizeof(Addr)); }
AddrRegObj regobj;
AddrObj obj;
AddrRegReg regreg;
};
sdPrimitive::Type optype;
Type itype;
RegIndex regTarget;
Addr addr;
};
struct sdProgram {
int instructionCount;
int registers;
std::vector<sdInstruction> instructions;
sdProgram() : instructionCount(0), registers(0) {
}
size_t staticSize() const {
return 2 * sizeof(int) + sizeof(sdInstruction)*instructions.size();
}
};
struct sdProgramStatic{
sdProgramStatic(const sdProgramStatic &) = delete;
sdProgramStatic & operator=(const sdProgramStatic &) = delete;
__DISTFUN__ size_t staticSize() const {
return 2 * sizeof(int) + sizeof(sdInstruction)*instructionCount;
}
int instructionCount;
int registers;
sdInstruction instructions[DISTFUN_ARRAY_PLACEHOLDER]; //In-place pointer for variable size
};
template <typename T>
__DISTFUN_T_ const sdProgramStatic * sdCastProgramStatic(const T * ptr) {
return reinterpret_cast<const sdProgramStatic *>(ptr);
}
template <typename T>
__DISTFUN_T_ sdProgramStatic * sdCastProgramStatic(T * ptr) {
return reinterpret_cast<sdProgramStatic *>(ptr);
}
/*////////////////////////////////////////////////////////////////////////////////////
Tree To Program conversion
////////////////////////////////////////////////////////////////////////////////////*/
sdProgram sdCompile(const sdTreeNode & node);
template <class CopyFun>
void sdCommit(void * destination, const sdProgram & program, CopyFun copyFunction){
sdProgramStatic *dst = reinterpret_cast<sdProgramStatic*>(destination);
copyFunction(&dst->instructionCount, &program.instructionCount, sizeof(int));
copyFunction(&dst->registers, &program.registers, sizeof(int));
copyFunction(&dst->instructions, program.instructions.data(), sizeof(sdInstruction) * program.instructionCount);
}
const sdProgramStatic * sdCommitCPU(void * destination, const sdProgram & program);
#ifdef DISTFUN_ENABLE_CUDA
const sdProgramStatic * sdCommitGPU(void * destination, const sdProgram & program);
#endif
/*////////////////////////////////////////////////////////////////////////////////////
Program evaluation
////////////////////////////////////////////////////////////////////////////////////*/
template <size_t regNum = 4>
__DISTFUN_T_ float sdDistanceAtPos(const vec3 & pos, const sdProgramStatic * programPtr) {
//Registers
float r[regNum];
if (programPtr->instructionCount == 0)
return FLT_MAX;
//Step through each instruction
for (auto pc = 0; pc < programPtr->instructionCount; pc++) {
const sdInstruction & i = programPtr->instructions[pc];
float & dest = r[i.regTarget];
if (i.itype == sdInstruction::OBJ) {
dest = sdPrimitiveDistance(pos, i.addr.obj.prim);
}
else if (i.itype == sdInstruction::REG_REG) {
switch (i.optype) {
case sdPrimitive::SD_OP_UNION:
dest = sdUnion(r[i.addr.regreg.reg[0]], r[i.addr.regreg.reg[1]]);
break;
case sdPrimitive::SD_OP_BLEND:
dest = sdSmoothmin(r[i.addr.regreg.reg[0]], r[i.addr.regreg.reg[1]], i.addr.regreg._p0);
break;
case sdPrimitive::SD_OP_INTERSECT:
dest = sdIntersection(r[i.addr.regreg.reg[0]], r[i.addr.regreg.reg[1]]);
break;
case sdPrimitive::SD_OP_DIFFERENCE:
dest = sdDifference(r[i.addr.regreg.reg[0]], r[i.addr.regreg.reg[1]]);
break;
}
}
else {
switch (i.optype) {
case sdPrimitive::SD_OP_UNION:
dest = sdUnion(r[i.addr.regobj.reg], sdPrimitiveDistance(pos, i.addr.regobj.prim));
break;
case sdPrimitive::SD_OP_BLEND:
dest = sdSmoothmin(r[i.addr.regobj.reg], sdPrimitiveDistance(pos, i.addr.regobj.prim), i.addr.regobj._p0);
break;
case sdPrimitive::SD_OP_INTERSECT:
dest = sdIntersection(r[i.addr.regobj.reg], sdPrimitiveDistance(pos, i.addr.regobj.prim));
break;
case sdPrimitive::SD_OP_DIFFERENCE:
dest = sdDifference(r[i.addr.regobj.reg], sdPrimitiveDistance(pos, i.addr.regobj.prim));
break;
}
}
}
return r[0];
}
template <size_t regNum = 4>
__DISTFUN_T_ vec3 sdGetNearestPoint(const vec3 & pos, const sdProgramStatic * programPtr, float dx = 0.001f) {
float d = sdDistanceAtPos<regNum>(pos, programPtr);
vec3 N = sdNormal(pos, dx, sdDistanceAtPos<regNum>, programPtr);
return pos - d*N;
}
template <size_t regNum = 4>
__DISTFUN_T_ float sdVolumeInBounds(
const sdAABB & bounds,
const sdProgramStatic * programPtr,
int curDepth,
int maxDepth
) {
const vec3 pt = bounds.center();
const float d = sdDistanceAtPos<regNum>(pt, programPtr);
//If nearest surface is outside of bounds
const vec3 diagonal = bounds.diagonal();
if (curDepth == maxDepth || d*d >= 0.5f * 0.5f * glm::length2(diagonal)) {
//Cell completely outside
if (d > 0.0f) return 0.0f;
//Cell completely inside, return volume of bounds
return bounds.volume();
}
//Nearest surface is within bounds, subdivide
float volume = 0.0f;
for (auto i = 0; i < 8; i++) {
volume += sdVolumeInBounds<regNum>(bounds.getOctant(i), programPtr, curDepth + 1, maxDepth);
}
return volume;
}
__DISTFUN__ float sdIntersectionVolume(
const sdAABB & bounds,
const sdPrimitive & a,
const sdPrimitive & b,
int curDepth,
int maxDepth
) {
const vec3 pt = bounds.center();
const float da = sdPrimitiveDistance(pt, a);
const float db = sdPrimitiveDistance(pt, b);
const float d = sdIntersection(da, db);
//If nearest surface is outside of bounds
const vec3 diagonal = bounds.diagonal();
if (curDepth == maxDepth || d*d >= 0.5f * 0.5f * glm::length2(diagonal)) {
//Cell completely outside
if (d > 0.0f) return 0.0f;
//Cell completely inside, return volume of bounds
return bounds.volume();
}
//Nearest surface is within bounds, subdivide
float volume = 0.0f;
for (auto i = 0; i < 8; i++) {
volume += sdIntersectionVolume(bounds.getOctant(i), a,b, curDepth + 1, maxDepth);
}
return volume;
}
__DISTFUN__ vec4 sdElasticity(
const sdAABB & bounds,
const sdPrimitive & a,
const sdPrimitive & b,
float k,
int curDepth,
int maxDepth
){
const vec3 pt = bounds.center();
const float da = sdPrimitiveDistance(pt, a);
const float db = sdPrimitiveDistance(pt, b);
const float d = sdIntersection(db, da);
//If nearest surface is outside of bounds
const vec3 diagonal = bounds.diagonal();
if (curDepth == maxDepth || d*d >= 0.5f * 0.5f * glm::length2(diagonal)) {
//Cell completely outside
if (d > 0.0f) return vec4(0.0f);
//Cell completely inside
//Distance to nearest non-penetrating surface of a
const float L = sdDifference(da, db);
//Normal to nearest non-penetrating surface of a
const vec3 N = sdNormal(pt, 0.0001f, sdPrimitiveDifference, a, b);
const float magnitude = 0.5f * k * (L*L);
const vec3 U = magnitude * N;
return vec4(U, magnitude);
}
//Nearest surface is within bounds, subdivide
vec4 elasticity = vec4(0.0f);
float childK = k / 5.0f;
for (auto i = 0; i < 8; i++) {
elasticity += sdElasticity(bounds.getOctant(i), a, b, childK, curDepth + 1, maxDepth);
}
return elasticity;
}
/*////////////////////////////////////////////////////////////////////////////////////
Raymarching
////////////////////////////////////////////////////////////////////////////////////*/
struct sdMarchState {
bool hit;
vec3 pos;
vec3 normal;
float dist;
};
__DISTFUN__ sdMarchState sdMarch(
const sdProgramStatic * programPtr,
const sdRay & ray,
float precision,
float maxDist
) {
float curDist = 0.0f;
float px = precision;
vec3 curPos = ray.origin;
while (curDist < maxDist) {
float t = sdDistanceAtPos<4>(curPos, programPtr);
if (t == FLT_MAX)
break;
if (t < precision) {
sdMarchState mstate;
mstate.hit = true;
mstate.pos = curPos;
mstate.normal = sdNormal(curPos, 2 * px, sdDistanceAtPos<4>, programPtr);
mstate.dist = curDist;
return mstate;
}
curDist += t;
curPos += t*ray.dir;
};
sdMarchState mstate;
mstate.hit = false;
mstate.pos = curPos;
return mstate;
}
/*////////////////////////////////////////////////////////////////////////////////////
Integration
////////////////////////////////////////////////////////////////////////////////////*/
template <typename ResType>
using sdIntegrateFunc = ResType(*)(const vec3 &pt, float d, const sdAABB & bounds);
__DISTFUN__ float sdIntegrateVolume(const vec3 & pt, float d, const sdAABB & bounds){
if(d > 0.0f) return 0.0f;
return bounds.volume();
}
__DISTFUN__ vec4 sdIntegrateCenterOfMass(const vec3 & pt, float d, const sdAABB & bounds){
if(d > 0.0f) return vec4(0.0f);
float V = bounds.volume();
return vec4(V * pt, V);
}
struct sdIntertiaTensor{
float s1;
float sx,sy,sz;
float sxy,syz,sxz;
float sxx,syy,szz;
__DISTFUN__ sdIntertiaTensor operator + (const sdIntertiaTensor & o) const{
sdIntertiaTensor r;
#ifdef __CUDA_ARCH__
#pragma unroll
#endif
for(auto i =0 ; i < 10; i++)
((float*)&r)[i] = ((const float*)this)[i] + ((const float*)&o)[i];
return r;
}
__DISTFUN__ sdIntertiaTensor(float val = 0.0f) :
s1(val),
sx(val), sy(val), sz(val),
sxy(val), syz(val), sxz(val),
sxx(val), syy(val), szz(val)
{
}
};
__DISTFUN__ sdIntertiaTensor sdIntegrateIntertia(const vec3 & pt, float d, const sdAABB & bounds){
if (d > 0.0f) return sdIntertiaTensor(0.0f);
sdIntertiaTensor s;
vec3 V = bounds.diagonal();
vec3 V2max = bounds.max * bounds.max;
vec3 V2min = bounds.min * bounds.min;
vec3 V2 = V2max - V2min;
vec3 V3max = bounds.max * V2max;
vec3 V3min = bounds.min * V2min;
vec3 V3 = V3max - V3min;
s.s1 = V.x * V.y * V.z;
s.sx = 0.5f * V2.x * V.y * V.z;
s.sy = 0.5f * V.x * V2.y * V.z;
s.sz = 0.5f * V.x * V.y * V2.z;
s.sxy = 0.25f * V2.x * V2.y * V.z;
s.syz = 0.25f * V.x * V2.y * V2.z;
s.sxz = 0.25f * V2.x * V.y * V2.z;
s.sxx = (1.0f / 3.0f) * V3.x * V.y * V.z;
s.syy = (1.0f / 3.0f) * V.x * V3.y * V.z;
s.szz = (1.0f / 3.0f) * V.x * V.y * V3.z;
return s;
}
template <typename ResType, class F>
__DISTFUN_T_ ResType sdIntegrateProgramRecursive(
const sdProgramStatic * programPtr,
const sdAABB & bounds,
F func,
int maxDepth = 5,
int curDepth = 0
){
vec3 pt = bounds.center();
float d = sdDistanceAtPos(pt, programPtr);
if (curDepth == maxDepth || d*d >= 0.5f * 0.5f * glm::length2(bounds.diagonal())) {
return func(pt, d, bounds);
}
ResType r = ResType(0);
for (auto i = 0; i < 8; i++) {
r = r + sdIntegrateProgramRecursive<ResType>(
programPtr,
bounds.getOctant(i),
func,
maxDepth,
curDepth + 1
);
}
return r;
}
/*
Same functionality as sdIntegrateProgramRecursive
but with explicit stack.
Faster on CUDA as it reduces thread divergence.
*/
template <int stackSize = 8, typename ResType, class F>
__DISTFUN_T_ ResType sdIntegrateProgramRecursiveExplicit(
const sdProgramStatic * programPtr,
const sdAABB & bounds,
F func,
int maxDepth = 5,
int curDepth = 0
) {
ResType result = ResType(0);
struct StackVal {
sdAABB bounds;
unsigned char i;
};
int stackDepth = 1;
StackVal _stack[stackSize];
StackVal * stackTop = &_stack[0];
stackTop->bounds = bounds;
stackTop->i = 0;
while (stackDepth > 0) {
StackVal & val = *stackTop;
if (val.i == 8) {
//Pop
stackTop--;
stackDepth--;
continue;
}
const sdAABB curBounds = val.bounds.getOctant(val.i);
val.i++;
const vec3 pt = curBounds.center();
const float d = sdDistanceAtPos<4>(pt, programPtr);
if (curDepth + stackDepth > maxDepth || d * d >= 0.5f * 0.5f * glm::length2(curBounds.diagonal())) {
result = result + func(pt, d, curBounds);
}
else {
//Push
StackVal & newVal = *(++stackTop);
newVal.bounds = curBounds;
newVal.i = 0;
stackDepth++;
}
}
return result;
}
template <typename ResType, class F, class ... Args>
__DISTFUN_T_ ResType sdIntegrateProgramGrid(
const sdProgramStatic * programPtr,
const sdAABB & bounds,
ivec3 gridSpec,
const F & func,
Args ... args
){
ResType r = ResType(0.0f);
for (auto z = 0; z < gridSpec.z; z++) {
for (auto y = 0; y < gridSpec.y; y++) {
for (auto x = 0; x < gridSpec.x; x++) {
const sdAABB cellBounds = bounds.getSubGrid(gridSpec, { x,y,z });
r = r + func(programPtr, cellBounds, args ...);
}
}
}
return r;
}
/*////////////////////////////////////////////////////////////////////////////////////
CUDA Kernels
////////////////////////////////////////////////////////////////////////////////////*/
#ifdef DISTFUN_ENABLE_CUDA
#define DISTFUN_VOLUME_VOX \
ivec3 vox = ivec3( \
blockIdx.x * blockDim.x + threadIdx.x, \
blockIdx.y * blockDim.y + threadIdx.y, \
blockIdx.z * blockDim.z + threadIdx.z \
);
#define DISTFUN_VOLUME_VOX_GUARD(res) \
DISTFUN_VOLUME_VOX \
if (vox.x >= res.x || vox.y >= res.y || vox.z >= res.z) \
return;
/*
Kernel integrating over bounds using func, with base resolution given by gridSpec.
Integrates from curDepth recursively until maxDepth
Each grid cell result is saved into result, which should be an array allocated to
gridSpec.x*gridSpec.y*gridSpec.z size
*/
template <int stackSize = 8, typename ResType, sdIntegrateFunc<ResType> func>
__global__ void sdIntegrateKernel(
const sdProgramStatic * programPtr,
sdAABB bounds,
ivec3 gridSpec,
ResType * result,
int maxDepth,
int curDepth
) {
DISTFUN_VOLUME_VOX_GUARD(gridSpec);
const ResType res = sdIntegrateProgramRecursiveExplicit<stackSize, ResType>(
programPtr,
bounds.getSubGrid(gridSpec, vox),
func,
maxDepth,
curDepth
);
const ivec3 stride = { 1, gridSpec.x, gridSpec.x * gridSpec.y };
const size_t index = sdLinearIndex(stride, vox);
result[index] = res;
}
#endif
}
/*////////////////////////////////////////////////////////////////////////////////////
CPU code definition
////////////////////////////////////////////////////////////////////////////////////*/
#ifdef DISTFUN_IMPLEMENTATION
#include <unordered_map>
#include <stack>
#include <functional>
#include <cstring>
namespace distfun {
bool sdIsLeaf(const sdTreeNode & node) {
return !node.children[0] && !node.children[1];
}
int sdTreeDepth(const sdTreeNode & node) {
int depth = 1;
if (node.children[0])
depth = sdTreeDepth(*node.children[0]);
if (node.children[1])
depth = glm::max(depth, sdTreeDepth(*node.children[1]));
return depth;
}
#define LABEL_LEFT_SIDE 0
#define LABEL_RIGHT_SIDE 1
int labelTreeNode(const sdTreeNode * node, int side, std::unordered_map<const sdTreeNode*, int> & labels) {
if (!node) return 0;
if (sdIsLeaf(*node)) {
//Left node (0), label 1; Right side (1) -> label 0
int newLabel = 1 - side;
labels[node] = newLabel;
return newLabel;
}
int labelLeft = labelTreeNode(node->children[0].get(), LABEL_LEFT_SIDE, labels);
int labelRight = labelTreeNode(node->children[1].get(), LABEL_RIGHT_SIDE, labels);
if (labelLeft == labelRight) {
labels[node] = labelLeft + 1;
}
else {
labels[node] = glm::max(labelLeft, labelRight);
}
return labels[node];
}
sdProgram sdCompile(const sdTreeNode & node) {
//Sethi-Ullman algorithm
//https://www.cse.iitk.ac.in/users/karkare/cs335/lectures/19SethiUllman.pdf
std::vector<sdInstruction> instructions;
std::unordered_map<const sdTreeNode*, int> labels;
int regs = labelTreeNode(&node, 0, labels);
int N = regs;
std::stack<sdInstruction::RegIndex> rstack;
std::stack<sdInstruction::RegIndex> tstack;
auto swapTop = [](std::stack<sdInstruction::RegIndex> & stack) {
int top = stack.top();
stack.pop();
int top2 = stack.top();
stack.pop();
stack.push(top);
stack.push(top2);
};
for (int i = 0; i < regs; i++) {
rstack.push(regs - i - 1);
tstack.push(regs - i - 1);
}
std::function<void(const sdTreeNode * node, int side)> genCode;
genCode = [&](const sdTreeNode * node, int side) -> void {
assert(node);
auto & leftChild = node->children[LABEL_LEFT_SIDE];
auto & rightChild = node->children[LABEL_RIGHT_SIDE];
if (sdIsLeaf(*node) && side == LABEL_LEFT_SIDE) {
sdInstruction i(sdInstruction::OBJ);
i.optype = node->primitive.type;
i.addr.obj.prim = node->primitive;
i.regTarget = rstack.top();
instructions.push_back(i);
}
else if (sdIsLeaf(*rightChild)) {
//Generate instructions for left subtree first
genCode(node->children[LABEL_LEFT_SIDE].get(), LABEL_LEFT_SIDE);
sdInstruction i(sdInstruction::REG_OBJ);
i.optype = node->primitive.type;
//special case for blend param
if (i.optype == sdPrimitive::SD_OP_BLEND) {
i.addr.regobj._p0 = node->primitive.params.blend.k;
}
i.addr.regobj.reg = rstack.top();
i.addr.regobj.prim = node->children[LABEL_RIGHT_SIDE]->primitive;
i.regTarget = rstack.top();
instructions.push_back(i);
}
//Case 3. left child requires less than N registers
//else if (labels[leftChild.get()] < N) {
else if (labels[leftChild.get()] < labels[rightChild.get()] && labels[leftChild.get()] < N) {
// Right child goes into next to top register
swapTop(rstack);
//Evaluate right child
genCode(node->children[LABEL_RIGHT_SIDE].get(), LABEL_RIGHT_SIDE);
sdInstruction::RegIndex R = rstack.top();
rstack.pop();
//Evaluate left child
genCode(node->children[LABEL_LEFT_SIDE].get(), LABEL_LEFT_SIDE);
sdInstruction i(sdInstruction::REG_REG);
i.optype = node->primitive.type;
i.addr.regreg.reg[0] = rstack.top();
i.addr.regreg.reg[1] = R;
//special case for blend param
if (i.optype == sdPrimitive::SD_OP_BLEND) {
i.addr.regreg._p0 = node->primitive.params.blend.k;
}
i.regTarget = rstack.top();
instructions.push_back(i);
rstack.push(R);
swapTop(rstack);
}
//else if (labels[rightChild.get()] < N) {
//Case 4
else if (labels[rightChild.get()] <= labels[leftChild.get()] && labels[rightChild.get()] < N) {
//Evaluate left child
genCode(node->children[LABEL_LEFT_SIDE].get(), LABEL_LEFT_SIDE);
sdInstruction::RegIndex R = rstack.top();
rstack.pop();
//Evaluate right child
genCode(node->children[LABEL_RIGHT_SIDE].get(), LABEL_RIGHT_SIDE);
sdInstruction i(sdInstruction::REG_REG);
i.optype = node->primitive.type;
i.addr.regreg.reg[0] = R;
i.addr.regreg.reg[1] = rstack.top();
i.regTarget = R;
instructions.push_back(i);
rstack.push(R);
}
//Shouldn't happen, uses temporary stack (in gmem)
else {
}
};
genCode(&node, 0);
sdProgram p;
p.instructions = std::move(instructions);
p.registers = regs;
p.instructionCount = static_cast<int>(p.instructions.size());
return p;
}
const sdProgramStatic * sdCommitCPU(void * destination, const sdProgram & program) {
sdCommit(destination, program, std::memcpy);
return sdCastProgramStatic(destination);
}
#ifdef DISTFUN_ENABLE_CUDA
const sdProgramStatic * sdCommitGPU(void * destination, const sdProgram & program) {
const auto cpyGlobal = [](void * dest, const void * src, size_t size) {
cudaMemcpy(dest, src, size, cudaMemcpyKind::cudaMemcpyHostToDevice);
};
sdCommit(destination, program, cpyGlobal);
return sdCastProgramStatic(destination);
}
#endif
}
#endif
#endif | true |
68d0cae235dc01b9c38619d98b0123dc3705e2a0 | C++ | rascal222/ProgrammationCPP3D | /src/surfaces/Surface.cpp | UTF-8 | 453 | 2.5625 | 3 | [] | no_license | #include "Surface.hpp"
namespace prog_3D {
Surface::Surface(int nbU, int nbV) : nbPointU(nbU), nbPointV(nbV) {
}
Surface::~Surface() {
}
void Surface::setPointNumberForU(int nb) {
nbPointU = nb;
}
void Surface::setPointNumberForV(int nb) {
nbPointV = nb;
}
int Surface::getPointNumberForU() {
return nbPointU;
}
int Surface::getPointNumberForV() {
return nbPointV;
}
} | true |
9dd4698cc0d1c11de790b253319b5a4c08fae0e0 | C++ | fredlim/lantern | /lantern/include/rasterizing_stage.h | UTF-8 | 61,339 | 3.0625 | 3 | [
"MIT"
] | permissive | #ifndef LANTERN_RASTERIZING_STAGE_H
#define LANTERN_RASTERIZING_STAGE_H
#include <algorithm>
#include "vector2.h"
#include "vector3.h"
#include "vector4.h"
#include "matrix3x3.h"
#include "texture.h"
#include "mesh_attribute_info.h"
#include "line.h"
#include "aabb.h"
#include "math_common.h"
namespace lantern
{
/** Rasterization algorithms option
* @ingroup Rendering
*/
enum class rasterization_algorithm_option
{
/** Rasterization using traversal algorithm with axis-aligned bounding box */
traversal_aabb,
/** Rasterization using traversal algorithm with backtracking */
traversal_backtracking,
/** Rasterization using traversal algorithm changing direction on every line */
traversal_zigzag,
/** Rasterization using inversed slope algorithm */
inversed_slope,
/** Rasterization using homogeneous 2d coordinates algorithm.
* This option uses perspective corrected interpolation for all attributes despite of what is specified in attribute info */
homogeneous
};
/** Class that holds information about binded attribute: its info and bind point.
* It's required when we rasterize a triangle: we need to know where put each attribute's interpolated value
* @ingroup Rendering
*/
template<typename TAttr>
class binded_mesh_attribute_info final
{
public:
/** Attribute data */
mesh_attribute_info<TAttr> const& info;
/** Address of variable to put interpolated value into */
TAttr* bind_point;
};
/** Container for all the binds
* @ingroup Rendering
*/
class binded_mesh_attributes final
{
public:
std::vector<binded_mesh_attribute_info<color>> color_attributes;
std::vector<binded_mesh_attribute_info<float>> float_attributes;
std::vector<binded_mesh_attribute_info<vector2f>> vector2f_attributes;
std::vector<binded_mesh_attribute_info<vector3f>> vector3f_attributes;
};
/** This rendering stage is responsible for calculating which pixels cover a texture
* @ingroup Rendering
*/
class rasterizing_stage final
{
public:
/** Constructs rasterizing stage with default settings */
rasterizing_stage();
/** Sets rasterization algorithm to use
* @param value Algorithm to use
*/
void set_rasterization_algorithm(rasterization_algorithm_option algorithm_option);
/** Gets rasterization algorithm
* @returns Current rasterization alogirthm
*/
rasterization_algorithm_option get_rasterization_algorithm() const;
/** Invokes stage
* @param vertex0 First triangle vertex
* @param vertex1 Second triangle vertex
* @param vertex2 Third triangle vertex
* @param index0 First vertex attribute index
* @param index1 Second vertex attribute index
* @param index2 Third vertex attribute index
* @param shader Shader to use
* @param binded_attributes Mesh attributes binded to shader
* @param target_texture Texture polygon will drawn into
* @param delegate Object to pass results to for further processing
*/
template<typename TShader, typename TDelegate>
void invoke(
vector4f const& vertex0, vector4f const& vertex1, vector4f const& vertex2,
unsigned int const index0, unsigned int const index1, unsigned int const index2,
TShader& shader,
binded_mesh_attributes const& binded_attributes,
texture& target_texture,
TDelegate& delegate);
private:
// Traversal algorithms
//
/** Checks if point lies on edge's positive halfspace, using top-left rule for points on the edge
* @param edge_equation_value Value of edge equation in the point
* @param edge_equation_a X-coefficient of edge equation
* @param edge_equation_b Y-coefficient of edge equation
* @returns True if point is either inside positive halfplane or it is on a left or a top edge
*/
bool is_point_on_positive_halfspace_top_left(
float const edge_equation_value, float const edge_equation_a, float const edge_equation_b);
/** Sets binds points values basing on barycentric coordinates
* @param binds List of binds
* @param index0 First triangle vertex index in a mesh
* @param index1 Second triangle vertex index in a mesh
* @param index2 Third triangle vertex index in a mesh
* @param b0 First barycentric coordinate
* @param b1 Second barycentric coordinate
* @param b2 Third barycentric coordinate
* @param z0_view_space_reciprocal 1/z-view for first vertex
* @param z1_view_space_reciprocal 1/z-view for second vertex
* @param z1_view_space_reciprocal 1/z-view for third vertex
*/
template<typename TAttr>
void set_bind_points_values_from_barycentric(
std::vector<binded_mesh_attribute_info<TAttr>> const& binds,
unsigned int const index0, unsigned int const index1, unsigned int const index2,
float const b0, float const b1, float const b2,
float const z0_view_space_reciprocal, float const z1_view_space_reciprocal, float const z2_view_space_reciprocal);
/** Rasterizes triangle using current pipeline setup using traversal aabb algorithm
* @param vertex0 First triangle vertex
* @param vertex1 Second triangle vertex
* @param vertex2 Third triangle vertex
* @param index0 First triangle vertex index in a mesh
* @param index1 Second triangle vertex index in a mesh
* @param index2 Third triangle vertex index in a mesh
* @param shader Shader to use
* @param binded_attributes Attributes to interpolate
* @param target_texture Texture polygon will be drawn into
* @param delegate Object to pass results to for further processing
*/
template<typename TShader, typename TDelegate>
inline void rasterize_traversal_aabb(
vector4f const& vertex0, vector4f const& vertex1, vector4f const& vertex2,
unsigned int const index0, unsigned int const index1, unsigned int const index2,
TShader& shader,
binded_mesh_attributes const& binded_attributes,
texture& target_texture,
TDelegate& delegate);
/** Rasterizes triangle using current pipeline setup using traversal backtracking algorithm
* @param vertex0 First triangle vertex
* @param vertex1 Second triangle vertex
* @param vertex2 Third triangle vertex
* @param index0 First triangle vertex index in a mesh
* @param index1 Second triangle vertex index in a mesh
* @param index2 Third triangle vertex index in a mesh
* @param shader Shader to use
* @param binded_attributes Attributes to interpolate
* @param target_texture Texture polygon will be drawn into
* @param delegate Object to pass results to for further processing
*/
template<typename TShader, typename TDelegate>
void rasterize_traversal_backtracking(
vector4f const& vertex0, vector4f const& vertex1, vector4f const& vertex2,
unsigned int const index0, unsigned int const index1, unsigned int const index2,
TShader& shader,
binded_mesh_attributes const& binded_attributes,
texture& target_texture,
TDelegate& delegate);
/** Rasterizes triangle using current pipeline setup using zigzag traversal algorithm
* @param vertex0 First triangle vertex
* @param vertex1 Second triangle vertex
* @param vertex2 Third triangle vertex
* @param index0 First triangle vertex index in a mesh
* @param index1 Second triangle vertex index in a mesh
* @param index2 Third triangle vertex index in a mesh
* @param shader Shader to use
* @param binded_attributes Attributes to interpolate
* @param target_texture Texture polygon will be drawn into
* @param delegate Object to pass results to for further processing
*/
template<typename TShader, typename TDelegate>
void rasterize_traversal_zigzag(
vector4f const& vertex0, vector4f const& vertex1, vector4f const& vertex2,
unsigned int const index0, unsigned int const index1, unsigned int const index2,
TShader& shader,
binded_mesh_attributes const& binded_attributes,
texture& target_texture,
TDelegate& delegate);
// Homogeneous algorithm
//
template<typename TAttr>
void save_edges_coefficients(
std::vector<binded_mesh_attribute_info<TAttr>> const& binds,
std::vector<vector3<TAttr>>& coefficients_storage,
unsigned int const index0, unsigned int const index1, unsigned int const index2,
matrix3x3f const& vertices_matrix_inversed);
template<typename TAttr>
void set_bind_points_values_from_edge_coefficients(
std::vector<binded_mesh_attribute_info<TAttr>> const& binds,
std::vector<vector3<TAttr>> const& coefficients_storage,
vector2f const& point,
float const w);
template<typename TShader, typename TDelegate>
void rasterize_homogeneous(
vector4f const& vertex0, vector4f const& vertex1, vector4f const& vertex2,
unsigned int const index0, unsigned int const index1, unsigned int const index2,
TShader& shader,
binded_mesh_attributes const& binded_attributes,
texture& target_texture,
TDelegate& delegate);
// Inversed slope algorithm
//
/** Saves scanline endpoints attributes values into intermediate storage.
* It saves attribute value divided by view z for attributes with perspective correction instead of just linearly interpolated values
* @param binds List of binds
* @param top_vertex_index Index of a top vertex
* @param left_vertex_index Index of a left vertex
* @param right_vertex_index Index of a right vertex
* @param distance_from_top_to_left_normalized Current distance from a top vertex to a left vertex
* @param distance_from_top_to_right_normalized Current distance from a top vertex to a right vertex
* @param left_values_storage Storage to put left edge values into
* @param right_values_storage Storage to put right edge values into
* @param top_vertex_zview_reciprocal Camera space z for top vertex, required for perspective correction
* @param left_vertex_zview_reciprocal Camera space z for left vertex, required for perspective correction
* @param right_vertex_zview_reciprocal Camera space z for right vertex, required for perspective correction
*/
template<typename TAttr>
void save_intermediate_attrs_values(
std::vector<binded_mesh_attribute_info<TAttr>> const& binds,
unsigned int const top_vertex_index,
unsigned int const left_vertex_index,
unsigned int const right_vertex_index,
float const distance_from_top_to_left_normalized,
float const distance_from_top_to_right_normalized,
std::vector<TAttr>& left_values_storage,
std::vector<TAttr>& right_values_storage,
float const top_vertex_zview_reciprocal,
float const left_vertex_zview_reciprocal,
float const right_vertex_zview_reciprocal);
/** Sets bind points values basing on scanline's endpoints and current position
* @param binds List of binds
* @param left_endpoint_values List of left endpoint values
* @param right_endpoint_values List of right endpoint values
* @param scanline_distance_normalized Current scanline distance from left endpoint to right endpoint
* @param zview_reciprocal_left Reciprocal of view z for left endpoint, required for attributes with perspective correction
* @param zview_reciprocal_right Reciprocal of view z for right endpoint, required for attributes with perspective correction
*/
template<typename TAttr>
void set_bind_points_values_from_scanline_endpoints(
std::vector<binded_mesh_attribute_info<TAttr>> const& binds,
std::vector<TAttr> const& left_endpoint_values,
std::vector<TAttr> const& right_endpoint_values,
float const scanline_distance_normalized,
float const zview_reciprocal_left, float const zview_reciprocal_right);
/** Gets next pixel center exclusively (if we're on 0.5, we move forward anyway)
* @param f Current position
* @returns Pixel center coordinate
*/
inline float get_next_pixel_center_exclusive(float const f);
/** Gets next pixel center inclusively (if we're on 0.5, we don't move)
* @param f Current position
* @returns Pixel center coordinate
*/
inline float get_next_pixel_center_inclusive(float const f);
/** Gets next previous center exclusively (if we're on 0.5, we move back anyway)
* @param f Current position
* @returns Pixel center coordinate
*/
inline float get_previous_pixel_center_exclusive(float const f);
/** Rasterizes triangle using inversed slope algorithm
* @param vertex0 First triangle vertex
* @param vertex1 Second triangle vertex
* @param vertex2 Third triangle vertex
* @param index0 First triangle vertex index in a mesh
* @param index1 Second triangle vertex index in a mesh
* @param index2 Third triangle vertex index in a mesh
* @param shader Shader to use
* @param binded_attributes Attributes to interpolate
* @param target_texture Texture polygon will be drawn into
* @param delegate Object to pass results to for further processing
*/
template<typename TShader, typename TDelegate>
void rasterize_inversed_slope(
vector4f const& vertex0, vector4f const& vertex1, vector4f const& vertex2,
unsigned int const index0, unsigned int const index1, unsigned int const index2,
TShader& shader,
binded_mesh_attributes const& binded_attributes,
texture& target_texture,
TDelegate& delegate);
/** Rasterizes triangle using inversed slope algorithm, triangle should be either top or bottom one
* @param vertex0 First triangle vertex
* @param vertex1 Second triangle vertex
* @param vertex2 Third triangle vertex
* @param index0 First triangle vertex index in a mesh
* @param index1 Second triangle vertex index in a mesh
* @param index2 Third triangle vertex index in a mesh
* @param v0_v1_edge_distance_offset Distance offset on v0-v1 edge (length of edge part which is not included in rasterizing triangle)
* @param v0_v2_edge_distance_offset Distance offset on v0-v2 edge (length of edge part which is not included in rasterizing triangle)
* @param shader Shader to use
* @param binded_attributes Attributes to interpolate
* @param target_texture Texture to draw into
* @param delegate Object to pass results to for further processing
*/
template<typename TShader, typename TDelegate>
void rasterize_inverse_slope_top_or_bottom_triangle(
vector4f& vertex0, vector4f& vertex1, vector4f& vertex2,
unsigned int index0, unsigned int index1, unsigned int index2,
float v0_v1_edge_distance_offset, float v0_v2_edge_distance_offset,
TShader& shader,
binded_mesh_attributes const& binded_attributes,
texture& target_texture,
TDelegate& delegate);
// Members
//
/** Current rasterization algorithm */
rasterization_algorithm_option m_rasterization_algorithm;
};
template<typename TShader, typename TDelegate>
void rasterizing_stage::invoke(
vector4f const& vertex0, vector4f const& vertex1, vector4f const& vertex2,
unsigned int const index0, unsigned int const index1, unsigned int const index2,
TShader& shader,
binded_mesh_attributes const& binded_attributes,
texture& target_texture,
TDelegate& delegate)
{
switch (m_rasterization_algorithm)
{
case rasterization_algorithm_option::traversal_aabb:
rasterize_traversal_aabb(
vertex0, vertex1, vertex2,
index0, index1, index2,
shader,
binded_attributes,
target_texture,
delegate);
break;
case rasterization_algorithm_option::traversal_backtracking:
rasterize_traversal_backtracking(
vertex0, vertex1, vertex2,
index0, index1, index2,
shader,
binded_attributes,
target_texture,
delegate);
break;
case rasterization_algorithm_option::traversal_zigzag:
rasterize_traversal_zigzag(
vertex0, vertex1, vertex2,
index0, index1, index2,
shader,
binded_attributes,
target_texture,
delegate);
break;
case rasterization_algorithm_option::homogeneous:
rasterize_homogeneous(
vertex0, vertex1, vertex2,
index0, index1, index2,
shader,
binded_attributes,
target_texture,
delegate);
break;
case rasterization_algorithm_option::inversed_slope:
rasterize_inversed_slope(
vertex0, vertex1, vertex2,
index0, index1, index2,
shader,
binded_attributes,
target_texture,
delegate);
break;
}
}
// Traversal algorithms
//
inline bool rasterizing_stage::is_point_on_positive_halfspace_top_left(
float const edge_equation_value, float const edge_equation_a, float const edge_equation_b)
{
// If we are on the edge, use top-left filling rule
//
if (std::abs(edge_equation_value) < FLOAT_EPSILON)
{
// edge_equation_value == 0.0f, thus point is on the edge,
// and we use top-left rule to decide if point is inside a triangle
//
if (std::abs(edge_equation_a) < FLOAT_EPSILON)
{
// edge.a == 0.0f, thus it's a horizontal edge and is either a top or a bottom one
//
// If normal y coordinate is pointing up - we are on the top edge
// Otherwise we are on the bottom edge
return edge_equation_b > 0.0f;
}
else
{
// If normal x coordinate is pointing right - we are on the left edge
// Otherwise we are on the right edge
return edge_equation_a > 0.0f;
}
}
else
{
// Check if we're on a positive halfplane
return edge_equation_value > 0.0f;
}
}
template<typename TAttr>
void rasterizing_stage::set_bind_points_values_from_barycentric(
std::vector<binded_mesh_attribute_info<TAttr>> const& binds,
unsigned int const index0, unsigned int const index1, unsigned int const index2,
float const b0, float const b1, float const b2,
float const z0_view_space_reciprocal, float const z1_view_space_reciprocal, float const z2_view_space_reciprocal)
{
size_t binds_count{binds.size()};
for (size_t i{0}; i < binds_count; ++i)
{
binded_mesh_attribute_info<TAttr> const& binded_attr = binds[i];
std::vector<TAttr> const& binded_attr_data = binded_attr.info.get_data();
std::vector<unsigned int> const& binded_attr_indices = binded_attr.info.get_indices();
TAttr const& value0 = binded_attr_data[binded_attr_indices[index0]];
TAttr const& value1 = binded_attr_data[binded_attr_indices[index1]];
TAttr const& value2 = binded_attr_data[binded_attr_indices[index2]];
if (binded_attr.info.get_interpolation_option() == attribute_interpolation_option::linear)
{
(*binded_attr.bind_point) = value0 * b0 + value1 * b1 + value2 * b2;
}
else if (binded_attr.info.get_interpolation_option() == attribute_interpolation_option::perspective_correct)
{
TAttr const value0_div_zview = value0 * z0_view_space_reciprocal;
TAttr const value1_div_zview = value1 * z1_view_space_reciprocal;
TAttr const value2_div_zview = value2 * z2_view_space_reciprocal;
float const zview_reciprocal_interpolated = z0_view_space_reciprocal * b0 + z1_view_space_reciprocal * b1 + z2_view_space_reciprocal * b2;
TAttr value_div_zview_interpolated = value0_div_zview * b0 + value1_div_zview * b1 + value2_div_zview * b2;
(*binded_attr.bind_point) = value_div_zview_interpolated * (1.0f / zview_reciprocal_interpolated);
}
}
}
template<typename TShader, typename TDelegate>
inline void rasterizing_stage::rasterize_traversal_aabb(
vector4f const& vertex0, vector4f const& vertex1, vector4f const& vertex2,
unsigned int const index0, unsigned int const index1, unsigned int const index2,
TShader& shader,
binded_mesh_attributes const& binded_attributes,
texture& target_texture,
TDelegate& delegate)
{
// Construct edges equations, considering that top left point is origin
//
line edge0{vertex1.x, vertex1.y, vertex0.x, vertex0.y};
line edge1{vertex2.x, vertex2.y, vertex1.x, vertex1.y};
line edge2{vertex0.x, vertex0.y, vertex2.x, vertex2.y};
// Calculate triangle area on screen and inverse it
float const triangle_area_inversed = 1.0f / triangle_2d_area(vertex0.x, vertex0.y, vertex1.x, vertex1.y, vertex2.x, vertex2.y);
// Construct triangle's bounding box
aabb<vector2ui> bounding_box{
vector2ui{
static_cast<unsigned int>(std::min(std::min(vertex0.x, vertex1.x), vertex2.x)),
static_cast<unsigned int>(std::min(std::min(vertex0.y, vertex1.y), vertex2.y))},
vector2ui{
static_cast<unsigned int>(std::max(std::max(vertex0.x, vertex1.x), vertex2.x)),
static_cast<unsigned int>(std::max(std::max(vertex0.y, vertex1.y), vertex2.y))}};
// Iterate over bounding box and check if pixel is inside the triangle
//
for (unsigned int y{bounding_box.from.y}; y <= bounding_box.to.y; ++y)
{
float const pixel_center_y{static_cast<float>(y) + 0.5f};
float const first_x_center{static_cast<float>(bounding_box.from.x) + 0.5f};
float edge0_equation_value{edge0.at(first_x_center, pixel_center_y)};
float edge1_equation_value{edge1.at(first_x_center, pixel_center_y)};
float edge2_equation_value{edge2.at(first_x_center, pixel_center_y)};
for (unsigned int x{bounding_box.from.x}; x <= bounding_box.to.x; ++x)
{
float const pixel_center_x{static_cast<float>(x) + 0.5f};
if (is_point_on_positive_halfspace_top_left(edge0_equation_value, edge0.a, edge0.b) &&
is_point_on_positive_halfspace_top_left(edge1_equation_value, edge1.a, edge1.b) &&
is_point_on_positive_halfspace_top_left(edge2_equation_value, edge2.a, edge2.b))
{
float const area01{triangle_2d_area(vertex0.x, vertex0.y, vertex1.x, vertex1.y, pixel_center_x, pixel_center_y)};
float const area12{triangle_2d_area(vertex1.x, vertex1.y, vertex2.x, vertex2.y, pixel_center_x, pixel_center_y)};
// Calculate barycentric coordinates
//
float const b2{area01 * triangle_area_inversed};
float const b0{area12 * triangle_area_inversed};
float const b1{1.0f - b0 - b2};
// Process different attributes
//
set_bind_points_values_from_barycentric<color>(
binded_attributes.color_attributes,
index0, index1, index2,
b0, b1, b2,
vertex0.w, vertex1.w, vertex2.w);
set_bind_points_values_from_barycentric<float>(
binded_attributes.float_attributes,
index0, index1, index2,
b0, b1, b2,
vertex0.w, vertex1.w, vertex2.w);
set_bind_points_values_from_barycentric<vector2f>(
binded_attributes.vector2f_attributes,
index0, index1, index2,
b0, b1, b2,
vertex0.w, vertex1.w, vertex2.w);
set_bind_points_values_from_barycentric<vector3f>(
binded_attributes.vector3f_attributes,
index0, index1, index2,
b0, b1, b2,
vertex0.w, vertex1.w, vertex2.w);
vector2ui pixel_coordinates{x, y};
vector3f sample_point{pixel_center_x, pixel_center_y, 0.0f};
delegate.process_rasterizing_stage_result(pixel_coordinates, sample_point, shader, target_texture);
}
edge0_equation_value += edge0.a;
edge1_equation_value += edge1.a;
edge2_equation_value += edge2.a;
}
}
}
template<typename TShader, typename TDelegate>
void rasterizing_stage::rasterize_traversal_backtracking(
vector4f const& vertex0, vector4f const& vertex1, vector4f const& vertex2,
unsigned int const index0, unsigned int const index1, unsigned int const index2,
TShader& shader,
binded_mesh_attributes const& binded_attributes,
texture& target_texture,
TDelegate& delegate)
{
// Construct edges equations, considering that top left point is origin
//
line edge0{vertex1.x, vertex1.y, vertex0.x, vertex0.y};
line edge1{vertex2.x, vertex2.y, vertex1.x, vertex1.y};
line edge2{vertex0.x, vertex0.y, vertex2.x, vertex2.y};
bool const edge0_normal_pointing_right = edge0.a > 0;
bool const edge1_normal_pointing_right = edge1.a > 0;
bool const edge2_normal_pointing_right = edge2.a > 0;
// Calculate triangle area on screen and inverse it
float const triangle_area_inversed = 1.0f / triangle_2d_area(vertex0.x, vertex0.y, vertex1.x, vertex1.y, vertex2.x, vertex2.y);
vector4f vertex0_sorted{vertex0};
vector4f vertex1_sorted{vertex1};
vector4f vertex2_sorted{vertex2};
// Sort vertices by y-coordinate
//
if (vertex1_sorted.y < vertex0_sorted.y)
{
std::swap(vertex0_sorted, vertex1_sorted);
}
if (vertex2_sorted.y < vertex1_sorted.y)
{
std::swap(vertex2_sorted, vertex1_sorted);
}
if (vertex1_sorted.y < vertex0_sorted.y)
{
std::swap(vertex1_sorted, vertex0_sorted);
}
// vertex0 is top vertex
// vertex2 is bottom vertex
vector2ui current_pixel{static_cast<unsigned int>(vertex0_sorted.x), static_cast<unsigned int>(vertex0_sorted.y)};
vector2f current_pixel_center{std::floor(vertex0_sorted.x) + 0.5f, std::floor(vertex0_sorted.y) + 0.5f};
float edge0_equation_value{edge0.at(current_pixel_center.x, current_pixel_center.y)};
float edge1_equation_value{edge1.at(current_pixel_center.x, current_pixel_center.y)};
float edge2_equation_value{edge2.at(current_pixel_center.x, current_pixel_center.y)};
while (current_pixel_center.y <= vertex2_sorted.y)
{
// Backtracking
//
while (true)
{
if ((edge0_normal_pointing_right && edge0_equation_value < 0) ||
(edge1_normal_pointing_right && edge1_equation_value < 0) ||
(edge2_normal_pointing_right && edge2_equation_value < 0))
{
break;
}
current_pixel.x -= 1;
current_pixel_center.x -= 1.0f;
edge0_equation_value -= edge0.a;
edge1_equation_value -= edge1.a;
edge2_equation_value -= edge2.a;
}
// Moving along the scanline
//
while (true)
{
if ((!edge0_normal_pointing_right && edge0_equation_value < 0) ||
(!edge1_normal_pointing_right && edge1_equation_value < 0) ||
(!edge2_normal_pointing_right && edge2_equation_value < 0))
{
break;
}
if (is_point_on_positive_halfspace_top_left(edge0_equation_value, edge0.a, edge0.b) &&
is_point_on_positive_halfspace_top_left(edge1_equation_value, edge1.a, edge1.b) &&
is_point_on_positive_halfspace_top_left(edge2_equation_value, edge2.a, edge2.b))
{
float const area01{triangle_2d_area(vertex0.x, vertex0.y, vertex1.x, vertex1.y, current_pixel_center.x, current_pixel_center.y)};
float const area12{triangle_2d_area(vertex1.x, vertex1.y, vertex2.x, vertex2.y, current_pixel_center.x, current_pixel_center.y)};
// Calculate barycentric coordinates
//
float const b2{area01 * triangle_area_inversed};
float const b0{area12 * triangle_area_inversed};
float const b1{1.0f - b0 - b2};
// Process different attributes
//
set_bind_points_values_from_barycentric<color>(
binded_attributes.color_attributes,
index0, index1, index2,
b0, b1, b2,
vertex0.w, vertex1.w, vertex2.w);
set_bind_points_values_from_barycentric<float>(
binded_attributes.float_attributes,
index0, index1, index2,
b0, b1, b2,
vertex0.w, vertex1.w, vertex2.w);
set_bind_points_values_from_barycentric<vector2f>(
binded_attributes.vector2f_attributes,
index0, index1, index2,
b0, b1, b2,
vertex0.w, vertex1.w, vertex2.w);
set_bind_points_values_from_barycentric<vector3f>(
binded_attributes.vector3f_attributes,
index0, index1, index2,
b0, b1, b2,
vertex0.w, vertex1.w, vertex2.w);
vector2ui pixel_coordinates{current_pixel.x, current_pixel.y};
vector3f sample_point{current_pixel_center.x, current_pixel_center.y, 0.0f};
delegate.process_rasterizing_stage_result(pixel_coordinates, sample_point, shader, target_texture);
}
current_pixel.x += 1;
current_pixel_center.x += 1.0f;
edge0_equation_value += edge0.a;
edge1_equation_value += edge1.a;
edge2_equation_value += edge2.a;
}
current_pixel.y += 1;
current_pixel_center.y += 1.0f;
edge0_equation_value += edge0.b;
edge1_equation_value += edge1.b;
edge2_equation_value += edge2.b;
}
}
template<typename TShader, typename TDelegate>
void rasterizing_stage::rasterize_traversal_zigzag(
vector4f const& vertex0, vector4f const& vertex1, vector4f const& vertex2,
unsigned int const index0, unsigned int const index1, unsigned int const index2,
TShader& shader,
binded_mesh_attributes const& binded_attributes,
texture& target_texture,
TDelegate& delegate)
{
// Construct edges equations, considering that top left point is origin
//
line edge0{vertex1.x, vertex1.y, vertex0.x, vertex0.y};
line edge1{vertex2.x, vertex2.y, vertex1.x, vertex1.y};
line edge2{vertex0.x, vertex0.y, vertex2.x, vertex2.y};
bool const edge0_normal_pointing_right = edge0.a > 0;
bool const edge1_normal_pointing_right = edge1.a > 0;
bool const edge2_normal_pointing_right = edge2.a > 0;
// Calculate triangle area on screen and inverse it
float const triangle_area_inversed = 1.0f / triangle_2d_area(vertex0.x, vertex0.y, vertex1.x, vertex1.y, vertex2.x, vertex2.y);
// Sort vertices by y-coordinate
//
vector4f vertex0_sorted{vertex0};
vector4f vertex1_sorted{vertex1};
vector4f vertex2_sorted{vertex2};
if (vertex1_sorted.y < vertex0_sorted.y)
{
std::swap(vertex0_sorted, vertex1_sorted);
}
if (vertex2_sorted.y < vertex1_sorted.y)
{
std::swap(vertex2_sorted, vertex1_sorted);
}
if (vertex1_sorted.y < vertex0_sorted.y)
{
std::swap(vertex1_sorted, vertex0_sorted);
}
// vertex0 is top vertex
// vertex2 is bottom vertex
vector2ui current_pixel{static_cast<unsigned int>(vertex0_sorted.x), static_cast<unsigned int>(vertex0_sorted.y)};
vector2f current_pixel_center{std::floor(vertex0_sorted.x) + 0.5f, std::floor(vertex0_sorted.y) + 0.5f};
float edge0_equation_value{edge0.at(current_pixel_center.x, current_pixel_center.y)};
float edge1_equation_value{edge1.at(current_pixel_center.x, current_pixel_center.y)};
float edge2_equation_value{edge2.at(current_pixel_center.x, current_pixel_center.y)};
bool start_direction_is_right{true};
bool is_moving_right{true};
// Index of the pixel we should move at when reach a pixel outside of a triangle from one side
unsigned int zigzag_x_index{current_pixel.x - 1};
while (current_pixel_center.y <= vertex2_sorted.y)
{
// Moving along the scanline
//
while (true)
{
// If we're moving right, we need to check pixel for being outside of a triangle from the right side
//
if (is_moving_right)
{
// If we're outside of a triangle
//
if ((!edge0_normal_pointing_right && edge0_equation_value < 0) ||
(!edge1_normal_pointing_right && edge1_equation_value < 0) ||
(!edge2_normal_pointing_right && edge2_equation_value < 0))
{
// If we moved only in side, switch direction and move to the first pixel we didn't visit yet
//
if (start_direction_is_right)
{
is_moving_right = false;
int const delta = current_pixel.x - zigzag_x_index;
current_pixel.x -= delta;
current_pixel_center.x -= delta * 1.0f;
edge0_equation_value -= delta * edge0.a;
edge1_equation_value -= delta * edge1.a;
edge2_equation_value -= delta * edge2.a;
continue;
}
else
{
// Otherwise scanline is over
break;
}
}
}
else
{
// If we're moving left, we need to check pixel for being outside of a triangle from the left side
//
if ((edge0_normal_pointing_right && edge0_equation_value < 0) ||
(edge1_normal_pointing_right && edge1_equation_value < 0) ||
(edge2_normal_pointing_right && edge2_equation_value < 0))
{
// If we moved only in side, switch direction and move to the first pixel we didn't visit yet
//
if (!start_direction_is_right)
{
is_moving_right = true;
int const delta = zigzag_x_index - current_pixel.x;
current_pixel.x += delta;
current_pixel_center.x += delta * 1.0f;
edge0_equation_value += delta * edge0.a;
edge1_equation_value += delta * edge1.a;
edge2_equation_value += delta * edge2.a;
continue;
}
else
{
// Otherwise scanline is over
break;
}
}
}
if (is_point_on_positive_halfspace_top_left(edge0_equation_value, edge0.a, edge0.b) &&
is_point_on_positive_halfspace_top_left(edge1_equation_value, edge1.a, edge1.b) &&
is_point_on_positive_halfspace_top_left(edge2_equation_value, edge2.a, edge2.b))
{
float const area01{triangle_2d_area(vertex0.x, vertex0.y, vertex1.x, vertex1.y, current_pixel_center.x, current_pixel_center.y)};
float const area12{triangle_2d_area(vertex1.x, vertex1.y, vertex2.x, vertex2.y, current_pixel_center.x, current_pixel_center.y)};
// Calculate barycentric coordinates
//
float const b2{area01 * triangle_area_inversed};
float const b0{area12 * triangle_area_inversed};
float const b1{1.0f - b0 - b2};
// Process different attributes
//
set_bind_points_values_from_barycentric<color>(
binded_attributes.color_attributes,
index0, index1, index2,
b0, b1, b2,
vertex0.w, vertex1.w, vertex2.w);
set_bind_points_values_from_barycentric<float>(
binded_attributes.float_attributes,
index0, index1, index2,
b0, b1, b2,
vertex0.w, vertex1.w, vertex2.w);
set_bind_points_values_from_barycentric<vector2f>(
binded_attributes.vector2f_attributes,
index0, index1, index2,
b0, b1, b2,
vertex0.w, vertex1.w, vertex2.w);
set_bind_points_values_from_barycentric<vector3f>(
binded_attributes.vector3f_attributes,
index0, index1, index2,
b0, b1, b2,
vertex0.w, vertex1.w, vertex2.w);
vector2ui const pixel_coordinates{current_pixel.x, current_pixel.y};
vector3f const sample_point{current_pixel_center.x, current_pixel_center.y, 0.0f};
delegate.process_rasterizing_stage_result(pixel_coordinates, sample_point, shader, target_texture);
}
if (is_moving_right)
{
current_pixel.x += 1;
current_pixel_center.x += 1.0f;
edge0_equation_value += edge0.a;
edge1_equation_value += edge1.a;
edge2_equation_value += edge2.a;
}
else
{
current_pixel.x -= 1;
current_pixel_center.x -= 1.0f;
edge0_equation_value -= edge0.a;
edge1_equation_value -= edge1.a;
edge2_equation_value -= edge2.a;
}
}
current_pixel.y += 1;
current_pixel_center.y += 1.0f;
edge0_equation_value += edge0.b;
edge1_equation_value += edge1.b;
edge2_equation_value += edge2.b;
start_direction_is_right = true;
is_moving_right = true;
zigzag_x_index = current_pixel.x - 1;
}
}
// Homogeneous algorithm
//
template<typename TAttr>
void rasterizing_stage::save_edges_coefficients(
std::vector<binded_mesh_attribute_info<TAttr>> const& binds,
std::vector<vector3<TAttr>>& coefficients_storage,
unsigned int const index0, unsigned int const index1, unsigned int const index2,
matrix3x3f const& vertices_matrix_inversed)
{
for (size_t i = 0; i < binds.size(); ++i)
{
binded_mesh_attribute_info<TAttr> const& binded_attr = binds[i];
std::vector<TAttr> const& binded_attr_data = binded_attr.info.get_data();
std::vector<unsigned int> const& binded_attr_indices = binded_attr.info.get_indices();
TAttr const& value0 = binded_attr_data[binded_attr_indices[index0]];
TAttr const& value1 = binded_attr_data[binded_attr_indices[index1]];
TAttr const& value2 = binded_attr_data[binded_attr_indices[index2]];
coefficients_storage[i] = vector3<TAttr>{value0, value1, value2} *vertices_matrix_inversed;
}
}
template<typename TAttr>
void rasterizing_stage::set_bind_points_values_from_edge_coefficients(
std::vector<binded_mesh_attribute_info<TAttr>> const& binds,
std::vector<vector3<TAttr>> const& coefficients_storage,
vector2f const& point,
float const w)
{
for (size_t i = 0; i < binds.size(); ++i)
{
vector3<TAttr> abc{coefficients_storage.at(i)};
TAttr const value_div_w = abc.x * point.x + abc.y * point.y + abc.z;
binded_mesh_attribute_info<TAttr> const& binded_attr = binds[i];
(*binded_attr.bind_point) = value_div_w * w;
}
}
template<typename TShader, typename TDelegate>
void rasterizing_stage::rasterize_homogeneous(
vector4f const& vertex0, vector4f const& vertex1, vector4f const& vertex2,
unsigned int const index0, unsigned int const index1, unsigned int const index2,
TShader& shader,
binded_mesh_attributes const& binded_attributes,
texture& target_texture,
TDelegate& delegate)
{
// p = ax + by + cw
// [p0 p1 p2] = [a b c] * m
// [a b c] = [p0 p1 p2] * m_inversed
matrix3x3f const m{
vertex0.x, vertex1.x, vertex2.x,
vertex0.y, vertex1.y, vertex2.y,
vertex0.w, vertex1.w, vertex2.w};
// Can also be interpreted as triple product
float const det = m.det();
// Check if m is invertible. If it's not, triangle shouldn't be rendered (volume == 0)
//
if (std::abs(det) < FLOAT_EPSILON)
{
return;
}
matrix3x3f const m_inversed{m.inversed_precalc_det(det)};
// Edges pseudoparameters
//
vector3f const edge0_p{1.0f, 0.0f, 0.0f};
vector3f const edge1_p{0.0f, 1.0f, 0.0f};
vector3f const edge2_p{0.0f, 0.0f, 1.0f};
// Edges coefficients
//
vector3f const edge0_abc{m_inversed.values[0][0], m_inversed.values[0][1], m_inversed.values[0][2]};
vector3f const edge1_abc{m_inversed.values[1][0], m_inversed.values[1][1], m_inversed.values[1][2]};
vector3f const edge2_abc{m_inversed.values[2][0], m_inversed.values[2][1], m_inversed.values[2][2]};
// 1/w function coefficients
//
vector3f const one_div_w_abc{vector3f{1.0f, 1.0f, 1.0f} *m_inversed};
// Calculate attributes coefficients
//
std::vector<vector3<color>> color_attrs_abc{binded_attributes.color_attributes.size()};
std::vector<vector3<float>> float_attrs_abc{binded_attributes.float_attributes.size()};
std::vector<vector3<vector2f>> vector2f_attrs_abc{binded_attributes.vector2f_attributes.size()};
std::vector<vector3<vector3f>> vector3f_attrs_abc{binded_attributes.vector3f_attributes.size()};
save_edges_coefficients<color>(
binded_attributes.color_attributes,
color_attrs_abc,
index0, index1, index2,
m_inversed);
save_edges_coefficients<float>(
binded_attributes.float_attributes,
float_attrs_abc,
index0, index1, index2,
m_inversed);
save_edges_coefficients<vector2f>(
binded_attributes.vector2f_attributes,
vector2f_attrs_abc,
index0, index1, index2,
m_inversed);
save_edges_coefficients<vector3f>(
binded_attributes.vector3f_attributes,
vector3f_attrs_abc,
index0, index1, index2,
m_inversed);
// Calculate bounding box
//
aabb<vector2ui> bounding_box;
if ((vertex0.w < FLOAT_EPSILON) || (vertex1.w < FLOAT_EPSILON) || (vertex2.w < FLOAT_EPSILON))
{
bounding_box.from = vector2ui{0, 0};
bounding_box.to = vector2ui{
static_cast<unsigned int>(target_texture.get_width()) - 1,
static_cast<unsigned int>(target_texture.get_height()) - 1};
}
else
{
float vertex0_screen_x{vertex0.x / vertex0.w};
vertex0_screen_x = clamp(vertex0_screen_x, 0.0f, static_cast<float>(target_texture.get_width()));
float vertex0_screen_y{vertex0.y / vertex0.w};
vertex0_screen_y = clamp(vertex0_screen_y, 0.0f, static_cast<float>(target_texture.get_height()));
float vertex1_screen_x{vertex1.x / vertex1.w};
vertex1_screen_x = clamp(vertex1_screen_x, 0.0f, static_cast<float>(target_texture.get_width()));
float vertex1_screen_y{vertex1.y / vertex1.w};
vertex1_screen_y = clamp(vertex1_screen_y, 0.0f, static_cast<float>(target_texture.get_height()));
float vertex2_screen_x{vertex2.x / vertex2.w};
vertex2_screen_x = clamp(vertex2_screen_x, 0.0f, static_cast<float>(target_texture.get_width()));
float vertex2_screen_y{vertex2.y / vertex2.w};
vertex2_screen_y = clamp(vertex2_screen_y, 0.0f, static_cast<float>(target_texture.get_height()));
bounding_box.from.x = static_cast<unsigned int>(std::min(std::min(vertex0_screen_x, vertex1_screen_x), vertex2_screen_x));
bounding_box.from.y = static_cast<unsigned int>(std::min(std::min(vertex0_screen_y, vertex1_screen_y), vertex2_screen_y));
bounding_box.to.x = static_cast<unsigned int>(std::max(std::max(vertex0_screen_x, vertex1_screen_x), vertex2_screen_x));
bounding_box.to.y = static_cast<unsigned int>(std::max(std::max(vertex0_screen_y, vertex1_screen_y), vertex2_screen_y));
}
for (unsigned int y{bounding_box.from.y}; y <= bounding_box.to.y; ++y)
{
vector2f const first_pixel_center{bounding_box.from.x + 0.5f, y + 0.5f};
float edge0_v{edge0_abc.x * first_pixel_center.x + edge0_abc.y * first_pixel_center.y + edge0_abc.z};
float edge1_v{edge1_abc.x * first_pixel_center.x + edge1_abc.y * first_pixel_center.y + edge1_abc.z};
float edge2_v{edge2_abc.x * first_pixel_center.x + edge2_abc.y * first_pixel_center.y + edge2_abc.z};
float one_div_w_v{one_div_w_abc.x * first_pixel_center.x + one_div_w_abc.y * first_pixel_center.y + one_div_w_abc.z};
for (unsigned int x{bounding_box.from.x}; x <= bounding_box.to.x; ++x)
{
vector2ui const p{x, y};
vector2f const pc{x + 0.5f, y + 0.5f};
// Because we're interested only in sign of p, and not the actual value, we can multiply instead of dividing, sign will be the same
//
if (is_point_on_positive_halfspace_top_left(edge0_v * one_div_w_v, edge0_abc.x, edge0_abc.y) &&
is_point_on_positive_halfspace_top_left(edge1_v * one_div_w_v, edge1_abc.x, edge1_abc.y) &&
is_point_on_positive_halfspace_top_left(edge2_v * one_div_w_v, edge2_abc.x, edge2_abc.y))
{
// Check if point is behind
//
if (one_div_w_v < 0.0f)
{
continue;
}
float const w_value{1.0f / one_div_w_v};
set_bind_points_values_from_edge_coefficients<color>(
binded_attributes.color_attributes,
color_attrs_abc,
pc,
w_value);
set_bind_points_values_from_edge_coefficients<float>(
binded_attributes.float_attributes,
float_attrs_abc,
pc,
w_value);
set_bind_points_values_from_edge_coefficients<vector2f>(
binded_attributes.vector2f_attributes,
vector2f_attrs_abc,
pc,
w_value);
set_bind_points_values_from_edge_coefficients<vector3f>(
binded_attributes.vector3f_attributes,
vector3f_attrs_abc,
pc,
w_value);
vector2ui const pixel_coordinates{p.x, p.y};
vector3f const sample_point{pc.x, pc.y, 0.0f};
delegate.process_rasterizing_stage_result(pixel_coordinates, sample_point, shader, target_texture);
}
edge0_v += edge0_abc.x;
edge1_v += edge1_abc.x;
edge2_v += edge2_abc.x;
one_div_w_v += one_div_w_abc.x;
}
}
}
// Inversed slope algorithm
//
/** Saves scanline endpoints attributes values into intermediate storage.
* It saves attribute value divided by view z for attributes with perspective correction instead of just linearly interpolated values
* @param binds List of binds
* @param top_vertex_index Index of a top vertex
* @param left_vertex_index Index of a left vertex
* @param right_vertex_index Index of a right vertex
* @param distance_from_top_to_left_normalized Current distance from a top vertex to a left vertex
* @param distance_from_top_to_right_normalized Current distance from a top vertex to a right vertex
* @param left_values_storage Storage to put left edge values into
* @param right_values_storage Storage to put right edge values into
* @param top_vertex_zview_reciprocal Camera space z for top vertex, required for perspective correction
* @param left_vertex_zview_reciprocal Camera space z for left vertex, required for perspective correction
* @param right_vertex_zview_reciprocal Camera space z for right vertex, required for perspective correction
*/
template<typename TAttr>
void rasterizing_stage::save_intermediate_attrs_values(
std::vector<binded_mesh_attribute_info<TAttr>> const& binds,
unsigned int const top_vertex_index,
unsigned int const left_vertex_index,
unsigned int const right_vertex_index,
float const distance_from_top_to_left_normalized,
float const distance_from_top_to_right_normalized,
std::vector<TAttr>& left_values_storage,
std::vector<TAttr>& right_values_storage,
float const top_vertex_zview_reciprocal,
float const left_vertex_zview_reciprocal,
float const right_vertex_zview_reciprocal)
{
size_t const binds_count{binds.size()};
for (size_t i{0}; i < binds_count; ++i)
{
binded_mesh_attribute_info<TAttr> const& binded_attr = binds[i];
std::vector<TAttr> const& binded_attr_data = binded_attr.info.get_data();
std::vector<unsigned int> const& binded_attr_indices = binded_attr.info.get_indices();
TAttr const& top_value = binded_attr_data[binded_attr_indices[top_vertex_index]];
TAttr const& left_value = binded_attr_data[binded_attr_indices[left_vertex_index]];
TAttr const& right_value = binded_attr_data[binded_attr_indices[right_vertex_index]];
if (binded_attr.info.get_interpolation_option() == attribute_interpolation_option::linear)
{
left_values_storage[i] = top_value * (1.0f - distance_from_top_to_left_normalized) + left_value * distance_from_top_to_left_normalized;
right_values_storage[i] = top_value * (1.0f - distance_from_top_to_right_normalized) + right_value * distance_from_top_to_right_normalized;
}
else
{
TAttr const& top_value_div_zview = top_value * top_vertex_zview_reciprocal;
TAttr const& left_value_div_zview = left_value * left_vertex_zview_reciprocal;
TAttr const& right_value_div_zview = right_value * right_vertex_zview_reciprocal;
left_values_storage[i] = top_value_div_zview * (1.0f - distance_from_top_to_left_normalized) + left_value_div_zview * distance_from_top_to_left_normalized;
right_values_storage[i] = top_value_div_zview * (1.0f - distance_from_top_to_right_normalized) + right_value_div_zview * distance_from_top_to_right_normalized;
}
}
}
/** Sets bind points values basing on scanline's endpoints and current position
* @param binds List of binds
* @param left_endpoint_values List of left endpoint values
* @param right_endpoint_values List of right endpoint values
* @param scanline_distance_normalized Current scanline distance from left endpoint to right endpoint
* @param zview_reciprocal_left Reciprocal of view z for left endpoint, required for attributes with perspective correction
* @param zview_reciprocal_right Reciprocal of view z for right endpoint, required for attributes with perspective correction
*/
template<typename TAttr>
void rasterizing_stage::set_bind_points_values_from_scanline_endpoints(
std::vector<binded_mesh_attribute_info<TAttr>> const& binds,
std::vector<TAttr> const& left_endpoint_values,
std::vector<TAttr> const& right_endpoint_values,
float const scanline_distance_normalized,
float const zview_reciprocal_left, float const zview_reciprocal_right)
{
size_t binds_count{binds.size()};
for (size_t i{0}; i < binds_count; ++i)
{
binded_mesh_attribute_info<TAttr> const& binded_attr = binds[i];
if (binded_attr.info.get_interpolation_option() == attribute_interpolation_option::linear)
{
TAttr const result =
left_endpoint_values[i] * (1.0f - scanline_distance_normalized) +
right_endpoint_values[i] * scanline_distance_normalized;
(*binded_attr.bind_point) = result;
}
else
{
TAttr const value_div_zview_interpolated = left_endpoint_values[i] * (1.0f - scanline_distance_normalized) + right_endpoint_values[i] * scanline_distance_normalized;
float const zview_reciprocal_interpolated = (1.0f - scanline_distance_normalized) * zview_reciprocal_left + scanline_distance_normalized * zview_reciprocal_right;
(*binded_attr.bind_point) = value_div_zview_interpolated * (1.0f / zview_reciprocal_interpolated);
}
}
}
inline float rasterizing_stage::get_next_pixel_center_exclusive(float const f)
{
return (std::floor(f + 0.5f) + 0.5f);
}
inline float rasterizing_stage::get_next_pixel_center_inclusive(float const f)
{
return (std::floor(f + (0.5f - FLOAT_EPSILON)) + 0.5f);
}
inline float rasterizing_stage::get_previous_pixel_center_exclusive(float const f)
{
return (std::floor(f - (0.5f + FLOAT_EPSILON)) + 0.5f);
}
template<typename TShader, typename TDelegate>
void rasterizing_stage::rasterize_inversed_slope(
vector4f const& vertex0, vector4f const& vertex1, vector4f const& vertex2,
unsigned int const index0, unsigned int const index1, unsigned int const index2,
TShader& shader,
binded_mesh_attributes const& binded_attributes,
texture& target_texture,
TDelegate& delegate)
{
// Sort vertices by y-coordinate
//
vector4f vertex0_sorted{vertex0};
vector4f vertex1_sorted{vertex1};
vector4f vertex2_sorted{vertex2};
unsigned int index0_sorted{index0};
unsigned int index1_sorted{index1};
unsigned int index2_sorted{index2};
if (vertex1_sorted.y < vertex0_sorted.y)
{
std::swap(vertex0_sorted, vertex1_sorted);
std::swap(index0_sorted, index1_sorted);
}
if (vertex2_sorted.y < vertex1_sorted.y)
{
std::swap(vertex2_sorted, vertex1_sorted);
std::swap(index2_sorted, index1_sorted);
}
if (vertex1_sorted.y < vertex0_sorted.y)
{
std::swap(vertex1_sorted, vertex0_sorted);
std::swap(index1_sorted, index0_sorted);
}
// vertex0 is top vertex
// vertex2 is bottom vertex
// Check if it's a top, bottom or custom triangle
//
if (std::abs(vertex1_sorted.y - vertex2_sorted.y) < FLOAT_EPSILON)
{
// Top triangle
//
if (vertex2_sorted.x < vertex1_sorted.x)
{
std::swap(vertex2_sorted, vertex1_sorted);
std::swap(index2_sorted, index1_sorted);
}
rasterize_inverse_slope_top_or_bottom_triangle(
vertex0_sorted, vertex1_sorted, vertex2_sorted,
index0_sorted, index1_sorted, index2_sorted,
0.0f, 0.0f,
shader,
binded_attributes,
target_texture,
delegate);
}
else if (std::abs(vertex0_sorted.y - vertex1_sorted.y) < FLOAT_EPSILON)
{
// Bottom triangle
//
if (vertex1_sorted.x < vertex0_sorted.x)
{
std::swap(vertex1_sorted, vertex0_sorted);
std::swap(index1_sorted, index0_sorted);
}
rasterize_inverse_slope_top_or_bottom_triangle(
vertex2_sorted, vertex0_sorted, vertex1_sorted,
index2_sorted, index0_sorted, index1_sorted,
0.0f, 0.0f,
shader,
binded_attributes,
target_texture,
delegate);
}
else
{
// Line that divides triangle into top and bottom
line const separator_line{vertex1_sorted.x, vertex1_sorted.y, vertex1_sorted.x + 1.0f, vertex1_sorted.y};
// Calculate intersection point
vector2f const intersection{separator_line.intersection(line{vertex0_sorted.x, vertex0_sorted.y, vertex2_sorted.x, vertex2_sorted.y})};
// Distance in pixels from top vertex to intersection vertex and from top vertex to bottom vertex on the same edge
// We need these because when we interpolate attributes across edge we need to know real edge length,
// even though we draw top and bottom triangles separately
//
float const distance_to_separator_vertex{vector2f{vertex0_sorted.x, vertex0_sorted.y}.distance_to(intersection)};
float const total_edge_with_separator_vertex_length{vector2f{vertex2_sorted.x, vertex2_sorted.y}.distance_to(vector2f{vertex0_sorted.x, vertex0_sorted.y})};
// Vertices that lie on separating line
// We need two different vectors because we do not calculate interpolated values of z and w and use just distance offset
//
vector4f separator_vertex_for_top_triangle{intersection.x, intersection.y, vertex2.z, vertex2.w};
vector4f separator_vertex_for_bottom_triangle{intersection.x, intersection.y, vertex0.z, vertex0.w};
// Draw top triangle
rasterize_inverse_slope_top_or_bottom_triangle(
vertex0_sorted, separator_vertex_for_top_triangle, vertex1_sorted,
index0_sorted, index2_sorted, index1_sorted,
total_edge_with_separator_vertex_length - distance_to_separator_vertex, 0.0f,
shader,
binded_attributes,
target_texture,
delegate);
// Draw bottom triangle
rasterize_inverse_slope_top_or_bottom_triangle(
vertex2_sorted, separator_vertex_for_bottom_triangle, vertex1_sorted,
index2_sorted, index0_sorted, index1_sorted,
distance_to_separator_vertex, 0.0f,
shader,
binded_attributes,
target_texture,
delegate);
}
}
template<typename TShader, typename TDelegate>
void rasterizing_stage::rasterize_inverse_slope_top_or_bottom_triangle(
vector4f& vertex0, vector4f& vertex1, vector4f& vertex2,
unsigned int index0, unsigned int index1, unsigned int index2,
float v0_v1_edge_distance_offset, float v0_v2_edge_distance_offset,
TShader& shader,
binded_mesh_attributes const& binded_attributes,
texture& target_texture,
TDelegate& delegate)
{
// Sort vertices on horizontal edge by their x-coordinate
//
if (vertex1.x > vertex2.x)
{
std::swap(vertex1, vertex2);
std::swap(index1, index2);
std::swap(v0_v1_edge_distance_offset, v0_v2_edge_distance_offset);
}
// True = current triangle is a top triangle (vertex0.y < vertex1.y, vertex0.y < vertex2.y)
bool const is_top_triangle{vertex0.y < vertex1.y};
// Direction coefficient
int const y_order_coefficient{is_top_triangle ? 1 : -1};
// Left edge length
float const left_total_distance{vector2f{vertex0.x, vertex0.y}.distance_to(vector2f{vertex1.x, vertex1.y}) + v0_v1_edge_distance_offset};
// Right edge length
float const right_total_distance{vector2f{vertex0.x, vertex0.y}.distance_to(vector2f{vertex2.x, vertex2.y}) + v0_v2_edge_distance_offset};
// For how many x's we move on the left edge for one y
float const inversed_slope_left{(vertex0.x - vertex1.x) / (vertex0.y - vertex1.y) * y_order_coefficient};
// For how many x's we move on the right edge for one y
float const inversed_slope_right{(vertex0.x - vertex2.x) / (vertex0.y - vertex2.y) * y_order_coefficient};
// Percent of left edge's length we pass when we increase y by one
float const left_distance_step_normalized{std::sqrt(1.0f + inversed_slope_left * inversed_slope_left) / left_total_distance};
// Percent of right edge's length we pass when we increase y by one
float const right_distance_step_normalized{std::sqrt(1.0f + inversed_slope_right * inversed_slope_right) / right_total_distance};
// Find next pixel center (if vertex0 is on the center already, move to the next pixel according to the top-left rule)
float const next_y_pixel_center{is_top_triangle ? get_next_pixel_center_exclusive(vertex0.y) : get_previous_pixel_center_exclusive(vertex0.y)};
// Calculate offset from the top to the next pixel center
float const next_y_pixel_center_delta{std::abs(next_y_pixel_center - vertex0.y)};
if ((next_y_pixel_center < 0.0f) || (next_y_pixel_center > target_texture.get_height()))
{
// If first scanline y coordinate is negative - we do not process a triangle
// Because either it wasn't clipped or it does not occupy any pixel center (along y axis) in a texture
return;
}
// Calculate last pixel y coordinate
float const last_y_pixel_center{is_top_triangle ? get_previous_pixel_center_exclusive(vertex1.y) : get_next_pixel_center_inclusive(vertex1.y)};
if ((last_y_pixel_center < 0.0f) || (last_y_pixel_center > target_texture.get_height()))
{
// If first scanline y coordinate is negative - we do not process a triangle
// Because either it wasn't clipped or it does not occupy any pixel center (along y axis) in a texture
return;
}
// Calculate starting left distance considering offset to the next y pixel center
float current_left_distance_normalized{left_distance_step_normalized * next_y_pixel_center_delta};
// Calculate starting right distance considering offset to the next y pixel center
float current_right_distance_normalized{right_distance_step_normalized * next_y_pixel_center_delta};
// Calculate first scanline endpoints considering offset the next y pixel center
//
float x_left{vertex0.x + inversed_slope_left * next_y_pixel_center_delta};
float x_right{vertex0.x + inversed_slope_right * next_y_pixel_center_delta};
// Calculate first and last scanlines integer y-coordinates
int const first_y{static_cast<int>(next_y_pixel_center)};
int const last_y{static_cast<int>(last_y_pixel_center) + y_order_coefficient};
// Initialize attributes storage
//
size_t color_binds_count{binded_attributes.color_attributes.size()};
std::vector<color> left_color_attributes(color_binds_count);
std::vector<color> right_color_attributes(color_binds_count);
size_t float_binds_count{binded_attributes.float_attributes.size()};
std::vector<float> left_float_attributes(float_binds_count);
std::vector<float> right_float_attributes(float_binds_count);
size_t vector2f_binds_count{binded_attributes.vector2f_attributes.size()};
std::vector<vector2f> left_vector2f_attributes(vector2f_binds_count);
std::vector<vector2f> right_vector2f_attributes(vector2f_binds_count);
size_t vector3f_binds_count{binded_attributes.vector3f_attributes.size()};
std::vector<vector3f> left_vector3f_attributes(vector3f_binds_count);
std::vector<vector3f> right_vector3f_attributes(vector3f_binds_count);
// For each scanline
//
for (int y{first_y}; y != last_y; y += y_order_coefficient)
{
// Calculate attributes values on scanline endpoints
//
save_intermediate_attrs_values<color>(
binded_attributes.color_attributes,
index0, index1, index2,
current_left_distance_normalized, current_right_distance_normalized,
left_color_attributes, right_color_attributes,
vertex0.w, vertex1.w, vertex2.w);
save_intermediate_attrs_values<float>(
binded_attributes.float_attributes,
index0, index1, index2,
current_left_distance_normalized, current_right_distance_normalized,
left_float_attributes, right_float_attributes,
vertex0.w, vertex1.w, vertex2.w);
save_intermediate_attrs_values<vector2f>(
binded_attributes.vector2f_attributes,
index0, index1, index2,
current_left_distance_normalized, current_right_distance_normalized,
left_vector2f_attributes, right_vector2f_attributes,
vertex0.w, vertex1.w, vertex2.w);
save_intermediate_attrs_values<vector3f>(
binded_attributes.vector3f_attributes,
index0, index1, index2,
current_left_distance_normalized, current_right_distance_normalized,
left_vector3f_attributes, right_vector3f_attributes,
vertex0.w, vertex1.w, vertex2.w);
// Length of the scanline
float const total_scanline_distance{x_right - x_left};
// Length we move for each x step
float const scanline_step_distance_normalized{1.0f / total_scanline_distance};
// Calculate first pixel center we start from, according to top-left rule
float const x_left_next_pixel_center{get_next_pixel_center_inclusive(x_left)};
if (x_left_next_pixel_center < 0.0f)
{
continue;
}
// Calculate last pixel center
float last_x_pixel_center{get_previous_pixel_center_exclusive(x_right)};
if (last_x_pixel_center < 0.0f)
{
continue;
}
// Calculate current scanline distance, taking into account starting left pixel offset
float current_scanline_distance_normalized{(x_left_next_pixel_center - x_left) * scanline_step_distance_normalized};
int const first_x{static_cast<int>(x_left_next_pixel_center)};
int const last_x{static_cast<int>(last_x_pixel_center)};
// Calculate endpoints interpolated z reciprocals
//
float const left_zview_reciprocal = (1.0f - current_left_distance_normalized) * vertex0.w + current_left_distance_normalized * vertex1.w;
float const right_zview_reciprocal = (1.0f - current_right_distance_normalized) * vertex0.w + current_right_distance_normalized * vertex2.w;
for (int x{first_x}; x <= last_x; ++x)
{
// Calculate attributes values on current pixel center
//
set_bind_points_values_from_scanline_endpoints<color>(
binded_attributes.color_attributes,
left_color_attributes, right_color_attributes,
current_scanline_distance_normalized,
left_zview_reciprocal, right_zview_reciprocal);
set_bind_points_values_from_scanline_endpoints<float>(
binded_attributes.float_attributes,
left_float_attributes, right_float_attributes,
current_scanline_distance_normalized,
left_zview_reciprocal, right_zview_reciprocal);
set_bind_points_values_from_scanline_endpoints<vector2f>(
binded_attributes.vector2f_attributes,
left_vector2f_attributes, right_vector2f_attributes,
current_scanline_distance_normalized,
left_zview_reciprocal, right_zview_reciprocal);
set_bind_points_values_from_scanline_endpoints<vector3f>(
binded_attributes.vector3f_attributes,
left_vector3f_attributes, right_vector3f_attributes,
current_scanline_distance_normalized,
left_zview_reciprocal, right_zview_reciprocal);
vector2ui const pixel_coordinates{static_cast<unsigned int>(x), static_cast<unsigned int>(y)};
vector3f const sample_point{x + 0.5f, y + 0.5f, 0.0f};
delegate.process_rasterizing_stage_result(pixel_coordinates, sample_point, shader, target_texture);
current_scanline_distance_normalized += scanline_step_distance_normalized;
}
// Move to the next scanline
//
x_left += inversed_slope_left;
x_right += inversed_slope_right;
current_left_distance_normalized += left_distance_step_normalized;
current_right_distance_normalized += right_distance_step_normalized;
}
}
}
#endif // LANTERN_RASTERIZING_STAGE_H | true |
a67ef7ec2e54d47f5d01e1e78de3c3e36a71046c | C++ | miguelraz/PathToPerformance | /Dojo/C++ Programming Practices and Principles - Stroustrup/ch5/trythistemperaturerevamped.cpp | UTF-8 | 766 | 3.515625 | 4 | [
"MIT"
] | permissive | //5.trythis temperature improved
#include "std_lib_facilities.h"
#include <vector>
#include <iostream>
using namespace std;
int main() {
double sum = 0;
double low_temp = 128 * -1; // initialize to impossibly low aka vostok
double high_temp = 136 ; // initialize to “impossibly high” aka dubai march 30 2017
int no_of_temps = 0;
for (double temp; cin >> temp; ) { // read temp
++no_of_temps; // count temperatures
sum += temp; // compute sum
if (temp > high_temp) high_temp = temp; // find high
if (temp < low_temp) low_temp = temp; // find low
}
cout << "High temperature: " << high_temp << '\n';
cout << "Low temperature: " << low_temp << '\n';
cout << "Average temperature: " << sum / no_of_temps << '\n';
}
| true |
577831c82ca8e388b68f53d41e032528b6fe2cec | C++ | inlart/SAToku | /satoku/satoku/sudokusolver.cpp | UTF-8 | 3,590 | 2.96875 | 3 | [
"MIT"
] | permissive | #include "satoku/sudokusolver.h"
#include <cmath>
namespace satoku {
SudokuSolver::SudokuSolver(const Sudoku& sudoku) : m_sudoku(sudoku) {
updateClauses();
}
std::size_t SudokuSolver::getVariableNumber(std::pair<std::size_t, std::size_t> pos,
std::int64_t val) const noexcept {
auto size = m_sudoku.getSize();
return (pos.first * size + pos.second) * size + val;
}
void SudokuSolver::updateClauses() {
std::vector<CMSat::Lit> clause;
auto size = m_sudoku.getSize();
// -- at least one number
for(int i = 0; i < size; ++i) {
for(int j = 0; j < size; ++j) {
clause.clear();
for(int k = 0; k < size; ++k) {
clause.push_back(CMSat::Lit(getVariableNumber({i, j}, k), false));
}
m_clauses.push_back(clause);
}
}
// -- at most one number
for(int i = 0; i < size; i++) {
for(int j = 0; j < size; ++j) {
for(int k = 0; k < size; k++) {
for(int l = k + 1; l < size; l++) {
clause.clear();
clause.push_back(CMSat::Lit(getVariableNumber({i, j}, k), true));
clause.push_back(CMSat::Lit(getVariableNumber({i, j}, l), true));
m_clauses.push_back(clause);
}
}
}
}
// -- one in a row
for(int i = 0; i < size; i++) {
for(int j = 0; j < size; ++j) {
for(int k = 0; k < size; k++) {
for(int l = k + 1; l < size; l++) {
clause.clear();
clause.push_back(CMSat::Lit(getVariableNumber({i, k}, j), true));
clause.push_back(CMSat::Lit(getVariableNumber({i, l}, j), true));
m_clauses.push_back(clause);
}
}
}
}
// -- one in a column
for(int i = 0; i < size; i++) {
for(int j = 0; j < size; j++) {
for(int k = 0; k < size; k++) {
for(int l = k + 1; l < size; l++) {
clause.clear();
clause.push_back(CMSat::Lit(getVariableNumber({k, i}, j), true));
clause.push_back(CMSat::Lit(getVariableNumber({l, i}, j), true));
m_clauses.push_back(clause);
}
}
}
}
// -- one in a block
std::int64_t blockLength = std::sqrt(size);
for(int a = 0; a < size; a += blockLength) {
for(int b = 0; b < size; b += blockLength) {
//[a,b] is the first element in the block
for(int num = 0; num < size; num++) {
for(int i = a; i < a + blockLength; i++) {
for(int j = b; j < b + blockLength; j++) {
for(int k = a; k < a + blockLength; k++) {
for(int l = b; l < b + blockLength; l++) {
if(i == k || j == l)
continue;
clause.clear();
clause.push_back(CMSat::Lit(getVariableNumber({i, j}, num), true));
clause.push_back(CMSat::Lit(getVariableNumber({k, l}, num), true));
m_clauses.push_back(clause);
}
}
}
}
}
}
}
// -- set values
for(int i = 0; i < size; i++) {
for(int j = 0; j < size; j++) {
auto val = m_sudoku[{i, j}];
if(val) {
clause.clear();
clause.push_back(CMSat::Lit(getVariableNumber({i, j}, val.value() - 1), false));
m_clauses.push_back(clause);
}
}
}
}
std::optional<SolvedSudoku> SudokuSolver::solve() noexcept {
CMSat::SATSolver solver;
solver.new_vars(getVariableNumber({m_sudoku.getSize(), 0}, 0));
for(auto&& clause : m_clauses) {
solver.add_clause(clause);
}
auto ret = solver.solve();
if(ret == CMSat::l_True) {
auto size = m_sudoku.getSize();
SolvedSudoku result(size);
for(int i = 0; i < size; ++i) {
for(int j = 0; j < size; ++j) {
for(int k = 0; k < size; ++k) {
if(solver.get_model()[getVariableNumber({i, j}, k)] == CMSat::l_True) {
result[{i, j}] = k + 1;
}
}
}
}
m_solutions.push_back(result);
return result;
}
return {};
}
} // namespace satoku
| true |
ea86cb49360b2db059fae6655f922dbd3e681ea6 | C++ | QTAnt/Exercise | /Merging_two_ordered_linked_lists/Merging_two_ordered_linked_lists.cpp | GB18030 | 1,101 | 3.65625 | 4 | [] | no_license | //Merging_two_ordered_linked_listsϲ
//https://leetcode-cn.com/problems/merge-two-sorted-lists/
//ϲΪһµءͨƴӸнڵɵġ
//ʾ
//룺1->2->4, 1->3->4
//1->1->2->3->4->4
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
if (l1 == NULL) return l2;//һΪֱӷһ
if (l2 == NULL) return l1;
ListNode* p = l1;
ListNode* q = l2;
ListNode* start = l1->val<l2->val ? l1 : l2;
do{
if (q->val <= p->val){
while (q->next != NULL&&q->next->val <= p->val)
q = q->next;
l2 = q->next;
q->next = p;
}
else
{
while (p->next != NULL&&p->next->val<q->val)
p = p->next;
l2 = q->next;
q->next = p->next;
p->next = q;
}
q = l2;
} while (q != NULL);
return start;
}
}; | true |
732c96fa29dc6b91f62ef6b099e9daa21288fcfb | C++ | Crawping/Cyclone | /Utilities/Graphs/Specializations/BinaryNode.h | UTF-8 | 4,146 | 3.453125 | 3 | [] | no_license | /* CHANGELOG
* Written by Josh Grooms on 20170708
*/
#pragma once
namespace Cyclone
{
namespace Utilities
{
/// <summary> A structure that represents a generic graph node. </summary>
/// <typeparam name="T"> The type of the data element held by the node. </typeparam>
/// <typeparam name="N"> A list of integers that define the dimensionality and degree of the node's adjacency array. </typeparam>
template<typename T> struct Node<T, 2>
{
/** STATIC DATA **/
/// <summary> The number of connections that could be formed with other nodes. </summary>
constexpr const static uint Degree = 2;
/// <summary> The number of dimensions present in the array that holds adjacent nodes. </summary>
constexpr const static uint Rank = 1;
private:
Array<Node*, 2> _adjacencies;
T _value;
public:
/** PROPERTIES **/
constexpr Node*& Left() { return operator ()(0); }
constexpr const Node*& Left() const { return operator ()(0); }
constexpr Node*& Right() { return operator ()(1); }
constexpr const Node*& Right() const { return operator ()(1); }
constexpr T& Value() { return _value; }
/// <summary> Gets the value of the data element stored within the node. </summary>
constexpr const T& Value() const { return _value; }
/// <summary> Sets the value of the data element stored within the node. </summary>
template<typename U> Node& Value(U&& value)
{
_value = std::forward<U>(value);
return *this;
}
/** CONSTRUCTORS **/
/// <summary> Constructs a new empty graph node. </summary>
constexpr Node():
_adjacencies { nullptr },
_value()
{
}
/// <summary> Constructs a new graph node containing a particular data value. </summary>
/// <param name="value"> The data value to be stored in the node. </param>
template<typename U> constexpr Node(U&& value):
_adjacencies { nullptr },
_value(std::forward<U>(value))
{
}
/** OPERATORS **/
/// <summary> Gets the adjacent node stored at a particular index. </summary>
/// <typeparam name="U"> A list of unsigned 32-bit integers. </typeparam>
/// <param name="subscripts"> A single linear index, or a list of array subscripts. </param>
template<typename ... U>
constexpr auto& operator ()(U ... subscripts) { return _adjacencies(subscripts...); }
/// <summary> Gets the adjacent node stored at a particular index. </summary>
/// <typeparam name="U"> A list of unsigned 32-bit integers. </typeparam>
/// <param name="subscripts"> A single linear index, or a list of array subscripts. </param>
template<typename ... U>
constexpr const auto& operator ()(U ... subscripts) const { return _adjacencies(subscripts...); }
/// <summary> Gets the adjacent node stored at a particular multidimensional index. </summary>
/// <param name="subscripts"> An array of subscripts that index into the node. </param>
constexpr auto& operator ()(const Array<uint, Rank>& subscripts)
{
return _adjacencies( _adjacencies.IndexOf(subscripts) );
}
constexpr const auto& operator ()(const Array<uint, Rank>& subscripts) const
{
return _adjacencies( _adjacencies.IndexOf(subscripts) );
}
};
template<typename T> using BinaryNode = Node<T, 2>;
}
}
| true |
a7fc50237415013052cd522dd06625bb2c2d7bd7 | C++ | Juice-2020/Implied-Tree-Pricer | /code/bsformula.h | UTF-8 | 1,406 | 3.03125 | 3 | [] | no_license | //
// BSformula.h
// Implied Tree
//
// Created by 陈家豪 on 2020/4/13.
// Copyright © 2020 陈家豪. All rights reserved.
//
#ifndef BSformula_h
#define BSformula_h
#include <iostream>
#include <cmath> // for std::exp()
#include <cassert> // for assertion on inputs
enum OptType{C, P};
double cnorm(double x);
double bsformula(OptType optType,double K,double T, double S_0,double sigma,double rate,double q)
{
double sigmaSqrtT = sigma * std::sqrt(T);
double d1 = (std::log(S_0 / K) + (rate-q) * T)/sigmaSqrtT + 0.5 * sigmaSqrtT;
double d2 = d1 - sigmaSqrtT;
double V_0;
switch (optType)
{
case C:
V_0 = S_0 *exp(-q*T)* cnorm(d1) - K * exp(-rate*T) * cnorm(d2);
break;
case P:
V_0 = K * exp(-rate*T) * cnorm(-d2) - S_0 *exp(-q*T)* cnorm(-d1);
break;
default:
throw "unsupported optionType";
}
// std::cout << "The--"<< optType << " --option price is " << V_0 << std::endl;
return V_0;
}
double cnorm(double x)
{
// constants
double a1 = 0.254829592;
double a2 = -0.284496736;
double a3 = 1.421413741;
double a4 = -1.453152027;
double a5 = 1.061405429;
double p = 0.3275911;
int sign = 1;
if (x < 0)
sign = -1;
x = fabs(x)/sqrt(2.0);
double t = 1.0/(1.0 + p*x);
double y = 1.0 - (((((a5*t + a4)*t) + a3)*t + a2)*t + a1)*t*exp(-x*x);
return 0.5*(1.0 + sign*y);
}
#endif /* BSformula_h */
| true |
f60df62bf7f6e8b8165db07b52410ec0bd9903c8 | C++ | maximechoulika/My42Cursus | /piscine_cpp/project/source/Tilemap.cpp | UTF-8 | 1,797 | 2.796875 | 3 | [] | no_license | #include "Tilemap.hpp"
#include "Vars.hpp"
#include "Operations.hpp"
#include <fstream>
#define TILE_SIZE 32u
#define TILES_PER_LINE 16u
Tilemap::Tilemap()
{
m_texture.loadFromFile("data/tilemap/tileset.png");
std::ifstream file("data/tilemap/tilemap");
std::string line;
std::getline(file, line);
unsigned int s = toNumber(line);
m_vertices.resize(s * s * 4);
m_vertices.setPrimitiveType(sf::Quads);
unsigned int posX = 0, posY = 0, index = 0;
for(std::string temp; std::getline(file, line); posY += TILE_SIZE)
{
for(unsigned int i = 0; i != line.size(); ++i)
{
if(line[i] != ',')
{
temp += line[i];
}
else
{
unsigned int nb = toNumber(temp);
sf::Vector2f texCoords((nb & (TILES_PER_LINE - 1)) * TILE_SIZE, nb / TILES_PER_LINE * TILE_SIZE);
sf::Vertex* quad = &(m_vertices[index]);
quad[0].position = sf::Vector2f(posX, posY);
quad[1].position = sf::Vector2f(posX + TILE_SIZE, posY);
quad[2].position = sf::Vector2f(posX + TILE_SIZE, posY + TILE_SIZE);
quad[3].position = sf::Vector2f(posX, posY + TILE_SIZE);
quad[0].texCoords = texCoords;
quad[1].texCoords = sf::Vector2f(texCoords.x + TILE_SIZE, texCoords.y);
quad[2].texCoords = texCoords + sf::Vector2f(TILE_SIZE, TILE_SIZE);
quad[3].texCoords = sf::Vector2f(texCoords.x, texCoords.y + TILE_SIZE);
posX += TILE_SIZE;
index += 4;
temp.clear();
}
}
posX = 0;
}
}
void Tilemap::render() const
{
window.draw(m_vertices, &m_texture);
}
| true |
c8d7ec14d00816e6f76ae201136d26498b396a78 | C++ | sw1024/testcpp | /logcxx.cpp | UTF-8 | 2,605 | 2.625 | 3 | [] | no_license | /**
* @file logcxx.cpp
* $Id$
* @brief
* @author My name SunWu
* @date 2019-05-04
*/
#include <iostream>
#include <stdarg.h>
#include <log4cxx/logger.h>
#include <log4cxx/dailyrollingfileappender.h>
#include <log4cxx/propertyconfigurator.h>
#include <log4cxx/helpers/exception.h>
#include <log4cxx/patternlayout.h>
#include <log4cxx/consoleappender.h>
#include <log4cxx/helpers/dateformat.h>
#include <log4cxx/helpers/stringhelper.h>
#include <log4cxx/helpers/loglog.h>
#include <log4cxx/helpers/system.h>
#include <sys/stat.h>
#include <time.h>
#include <unistd.h>
#include <string.h>
#include <log4cxx/rollingfileappender.h>
#include <log4cxx/rolling/rollingfileappender.h>
#define MSGBUF_MAX 4096
log4cxx::LoggerPtr logger;
char message[MSGBUF_MAX];
void addConsoleLog()
{
log4cxx::helpers::Pool p;
log4cxx::PatternLayoutPtr cpl = new log4cxx::PatternLayout("\%d{\%y\%m\%d-\%H:\%M:\%S }%c %5p: %m%n");
cpl->activateOptions(p);
log4cxx::ConsoleAppenderPtr carp = new log4cxx::ConsoleAppender(cpl);
carp->activateOptions(p);
carp->setName("console");
logger->addAppender(carp);
}
void removeConsoleLog()
{
auto ap = logger->getAppender("console");
if (ap) {
logger->removeAppender(ap);
ap->close();
}
}
void addLocalFileLog(const std::string& file)
{
log4cxx::helpers::Pool p;
log4cxx::PatternLayoutPtr cpl = new log4cxx::PatternLayout("\%d{\%y\%m\%d-\%H:\%M:\%S }%c %5p: %m%n");
cpl->activateOptions(p);
//log4cxx::RollingFileAppenderPtr rfa( new log4cxx::RollingFileAppender());
log4cxx::DailyRollingFileAppenderPtr rfa( new log4cxx::DailyRollingFileAppender());
rfa->setName("localfile" +file);
rfa->setLayout(cpl);
rfa->setAppend(false);
rfa->setFile(LOG4CXX_STR("./ivylog.log"));
rfa->setDatePattern(LOG4CXX_STR("'.'yyyy-MM-dd-HH-mm"));
rfa->activateOptions(p);
logger->addAppender(rfa);
}
void removeLocalFileLog(const std::string& file)
{
auto ap = logger->getAppender("localfile:"+file);
if (ap) {
logger->removeAppender(ap);
ap->close();
}
}
#define getMessage(msg,msglen,pat) \
do \
{ \
va_list ap; \
bzero(msg, msglen); \
va_start(ap, pat); \
vsnprintf(msg, msglen - 1, pat, ap); \
va_end(ap); \
}while(false)
bool debug(const char * pattern, ...)
{
getMessage(message,MSGBUF_MAX,pattern);
logger->debug(message);
return true;
}
int main()
{
logger = log4cxx::Logger::getLogger("Ivy");
logger->setLevel(log4cxx::Level::getDebug());
addConsoleLog();
addLocalFileLog("testlog");
int i = 0;
while(true) {
debug("hello world: %d", ++i);
sleep(10);
}
removeLocalFileLog("testlog");
removeConsoleLog();
return 0;
}
| true |
68418240e7029e3d588eff683032e4a4e22e513d | C++ | flohmann/Inf3Project | /ContractTest/Dijkstra_Pathfinding_Algorithm/Graph.cpp | UTF-8 | 1,133 | 3.1875 | 3 | [] | no_license |
#pragma once
#include "stdafx.h"
#include <vector>
#include "Graph.h"
using namespace std;
Graph::Graph()
{
}
void Graph::addNodes(Node n)
{
if (&n == nullptr)
{
nodeList.push_back(n);
}
}
bool Graph::hasNodes(Node n){
if (&n != NULL){
for each (Node node in nodeList)
{
if (node == n){
isNode = true;
}
}
}
return isNode;
}
int Graph::getAmount(){
return nodeList.size();
}
Node Graph::getNode(int x, int y){
Node* n;
unsigned i = 0;
while (i < nodeList.size() && n == nullptr) {
if ((nodeList[i].getX() == x) && (nodeList[i].getY() == y)) {
n = &nodeList[i];
}
}
return *n;
/*for (Node node : nodeList){
if ((node.getX() == x) && (node.getY() == y)) {
return node;
}
}
return ;*/
//
}
std::vector<Node> Graph::getNodes(){
return nodeList;
}
int Graph::getSize(){
int max = 0;
for (Node node : nodeList){
if (node.getSize() > max){
max = node.getSize();
}
}
return max;
}
void Graph::setNodes(std::vector<Node> list){
if ((&list == NULL) || list.size() < 1){
printf("seNodes: invalid Liste");
}
nodeList = list;
}
Graph::~Graph()
{
delete &nodeList;
}
| true |
b7db5c32dd53a5f872bf75a76f6695183b469133 | C++ | LuaXD/teambook | /teambook/string/SuffixAutomata.cpp | UTF-8 | 6,413 | 2.671875 | 3 | [] | no_license | #include <iostream>
#include <string.h>
#include <algorithm>
#include <stdio.h>
#include <vector>
typedef long long int number;
using namespace std;
const int INSERTE_VALOR = 90050;
vector<int> alpha;
/*################### Suffix Automata ###################*/
const int N = INSERTE_VALOR;//maxima longitud de la cadena
struct State { //OJO!!! tamanio del alfabeto, si MLE -> map
State *pre,*go[26];//se puede usar un map<char, State*> go
int step;
void clear() {
pre=0;
step=0;
memset(go,0,sizeof(go));//go.clear();
}
} *root,*last;
State statePool[N * 2],*cur;
void init() {
cur=statePool;
root=last=cur++;
root->clear();
}
void Insert(int w) {
State *p=last;
State *np=cur++;
np->clear();
np->step=p->step+1;
while(p&&!p->go[w])
p->go[w]=np,p=p->pre;
if(p==0)
np->pre=root;
else {
State *q=p->go[w];
if(p->step+1==q->step)
np->pre=q;
else {
State *nq=cur++;
nq->clear();
memcpy(nq->go,q->go,sizeof(q->go));//nq->go = q->go; para mapa
nq->step=p->step+1;
nq->pre=q->pre;
q->pre=nq;
np->pre=nq;
while(p&&p->go[w]==q)
p->go[w]=nq, p=p->pre;
}
}
last=np;
}
/*################### Suffix Automata ###################*/
/*################### Algunas aplicaciones ###################*/
//Obtiene el LCSubstring de 2 cadenas en O(|A| + |B|)
string lcs(char A[N], char B[N]) {
int n,m;
n = strlen(A); m = strlen(B);
//Construccion: O(|A|)
//solo hacerlo una vez si A no cambia
init();
for(int i=0; i<n; i++)
Insert(A[i]-'a'); //Fin construccion
//LCS: O(|B|)
int ans = 0, len = 0, bestpos = 0;
State *p = root;
for(int i = 0; i < m; i++) {
int x = B[i]-'a';
if(p->go[x]) {
len++;
p = p->go[x];
} else {
while (p && !p->go[x]) p = p->pre;
if(!p) p = root, len = 0;
else len = p->step+1, p = p->go[x];
}
if (len > ans)
ans = len, bestpos = i;
}
//return ans; //solo el tamanio del lcs
return string(B + bestpos - ans + 1, B + bestpos + 1);
}
/*Numero de subcadenas distintas + 1(subcadena vacia) en O(|A|)
OJO: Por alguna razon Suffix Array es mas rapido
Se reduce a contar el numero de paths que inician en q0 y terminan
en cualquier nodo. dp[u] = # de paths que inician en u
- Se debe construir el automata en el main(init y Insert's)
- Setear dp en -1
*/
number dp[N * 2];
number num_dist_substr(State *u = root) {
if (dp[u - statePool] != -1) return dp[u - statePool];
number ans = 1;//el path vacio que representa este nodo
for (int v = 0; v < 26; v++)//usar for (auto) para mapa
if (u->go[v])
ans += num_dist_substr(u->go[v]);
return (dp[u - statePool] = ans);
}
/*Suma la longitud de todos los substrings en O(|A|)
- Construir el automata(init y insert's)
- Necesita el metodo num_dist_substr (el de arriba)
- setear dp's en -1
*/
number dp1[N * 2];
number sum_length_dist_substr(State *u = root) {
if (dp1[u - statePool] != -1) return dp1[u - statePool];
number ans = 0;//el path vacio que representa este nodo
for (int v = 0; v < 26; v++)//usar for (auto) para mapa
if (u->go[v])
ans += (num_dist_substr(u->go[v]) + sum_length_dist_substr(u->go[v]));
return (dp1[u - statePool] = ans);
}
/*
Pregunta si p es subcadena de la cadena con la cual esta construida
el automata.
Complejidad: - Construir O(|Texto|) - solo una vez (init e insert's)
- Por Consulta O(|patron a buscar|)
*/
bool is_substring(char p[N]) {
State *u = root;
for (int i = 0; p[i]; i++) {
if (!u->go.count(p[i]))//esta con map!!!
return false;
u = u->go[p[i]];//esta con map!!!
}
return true;
}
/*####################################################################*/
//EL RESTO ESTA SIN PROBAR
/*
number K;
string ans = "";
number path;
void kth_lex_substring(State *u = root) {
for (int v = 0; v < 26; v++)
if (u->go[v]) {
path++;
if (path == K) {
ans.push_back('a' + v);
return;
}
kth_lex_substring(u->go[v]);
if (path == K) {
ans.push_back('a' + v);
return;
}
}
}*/
char A[N],B[N];
int main() {
/*
//LCS de 2 cadenas
//Ej: https://www.codechef.com/problems/SSTORY
scanf("%s%s",A,B);
string ans = lcs(A, B);
if (ans.size() > 0)
printf("%s\n", ans.c_str());
printf("%d\n", (int)ans.size());
*/
/*
//cantidad de subcadenas distintas
//http://www.spoj.com/problems/DISUBSTR/
int t;
scanf("%d", &t);
while (t--) {
scanf("%s", A);
init();
vector<bool> letters_used(257);
int n = 0;
for (int i = 0; A[i]; i++) {
letters_used[A[i]] = true;
Insert(A[i]);
n++;
}
alpha.clear();
for (int i = 0; i < 257; i++)
if (letters_used[i])
alpha.push_back(i);
for (int i = 0, lim = 2 * n; i <= lim; i++)
dp[i] = -1;
printf("%d\n", num_dist_substr() - 1);
}*/
/*
//suma de longitud de subcadenas distintas
//http://s8pc-2.contest.atcoder.jp/tasks/s8pc_2_e
scanf("%s", A);
init();
for (int i = 0; A[i]; i++)
Insert(A[i] - 'a');
memset(dp, -1, sizeof(dp));
memset(dp1, -1, sizeof(dp1));
printf("%lld\n", sum_length_dist_substr());
//printf("%lld\n", num_dist_substr());*/
/*
//K-esimo substring lexicografico
scanf("%s", A);
init();
for (int i = 0; A[i]; i++)
Insert(A[i] - 'a');
int q;
scanf("%d", &q);
while (q--) {
scanf("%lld", &K);
ans.clear();
path = 0;
kth_lex_substring();
printf("%s\n", ans.c_str());
}*/
scanf("%s", A);
init();
for (int i = 0; A[i]; i++)
Insert(A[i] - 'a');
int q;
scanf("%d", &q);
while (q--) {
scanf("%s", B);
printf("%c\n", is_substring(B)?'Y':'N');
}
return 0;
}
| true |
cde38dc912d3d0aca1d6e2af32ec83f21b0e3d03 | C++ | windystrife/UnrealEngine_NVIDIAGameWorks | /Engine/Source/Editor/UnrealEd/Private/PackageAutoSaver.h | UTF-8 | 4,818 | 2.515625 | 3 | [
"MIT",
"LicenseRef-scancode-proprietary-license"
] | permissive | // Copyright 1998-2017 Epic Games, Inc. All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "SlateFwd.h"
#include "UObject/WeakObjectPtr.h"
#include "IPackageAutoSaver.h"
namespace ECloseNotification
{
enum Type
{
NothingToDo,
Success,
Postponed,
Failed
};
}
/** A class to handle the creation, destruction, and restoration of auto-saved packages */
class FPackageAutoSaver : public IPackageAutoSaver
{
public:
FPackageAutoSaver();
virtual ~FPackageAutoSaver();
/** IPackageAutoSaver */
virtual void UpdateAutoSaveCount(const float DeltaSeconds) override;
virtual void ResetAutoSaveTimer() override;
virtual void ForceAutoSaveTimer() override;
virtual void ForceMinimumTimeTillAutoSave(const float TimeTillAutoSave = 10.0f) override;
virtual void AttemptAutoSave() override;
virtual void LoadRestoreFile() override;
virtual void UpdateRestoreFile(const bool bRestoreEnabled) const override;
virtual bool HasPackagesToRestore() const override;
virtual void OfferToRestorePackages() override;
virtual void OnPackagesDeleted(const TArray<UPackage*>& DeletedPackages) override;
virtual bool IsAutoSaving() const override
{
return bIsAutoSaving;
}
private:
/**
* Called when a package dirty state has been updated
*
* @param Pkg The package that was changed
*/
void OnPackageDirtyStateUpdated(UPackage* Pkg);
/**
* Called when a package is marked as dirty
*
* @param Pkg The package that was marked as dirty
* @param bWasDirty Whether the package was previously dirty before the call to MarkPackageDirty
*/
void OnMarkPackageDirty(UPackage* Pkg, bool bWasDirty);
/**
* Called when a package has been saved
*
* @param Filename The filename the package was saved to
* @param Obj The package that was saved
*/
void OnPackageSaved(const FString& Filename, UObject* Obj);
/**
* Update the dirty lists for the current package
*
* @param Pkg The package to update the lists for
*/
void UpdateDirtyListsForPackage(UPackage* Pkg);
/** @return Returns whether or not the user is able to auto-save. */
bool CanAutoSave() const;
/** @return Returns whether or not we would need to perform an auto-save (note: does not check if we can perform an auto-save, only that we should if we could). */
bool DoPackagesNeedAutoSave() const;
/** @return The notification text to be displayed during auto-saving */
FText GetAutoSaveNotificationText(const int32 TimeInSecondsUntilAutosave);
/**
* @param bIgnoreCanAutoSave if True this function returns the time regardless of whether auto-save is enabled.
*
* @return Returns the amount of time until the next auto-save in seconds. Or -1 if auto-save is disabled.
*/
int32 GetTimeTillAutoSave(const bool bIgnoreCanAutoSave = false) const;
/**
* Attempts to launch a auto-save warning notification if auto-save is imminent, if this is already the case
* it will update the time remaining.
*/
void UpdateAutoSaveNotification();
/** Closes the auto-save warning notification if open, with an appropriate message based on whether it was successful */
void CloseAutoSaveNotification(const bool Success);
/** Closes the auto-save warning notification if open, with an appropriate message based on type */
void CloseAutoSaveNotification(ECloseNotification::Type Type);
/** Used as a callback for auto-save warning buttons, called when auto-save is forced early */
void OnAutoSaveSave();
/** Used as a callback for auto-save warning buttons, called when auto-save is postponed */
void OnAutoSaveCancel();
/** Clear out any stale pointers in the dirty packages containers */
void ClearStalePointers();
/** The current auto-save number, appended to the auto-save map name, wraps after 10 */
int32 AutoSaveIndex;
/** The number of 10-sec intervals that have passed since last auto-save. */
float AutoSaveCount;
/** If we are currently auto-saving */
bool bIsAutoSaving;
/** Flag for whether auto-save warning notification has been launched */
bool bAutoSaveNotificationLaunched;
/** If we are delaying the time a little bit because we failed to save */
bool bDelayingDueToFailedSave;
/** Used to reference to the active auto-save warning notification */
TWeakPtr<SNotificationItem> AutoSaveNotificationPtr;
/** Packages that have been dirtied and not saved by the user, mapped to their latest auto-save file */
TMap<TWeakObjectPtr<UPackage>, FString> DirtyPackagesForUserSave;
/** Maps that have been dirtied and not saved by the auto-saver */
TSet<TWeakObjectPtr<UPackage>> DirtyMapsForAutoSave;
/** Content that has been dirtied and not saved by the auto-saver */
TSet<TWeakObjectPtr<UPackage>> DirtyContentForAutoSave;
/** Restore information that was loaded following a crash */
TMap<FString, FString> PackagesThatCanBeRestored;
};
| true |
8dc8cf5c02f9dda188e992c744dc1f0334b5bd79 | C++ | rsgilbert/helloCpp | /main.cpp | UTF-8 | 299 | 3.703125 | 4 | [] | no_license | #include <iostream>
using namespace std;
// Write a program that prints odd numbers between 0 and 100
int main() {
for (int num = 0; num < 100; num++) {
// Checks to see if num / 2 gives a remainder of 1
if (num % 2 == 1) {
cout << num << endl;
}
}
}
| true |
15e982273814d37d034e99512a3c0c61a564efc7 | C++ | phunghung/C | /mang1 & max.cpp | UTF-8 | 2,034 | 2.609375 | 3 | [] | no_license | #include<stdio.h>
#include<conio.h>
int nhapmang(int A[100], int n)
{
int i;
for(i=0; i<n; i++)
{
printf("\nA[%d] = ", i);
scanf("%d", &A[i]);
}
}
int xuatmang(int A[100], int n)
{
int i;
for(i=0; i<n; i++)
printf("%4d", A[i]);
}
int timmax(int A[100], int n)
{
int i, max;
max=A[0];
for(i=0; i<n; i++)
if(max<A[i])
max = A[i];
printf("\n gia tri lon nhat la: %d", max);
}
void gopmang(int a[], int na, int b[], int nb,int c[], int &nc)
{
nc = 0;
for (int i = 0; i < na; i++)
{
c[nc] = a[i]; nc++; // c[nc++] = a[i];
}
for (int i = 0; i < nb; i++)
{
c[nc] = b[i]; nc++; // c[nc++] = b[i];
}
}
int timkiem(int A[], int n, int x)
{
for (int vt = 0; vt < n; vt++)
if (A[vt] == x)
return vt;
return 0;
}
int LaSNT(int n)
{
int i;
for (i = 2; i < n; i++)
if (n % i == 0)
return 0;
else return 1;
}
int kiemtra_c3(int A[], int n)
{
for (int i = 0; i < n ; i++)
if (LaSNT(A[i]) == 0)
return 0;
return 1;
}
void TachSNT(int a[100], int na, int b[100], int &nb)
{
nb = 0;
for (int i = 0; i < na; i++)
if (LaSNT(a[i]) == 1)
{
b[nb] = a[i];
nb++;
}
}
int hoanvi(int &x, int &y)
{
int tam;
tam = x;
x = y;
y = tam;
}
void sapxeptang(int A[10], int n)
{
int i, j;
for (i = 0; i < n; i++)
{
for (j = i + 1; j < n; j++)
if (A[j] < A[i])
hoanvi(A[j], A[i]);
}
xuatmang(A,n);
}
int main()
{
int A[100],B[100], C[100], D[100], nd, nc, nb, n, z, vtx;
printf("nhap so luong phan tu cua mang A: "); scanf("%d", &n);
printf("nhap gia tri can tim: "); scanf("%d", &z);
nhapmang(A,n);
xuatmang(A,n);
timmax(A,n);
printf("\n");
if(vtx = timkiem(A,n,z))
printf("\n gia tri z = %d nam o vi tri %d", z, vtx);
else printf("\n gia tri z = %d khong nam trong mang", z);
printf("\n");
if(kiemtra_c3(A,n))
printf("\n mang toan so nguyen to");
else
printf("\n mang khong phai tat ca deu la so nguyen to\n");
printf("\n");
printf(" sap xep gia tri tang dan: \n");
sapxeptang(A,n);
printf("\n");
printf("\nTach cac so nguyen to trong mang A sang mang B la: ");
TachSNT(A, n, B, nb);
xuatmang(B,nb);
}
| true |
8300ec6e44cbf106adb80300bf8586e0bc94a1d8 | C++ | Mark-zw/C-Plus-Plus | /c++_practice0822.cpp | GB18030 | 4,673 | 3.3125 | 3 | [] | no_license | #define _CRT_SECURE_NO_WARNINGS 1
#include<iostream>
using namespace std;
//class Stack {
//public:
// //캯ɳʼ
// Stack(int n = 10) {
// _array = (int*)malloc(sizeof(int) * n);
// _size = 0;
// _capacity = 10;
// }
// //Դ
// ~Stack() {
// free(_array);
// _array = NULL;
// _size = 0;
// _capacity = 0;
// }
//private:
// int* _array;
// int _size;
// int _capacity;
//};
//int main() {
// Stack st;
// return 0;
//}
//#include<iostream>
//using namespace std;
//class Time {
//public:
// ~Time() {
// cout << "~Time()" << endl;
// }
//private:
// int _hour;
// int _minute;
// int _second;
//};
//class Date
//{
//public:
// //캯
// Date(int year = 0, int month = 1, int day = 1) {
// _year = year;
// _month = month;
// _day = day;
// cout << "Զù캯" << endl;
// }
// ////
// //~Date() {
// // cout << "Զ~" << endl;
// //}
// void Display()
// {
// cout << _year << "-" << _month << "-" << _day << endl;
// //cout << this->_year << "-" << this->_month << "-" <<this-> _day << endl;
// }
//
//private:
// int _year;//
// int _month;//
// int _day;//
// Time _t;//Զ
//};
//int main()
//{
// Date d1(2021, 10, 1);
// Date d2;
// d1.Display();
// d2.Display();
// return 0;
//}
#include<iostream>
using namespace std;
class Date {
public:
int GetMonthDay(int year, int month) {
static int monthDays[13] = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
//2¾ͷ29
if (month == 2 && ((year % 4 == 0) && (year % 100 != 0) || year % 400 == 0)) {
return 29;
}
return monthDays[month];
}
Date(int year = 0, int month = 1, int day = 1) {
if (year >= 0 && month >= 1 && month <= 12 && day >= 1 && day <= GetMonthDay(year, month)) {
_year = year;
_month = month;
_day = day;
}
else {
cout << "Ƿ" << endl;
}
}
//캯
Date(const Date& d) {
_year = d._year;
_month = d._month;
_day = d._day;
}
void Print() {
cout << _year << "-" << _month << "-" << _day << endl;
}
//Ϊʹأŵclasspublic
//мoperatorصĺм
bool operator==(const Date& d) { //bool operator == (Date* this,const Date& d)
return _year == d._year
&& _month == d._month
&& _day == d._day;
}
//Ż
bool operator>(const Date& d) {
if (_year > d._year)
return true;
else if (_year == d._year && _month > d._month)
return true;
else if (_year == d._year && _month == d._month && _day > d._day)
return true;
return false;
}
bool operator>=(const Date& d) {
return *this > d || *this == d;
}
bool operator!=(const Date& d) {
return !(*this == d);
}
bool operator<(const Date& d) {
return !(*this > d);
}
bool operator<=(const Date& d) {
return *this < d || *this == d;
}
Date operator+(int day) {
Date ret(*this);
ret._day += day;
while (ret._day > GetMonthDay(ret._year, ret._month)) {
ret._day -= GetMonthDay(ret._year, ret._month);
ret._month++;
if (ret._month == 13) {
ret._year++;
ret._month = 1;
}
}
return ret;
}
Date operator+=(int day);
Date operator-(int day);
Date operator-=(int day);
Date operator++(int day);
Date operator--(int day);
private:
int _year;
int _month;
int _day;
};
int main() {
Date d1(2021, 10, 1);
Date d2(2021, 10, 2);
Date d3(d1);
Date d4 = d1;
bool ret = d2 > d1;//ᱻתɣoperator > (Date* this,const Date& d)
d1.Print();
d2.Print();
Date d5(2021, 2, 29);
//cout << (d1 == d2) << endl;
//cout << (d1 != d2) << endl;
//cout << (d1 < d2) << endl;
//cout << (d1 <= d2) << endl;
//cout << (d1 > d2) << endl;
//cout << (d1 >= d2) << endl;
Date d6 = d2 + 1000;
d6.Print();
return 0;
}
//func1(int i) {
// //ڲ
//}
//int main() {
// int j = 0;
// func1(j);//func1ʱҪȽji
//}
//bool operator>(const Date& d) {
// if (_year > d._year)
// return true;
// else if (_year < d._year)
// return false;
// if (_month > d._month)
// return true;
// else if (_month < d._month)
// return false;
// if (_day > d._day)
// return true;
// else if (_day < d._day)
// return false;
// else
// return false;
//}
//Ϊoperator==ãʱ˽pravate
//ʵʹõʱԱprivate | true |
37972f153eb0e2d34e535e085da9b84f6166d1ac | C++ | cs1102-lab1-09-2019-2/proyecto-final-team_laberinto | /pruebas.cpp | UTF-8 | 3,611 | 3.21875 | 3 | [] | no_license | #include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
int** LeerMatriz(char const * const filename, int &Filas, int &Columnas) {
FILE *fp = fopen(filename, "r");
if (fp == nullptr){
exit(EXIT_FAILURE);
}
char linea[225];
fgets(linea, 224, fp);
char *token = strtok(linea, " ");
Filas = atoi(token);
token = strtok(nullptr, " ");
Columnas = atoi(token);
int **matriz = new int*[Filas];
for (int i = 0; i < Filas; i++){
matriz[i] = new int[Columnas];
fgets (linea, 224, fp);
token = strtok(linea, " ");
matriz[i][0] = atoi(token);
for (int j = 1; j < Columnas; j++){
token = strtok(nullptr, " ");
matriz[i][j] = atoi(token);
}
}
fclose(fp);
return matriz;
}
void ImprimirMatriz(int **Matriz){
for (int i = 0; i < 15; i++){
for (int j = 0; j < 15; j++){
if (*(*(Matriz + i)+ j) == 1){
cout << "#" << " ";
}else if ((*(*(Matriz + i)+ j) == 0)){
cout << " " << " ";
}else if ((*(*(Matriz + i)+ j) == 2)){
cout << "i" << " ";
}else if ((*(*(Matriz + i)+ j) == 3)){
cout << "f" << " ";
}else if ((*(*(Matriz + i)+ j) == 9)){
cout << ">" << " ";
}
}
cout << endl;
}
}
void HallarPosiCarro (int **Matriz, int Filas, int Columnas, int &x, int &y){
for (int i = 0; i < Filas; i++){
for (int j = 0; j < Columnas; j++){
if (*(*(Matriz + i)+ j) == 2){
y = i;
x = j;
}
}
}
}
void HallarPosiMeta (int **Matriz, int Filas, int Columnas, int &x, int &y){
for (int i = 0; i < Filas; i++){
for (int j = 0; j < Columnas; j++){
if (*(*(Matriz + i)+ j) == 3){
y = i;
x = j;
}
}
}
}
bool seguro(int **Matriz, int Filas, int Columnas, int xo, int yo){
if (xo >= 0 && xo < Columnas && yo >= 0 && yo < Filas && *(*(Matriz + yo)+ xo) == 0){
return true;
}else{
return false;
}
}
bool camino(int ** mat, int N, int M, int y, int x, int finf, int finc) {
if (y == finf && x == finc) {
*(*(mat + y) + x) = 9;
return true;
}
if (seguro(mat, N, M, x, y) == true) {
*(*(mat + y) + x) = 9;
if (camino(mat, N, M, y, x + 1, finf, finc) == true)
return true;
if (camino(mat, N, M, y + 1, x, finf, finc) == true)
return true;
if (camino(mat, N, M, y, x - 1, finf, finc) == true)
return true;
if (camino(mat, N, M, y - 1, x, finf, finc) == true)
return true;
*(*(mat + y) + x) = 0;
return false;
}
return false;
}
int main(){
int TamFila = 0, TamCol = 0;
int Xo = 0, Yo = 0, Xf = 0, Yf = 0;
const char* n = "C:\\Users\\Gabriel Alexsander\\Desktop\\MapasPOO\\MAPA#8.txt";
int **MatrizMapa = LeerMatriz(n, TamFila, TamCol); //Deben poner la direccion en donde este el mapa
cout << "LABERINTO++ \n";
cout << "# -> Pared \n" << "Espacio -> Camino libre \n" << "0 -> Punto de inicio \n" << "1 -> Meta \n \n";
cout << "Mapa #1: \n";
ImprimirMatriz(MatrizMapa);
HallarPosiCarro(MatrizMapa, TamFila, TamCol, Xo, Yo);
HallarPosiMeta(MatrizMapa, TamFila, TamCol, Xf, Yf);
MatrizMapa[Yo][Xo] = 0;
camino(MatrizMapa, TamFila, TamCol, Yo, Xo, Yf, Xf);
cout << endl << endl;
cout << "Mapa #1 SOLUCION: \n";
ImprimirMatriz(MatrizMapa);
}
| true |
8f0b3e0e58a6d6e5c6cde64b0fb76e4fa971f881 | C++ | hemanthk92/IDD-Fa18-Lab2 | /jukebox.ino | UTF-8 | 2,903 | 2.671875 | 3 | [] | no_license | /*
Melody
Plays a melody
circuit:
- 8 ohm speaker on digital pin 8
created 21 Jan 2010
modified 30 Aug 2011
by Tom Igoe
This example code is in the public domain.
http://www.arduino.cc/en/Tutorial/Tone
*/
#include "pitches.h"
#include <LiquidCrystal.h>
#define ENC_A 2 //these need to be digital input pins
#define ENC_B 3
const int rs = 12, en = 11, d4 = 5, d5 = 4, d6 = 3, d7 = 2;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);
int melodies[2][20] = {
{
NOTE_C2, NOTE_F3, NOTE_C3, NOTE_A2,
NOTE_C3, NOTE_F3, NOTE_C3,
NOTE_C3, NOTE_F3, NOTE_C3, NOTE_F3,
NOTE_AS3, NOTE_G3, NOTE_F3, NOTE_E3, NOTE_D3, NOTE_CS3,
NOTE_C3, NOTE_F3, NOTE_C3},
{NOTE_D3,NOTE_D3,NOTE_D3,NOTE_G3,NOTE_D4,NOTE_C4,NOTE_B3,NOTE_A3,NOTE_G4,NOTE_D4,
NOTE_C4,NOTE_B3,NOTE_A3,NOTE_G4,NOTE_D4,NOTE_C4,NOTE_B3,NOTE_C4,NOTE_A3,0}
};
// note durations: 4 = quarter note, 8 = eighth note, etc.:
int noteDurations[2][20] = {
{
4, 4, 4, 4,
4, 4, 2,
4, 4, 4, 4,
3, 8, 8, 8, 8, 8,
4, 4, 4},
{ 10,10,10,2,2,10,10,10,2,4,
10,10,10,2,4,10,10,10,2,4}
};
void setup() {
// iterate over the notes of the melody:
lcd.clear();
lcd.begin(16, 2);
pinMode(ENC_A, INPUT_PULLUP);
pinMode(ENC_B, INPUT_PULLUP);
Serial.begin (9600);
Serial.print("Hello");
lcd.print("Hello World\n");
int tmpdata;
int currentEncoderValue;
int newEncoderValue;
currentEncoderValue = read_encoder();
while(true){
for (int thisSong = 0; thisSong < 2; thisSong++){
for (int thisNote = 0; thisNote < 20; thisNote++) {
// to calculate the note duration, take one second divided by the note type.
//e.g. quarter note = 1000 / 4, eighth note = 1000/8, etc.
int noteDuration = 1000 / noteDurations[thisSong][thisNote];
tone(8, melodies[thisSong][thisNote], noteDuration);
// to distinguish the notes, set a minimum time between them.
// the note's duration + 30% seems to work well:
int pauseBetweenNotes = noteDuration * 1.30;
delay(pauseBetweenNotes);
// stop the tone playing:
noTone(8);
//lcd.clear();
//lcd.setCursor(0, 1);
Serial.print(20-thisNote);
Serial.print("\n");
newEncoderValue = read_encoder();
if (newEncoderValue != currentEncoderValue) {
break;
};
currentEncoderValue = newEncoderValue;
}
delay(1000);
}
}
}
void loop() {
// no need to repeat the melody.
}
int read_encoder()
{
static int enc_states[] = {
0,-1,1,0,1,0,0,-1,-1,0,0,1,0,1,-1,0 };
static byte ABab = 0;
ABab *= 4; //shift the old values over 2 bits
ABab = ABab%16; //keeps only bits 0-3
ABab += 2*digitalRead(ENC_A)+digitalRead(ENC_B); //adds enc_a and enc_b values to bits 1 and 0
return ( enc_states[ABab]);
}
| true |
cd9c62e86fcd7e860a0f87bc4b9fee586388498a | C++ | usherfu/zoj | /zju.finished/2861.cpp | UTF-8 | 1,007 | 2.515625 | 3 | [] | no_license | #include<iostream>
using namespace std;
enum {
SIZ = 32,
};
long long sum[SIZ+1][SIZ+1];
long long ans = 0;
long long N, L, P;
void init(){
int i, j;
sum[0][0] = 1;
for (i=1; i<SIZ; ++i){
sum[i][0] = 1;
for (j=1; j<SIZ; ++j){
sum[i][j] = sum[i-1][j] + sum[i-1][j-1];
}
}
for (i=0; i<SIZ; ++i){
for (j=1; j<SIZ; ++j){
sum[i][j] += sum[i][j-1];
}
}
}
int findLevel(){
int i;
for (i=0; i<SIZ; ++i){
if (P<sum[i][L]){
return i;
} else {
P-=sum[i][L];
}
}
return -1;
}
void fun(){
if (P == 1){
printf("0\n");
return;
}
ans = 0;
--P;
while(L-->0 && P-->0){
int f = findLevel();
if (f >= 0)
ans |= 1llu<<(f);
else
break;
}
printf("%lld\n", ans);
}
int main(){
init();
while(scanf("%lld%lld%lld", &N,&L,&P) > 0){
fun();
}
return 0;
}
| true |
bdfea1865fa52f40907c7e0cfc692694cd777350 | C++ | devakar/codes | /coding/reverse.cpp | UTF-8 | 300 | 3.25 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <stack>
using namespace std;
int main()
{
string s;
cin>>s;
int l=s.length();
stack <char> st;
for(int i=0;i<l;i++)
{
st.push(s[i]);
}
for(int i=0;i<l;i++)
{
s[i]=st.top();
st.pop();
}
cout<<"Reverse is "<<s<<endl;
return 0;
} | true |
78aec216cffb3aadb00ad031cc5546413dd2f8da | C++ | aabedraba/DataStructures | /3-Linked_Lists_Implementation/src/ListaEnlazada.h | UTF-8 | 4,514 | 3.03125 | 3 | [] | no_license | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/*
* File: ListaEnlazada.h
* Author: aabedraba
*
* Created on October 17, 2017, 11:29 PM
*/
#ifndef LISTAENLAZADA_H
#define LISTAENLAZADA_H
#include "Diccionario.h"
#include <stdexcept>
template<typename T>
class Nodo {
public:
T _dato;
Nodo *_sig;
Nodo( T &aDato, Nodo *aSig = 0 ):
_dato ( aDato ),
_sig ( aSig )
{};
Nodo( const Nodo& orig )
: _dato ( orig._dato ),
_sig ( orig._sig )
{};
virtual ~Nodo (){};
};
template<typename T>
class ListaEnlazada {
public:
ListaEnlazada<T>();
ListaEnlazada<T>( const ListaEnlazada<T>& orig );
virtual ~ListaEnlazada();
ListaEnlazada<T>& operator= ( const ListaEnlazada<T> &orig );
class Iterador {
private:
Nodo<T> *_nodo;
friend class ListaEnlazada<T>;
public:
Iterador()
: _nodo (0)
{};
Iterador( Nodo<T> *aNodo )
: _nodo ( aNodo )
{};
Iterador( const Iterador& orig )
: _nodo ( orig._nodo )
{};
Iterador& operator=( const Iterador &orig ){
_nodo = orig._nodo;
}
virtual ~Iterador( ){};
bool fin () {
return _nodo == 0;
};
void siguiente () {
_nodo = _nodo->_sig;
};
T& dato () {
return _nodo->_dato;
}
};
Iterador iterador();
T& inicio();
T& fin();
void insertaInicio ( T &dato );
void insertaFin ( T &dato );
void inserta ( Iterador &iter, T &dato );
void borraInicio ();
void borraFinal ();
void borra ( Iterador &iter );
private:
Nodo<T> *_cabecera, *_cola;
};
template<typename T>
ListaEnlazada<T>::ListaEnlazada()
: _cabecera( 0 ),
_cola( 0 )
{
}
template<typename T>
ListaEnlazada<T>::ListaEnlazada ( const ListaEnlazada<T>& orig )
: _cabecera ( orig._cabecera ),
_cola ( orig._cola )
{
}
template<typename T>
ListaEnlazada<T>::~ListaEnlazada() {
while ( _cabecera == 0 ){
Nodo<T> *aBorrar = _cabecera;
_cabecera = _cabecera->_sig;
delete aBorrar;
}
}
template<typename T>
ListaEnlazada<T>& ListaEnlazada<T>::operator =( const ListaEnlazada<T>& orig ) {
if ( this->_cabecera != 0 ){
this->_cabecera = orig._cabecera;
this->_cola = orig._cola;
}
return *this;
}
template<typename T>
void ListaEnlazada<T>::insertaInicio ( T& dato ) {
Nodo<T> *nuevo;
nuevo = new Nodo<T> ( dato, _cabecera );
if ( _cola == 0 )
_cola = nuevo;
_cabecera = nuevo;
}
template<typename T>
void ListaEnlazada<T>::insertaFin ( T& dato ) {
Nodo<T> *nuevo;
nuevo = new Nodo<T> ( dato );
if ( _cola != 0 )
_cola->_sig = nuevo;
if ( _cabecera == 0 )
_cabecera = nuevo;
_cola = nuevo;
}
template<typename T>
void ListaEnlazada<T>::inserta ( Iterador& iter, T& dato ) { //El iterador apunta al anterior
Nodo<T> *nuevo = new Nodo<T> ( dato, iter._nodo );
iter.dato() = nuevo;
if ( _cabecera == 0 )
_cabecera = _cola = nuevo;
}
template<typename T>
void ListaEnlazada<T>::borraInicio () {
Nodo<T> *borrado = _cabecera;
_cabecera = _cabecera->_sig;
if (borrado)
// delete borrado;
borrado = 0;
if ( _cabecera == 0 )
_cola = 0;
}
template<typename T>
void ListaEnlazada<T>::borraFinal () {
Nodo<T> *anterior =0;
if ( _cabecera != _cola ) {
anterior = _cabecera;
while ( anterior->_sig != _cola )
anterior = anterior->_sig;
}
delete _cola;
_cola = anterior;
if ( anterior != 0 )
anterior->_sig = 0;
else
_cabecera = 0;
}
template<typename T>
void ListaEnlazada<T>::borra ( Iterador& iter ) {
Nodo<T> *anterior = 0;
if ( _cabecera != _cola ) {
anterior = _cabecera;
while ( anterior->_sig != iter )
anterior = anterior->_sig;
}
anterior->_sig = iter.getNodo()->_sig;
delete iter;
}
template<typename T>
T& ListaEnlazada<T>::inicio () {
return _cabecera->_dato;
}
template<typename T>
T& ListaEnlazada<T>::fin () {
return _cola->_dato;
}
template<typename T>
typename ListaEnlazada<T>::Iterador ListaEnlazada<T>::iterador(){
return Iterador( _cabecera );
}
#endif /* LISTAENLAZADA_H */ | true |
7692330dfd1844db24566b48ea322810f8af1fb4 | C++ | stjenkins/Programming_Portfolio | /vowel_counter/vowel_counter.cpp | UTF-8 | 1,142 | 3.625 | 4 | [] | no_license | #include <iostream>
#include <fstream>
using namespace std;
int main(int argc, char* argv[]){
//declare variables
ifstream myfile;
int num_vowels = 0;
string buffer;
//check for correct number of arguments
if(argc != 2){cerr << "Usage is a.out filename.txt\n"; return -1;}
//open file and check if the file sucessfully opened
myfile.open(argv[1]);
if(!myfile.is_open()){cerr << "File failed to open.\n"; return -1;}
//read the characters out and check if they're vowels.
while(getline(myfile, buffer)){
for(int i = 0; i < buffer.size(); i++){
switch(buffer.at(i)){
case 'A': num_vowels ++; break;
case 'a': num_vowels ++; break;
case 'E': num_vowels ++; break;
case 'e': num_vowels ++; break;
case 'I': num_vowels ++; break;
case 'i': num_vowels ++; break;
case 'O': num_vowels ++; break;
case 'o': num_vowels ++; break;
case 'U': num_vowels ++; break;
case 'u': num_vowels ++; break;
default: break;
}
}
}
//print out the number of vowels
cout << num_vowels << endl;
//do clean-up procedures and return control back to the OS
myfile.close();
return num_vowels;
}
| true |
451224ab31690957b5b4ee3efc1dbd750126ce1d | C++ | xmcpp/DeepRender | /Dx9World/Dx9World/SimpleMesh.h | GB18030 | 1,107 | 2.734375 | 3 | [] | no_license | #ifndef __SIMPLEMESH_H__
#define __SIMPLEMESH_H__
#include "MeshFileIO.h"
class SimpleMesh
{
public:
SimpleMesh( const std::string & meshName );
~SimpleMesh();
public:
bool loadFromFile( const std::string & fileName );
bool unloadMesh();
bool loadToGpu();
bool unloadFromGpu();
public:
const std::vector<VERTEX_FORMAT_TYPE> & getVertexType() { return m_fvfVec;}
const std::string getMatName() { return m_matName;}
INDEX_TYPE getIndexType() { return m_indexType; }
int getIndexCount() { return m_reader.getIndexCount(); }
int getVertexCount() { return m_reader.getVertexCount(); }
char * getIndexData () { return m_indexData; }
char * getVertexData() { return m_vertexData; }
private:
std::string m_name;
std::vector<VERTEX_FORMAT_TYPE> m_fvfVec;
std::string m_matName;
INDEX_TYPE m_indexType;
char * m_vertexData; //¼
char * m_indexData; //¼
MeshFileReader m_reader;
int m_vertexDataSize; //ݴС(ֽ)
int m_indexDataSize;//ݴС(ֽ)
bool m_isLoadedFromFile;
bool m_isLoadedToGpu;
};
#endif //__SIMPLEMESH_H__
| true |
56b201edefee53d6761550e8c9408da0362188f0 | C++ | abhigoyal1997/Codes | /data-structures/linked_list/main1.cpp | UTF-8 | 815 | 3.078125 | 3 | [] | no_license | #include "list_of_list.h"
void insertData(datastore<float> &x){
int n; cin >> n;
float in;
while(n--){
cin >> in;
x.insert(in);
}
}
int main(){
datastore<float> x;
char ch;
cin>>ch;
while(ch!='q'){
float in; int inp;
switch(ch){
case 'i': insertData(x);
break;
case 'p': x.print();
break;
case 's': cin >> in;
cout << x.search(in) << endl;
break;
case 'm': cout << x.find_max() << endl;
break;
case 'l': x.list_max();
break;
case 'z': x.list_zero();
break;
case 'c': cin >> inp;
x.list_count(inp);
break;
case 'e': cin >> in;
cout << x.eject(in) << endl;
break;
case 'x': break;
case 'd': cin >> in;
x.decrement(in);
break;
case 'r': x.reset();
}
cin>>ch;
}
return 0;
}
| true |
53e0d4eb635af7a62ebb0492721f1d3dd0abc32d | C++ | Rearcher/OJcodes | /leetcode/530.cpp | UTF-8 | 1,194 | 3.796875 | 4 | [] | no_license | // 530. Minimum Absolute Difference in BST
#include <iostream>
#include <vector>
#include <stack>
#include <algorithm>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
int getMinimumDifference(TreeNode* root) {
if (root == NULL) {
return 0;
}
stack<TreeNode*> s;
vector<int> vals;
s.push(root);
while (!s.empty()) {
TreeNode* tmp = s.top();
s.pop();
vals.push_back(tmp->val);
if (tmp->right) {
s.push(tmp->right);
}
if (tmp->left) {
s.push(tmp->left);
}
}
sort(vals.begin(), vals.end());
int result = INT_MAX;
for (int i = 0; i < vals.size() - 1; ++i) {
result = min(result, vals[i+1] - vals[i]);
}
return result;
}
};
int main() {
Solution s;
TreeNode* root = new TreeNode(1);
root->right = new TreeNode(3);
root->right->left = new TreeNode(2);
cout << s.getMinimumDifference(root) << endl;
} | true |
12e936876e7e97fe1a569b0b38f78c95e4d5f521 | C++ | Ph0en1xGSeek/ACM | /Others/LCS_Revised.cpp | GB18030 | 366 | 2.90625 | 3 | [] | no_license | /**
ͬȵƴ
Ҫô1࣬Ҫô0
**/
#include <stdio.h>
#include <iostream>
char s[100008];
int main()
{
int a=0, b=0, i;
while(scanf("%s", s) != EOF)
{
for(i=0;s[i];i++)
if(s[i]=='0')
++a;
else
++b;
printf("%d\n", a<b?a:b);
}
}
| true |
31c7ac1562093fc622b0a7641674c8e64cdc134e | C++ | dudochkin-victor/handset-video | /src/videofileinfo.cpp | UTF-8 | 1,738 | 2.546875 | 3 | [
"Apache-2.0"
] | permissive | /*
* Meego-handset-video is an video player for MeeGo handset.
* Copyright (C) 2010, Intel Corporation.
*
* This program is licensed under the terms and conditions of the
* Apache License, version 2.0. The full text of the Apache License is at
* http://www.apache.org/licenses/LICENSE-2.0
*
*/
#include <QStringList>
#include "videofileinfo.h"
VideoFileInfo::VideoFileInfo()
: m_favorite(false)
{
}
void VideoFileInfo::setLastPlayedDate(const QDateTime & date)
{
m_lastPlayedDate = date;
}
QDateTime VideoFileInfo::lastPlayedDate() const
{
return m_lastPlayedDate;
}
void VideoFileInfo::setFavorite(bool favorite)
{
m_favorite = favorite;
}
bool VideoFileInfo::isFavorite() const
{
return m_favorite;
}
void VideoFileInfo::setDateAdded(const QDateTime & date)
{
m_dateAdded = date;
}
QDateTime VideoFileInfo::dateAdded() const
{
return m_dateAdded;
}
VideoFileInfo VideoFileInfo::fromString(const QString & str/*, bool * ok*/)
{
VideoFileInfo info;
QStringList list = str.split(";");
if (list.size() == 3) { // there are some records about this file
bool ok;
bool favorite = list.at(0).toInt(&ok);
if (!ok)
favorite = false;
info.setFavorite(favorite);
info.setLastPlayedDate( QDateTime::fromString(list.at(1)) );
info.setDateAdded( QDateTime::fromString(list.at(2)) );
}
return info;
}
QString VideoFileInfo::toString() const
{
return QString("%1;%2;%3")
.arg(m_favorite ? "1" : "0")
.arg(m_lastPlayedDate.toString())
.arg(m_dateAdded.toString());
}
void VideoFileInfo::reset()
{
m_lastPlayedDate = QDateTime();
m_dateAdded = QDateTime();
m_favorite = false;
}
| true |
3e63edf44285c883d8eb13df2b8342dd13d07a0e | C++ | alvishnitskiy/ics | /pset5/speller/table.h | UTF-8 | 1,245 | 2.78125 | 3 | [] | no_license | /**
* Declares a hash table's functionality.
*/
#ifndef TABLE_H
#define TABLE_H
#include <strings.h>
#include <ctype.h>
#include "dictionary.h"
#include "list.h"
//#define SIZE 50
class HashMap {
private:
// default size of hashMap in memory
const int SIZE_ON_DEFAULT = 50;
// pointer to begin of base array
LinkedList* hashMap;
// number of data in map
unsigned int sizeOfMap;
// size of base array
int sizeOfArray;
const char* TAG = "hash_map";
public:
// debug info
void tagging(const char* NAME);
// constructor with initialization by default
HashMap();
// constructor with initialization of inner array
HashMap(int size);
// cynical breaking inner data
~HashMap();
// if main node of list is empty
bool listIsEmpty(LinkedList* list);
// add new node
bool add(const char* word);
// find the data
bool find(const char* word);
// remove all nodes from map
bool removeAll();
// get number of data in map
unsigned int size();
// show all data in map
void show();
// using hash function
int hash(const char* key);
};
#endif // TABLE_H
| true |
19d5e0374f233d5bf716de3ded9ff4797e77529f | C++ | milindbhavsar/Leetcode-Templates-and-Examples | /code/0952. Largest Component Size by Common Factor.h | UTF-8 | 1,889 | 3.453125 | 3 | [] | no_license | /*
Given a non-empty array of unique positive integers A, consider the following graph:
There are A.length nodes, labelled A[0] to A[A.length - 1];
There is an edge between A[i] and A[j] if and only if A[i] and A[j] share a common factor greater than 1.
Return the size of the largest connected component in the graph.
Input: [4,6,15,35]
Output: 4
Input: [20,50,9,63]
Output: 2
*/
class UnionFind{
private:
vector<int> nums;
public:
UnionFind(int n){
nums=vector<int>(n,0);
for(int i=0;i<n;i++)
nums[i]=i;
}
void Union(int i,int j){
int ri=root(i),rj=root(j);
if(ri!=rj)
nums[ri]=rj;
return;
}
int root(int i){
if(nums[i]!=i){
nums[i]=root(nums[i]);
}
return nums[i];
}
int getroot(int i){
return nums[i];
}
int count(){ //count largest divider
int res=0, n=nums.size();
vector<int> v(n,0);
for(int i=0;i<n;i++){
int r=root(i);
v[r]++;
res=max(res,v[r]);
}
return res;
}
};
class Solution {
public:
int largestComponentSize(vector<int>& A) {
int n=A.size();
unordered_map<int,int> graph;
UnionFind u(n);
for(int i=0;i<n;i++){
for(int j=2;j<=(int)sqrt(A[i]);j++){
if(A[i]%j==0){
if(graph.count(j)) u.Union(i,graph[j]);
else graph[j]=u.getroot(i);
if(graph.count(A[i]/j)) u.Union(i,graph[A[i]/j] ); //replace j by A[i]/j
else graph[A[i]/j]=u.getroot(i);
}
}
if(graph.count(A[i])) u.Union(i,graph[A[i]]); //replace j by A[i]
else graph[A[i]]=u.getroot(i);
}
return u.count();
}
};
| true |
1e5ebd4eaff97df2a5a07425545d713614004c0f | C++ | Datin71/DatinLogan_2666266 | /Hmwk/Assignment3/Gaddis_8thEd_Chap4_Prob5_BMI/main.cpp | UTF-8 | 927 | 3.640625 | 4 | [] | no_license | /*
File: main
Author: Logan Datin
Created on October 05, 2016, 4:37 PM
Purpose: Calculate bmi and determine if the bmi is healthy or not
*/
//System Libraries
#include <iostream> //Input/Output objects
using namespace std; //Name-space used in the System Library
//User Libraries
//Global Constants
//Function prototypes
//Execution Begins Here!
int main(int argc, char** argv) {
//Declaration of Variables
float bmi, weight, height;
//Input values
cout<<"Enter your weight in pounds"<<endl;
cin>>weight;
cout<<"Enter your height in inches"<<endl;
cin>>height;
//Process values -> Map inputs to Outputs
bmi=weight*(703/(height*height)); //calculate bmi
//Display Output
cout<<"Your BMI is "<<bmi<<endl;
(bmi<18.5)?cout<<"You are underweight":
(bmi>25)?cout<<"You are overweight":cout<<"You are at optimal weight";
//Exit Program
return 0;
} | true |
794d08275b73e5b464a685ad976de4718ed0f0e9 | C++ | Luminatus/eva-labyrinth | /app/Headers/game_map.h | UTF-8 | 884 | 2.65625 | 3 | [] | no_license | #ifndef GAME_MAP_H
#define GAME_MAP_H
#include <QVector>
#include <QMap>
#include "Headers/datastructures.h"
class GameMap{
public:
static GameMap* createFromString(QString data, QString name,const QMap<QString,GameField>& code_table);
static GameMap* createGameMap(QVector<QVector<GameField> >* map, QString name);
GameField getField(int row,int col);
GameField getField(Position position);
QString getName();
int getSize();
bool isSolvable();
bool isAnalised();
int getMinimumSteps();
void solve();
private:
GameMap(QVector<QVector<GameField> >* map, QString name): _map(map), _name(name){}
QVector<QVector<GameField> >* _map;
QString _name;
bool _isAnalised = false;
bool _isSolvable = false;
int _minimumSteps = 0;
};
#endif // GAME_MAP_H
| true |
7e4b0ab68343f8d10516dc984779824af07feed7 | C++ | sankha87/Linked-List-swap-the-k-th-node-from-beginning-with-the-k-th-last-node-2 | /Source.cpp | UTF-8 | 1,698 | 4.15625 | 4 | [] | no_license | // Given a linked list(singly - linked, non - circular), write a program to swap the kth node from beginning
// with the kth last node in the list. Note that the length of the list is not known.
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
struct Node
{
int data;
struct Node *next;
};
void swap_kth_begin_last(struct Node *head, int n) // Function to get the nth node from the last of a linked list
{
int len = 0, i;
struct Node *temp = head, *temp2 = head;
for (i = 1; i < n; i++) // get the n th node from the beginning
{
temp = temp->next;
if (temp == NULL)
{
printf("\nPlease give n less than LinkedList length");
return;
}
}
for (temp; temp->next!= NULL; temp = temp->next) // get the n th node from the last
temp2 = temp2->next;
temp = head;
for (i = 1; i < n; i++)
temp = temp->next;
int swap = temp->data; // swap
temp->data = temp2->data;
temp2->data = swap;
for (head; head!=NULL; head=head->next)
printf(" %d ", head->data);
}
Node* push(struct Node *head_ref, int new_data)
{
struct Node *new_node = (struct Node*)malloc(sizeof(struct Node));
if (new_node == NULL)
printf("\nStack Overflow");
else
{
new_node->data = new_data;
new_node->next = head_ref;
head_ref = new_node;
return head_ref;
}
}
int main()
{
struct Node *head = NULL; // Start with the empty list
head = push(head, 20); // create linked list 2->5->10->35->15->4->20
head = push(head, 4);
head = push(head, 15);
head = push(head, 35);
head = push(head, 10);
head = push(head, 5);
head = push(head, 2);
swap_kth_begin_last(head, 1);
_getch();
} | true |
56edd7ad83fef49d50e1773cb6c82e3b60533d59 | C++ | iamitshaw/codechef-contest | /PSTR2020/ITGUY07/main.cpp | UTF-8 | 536 | 2.65625 | 3 | [] | no_license | #include <bits/stdc++.h>
int32_t main(int32_t argc, char* argv[]) {
/* fast input-output */
std::ios_base::sync_with_stdio(false);
std::cin.tie(nullptr);
std::cout.tie(nullptr);
/* get test_case */
int32_t test_case;
std::cin >> test_case;
while (test_case--) {
/* get N */
int64_t N;std::cin >> N;
/* evaluate N-th term of series */
int64_t N_th_term{(N*(N-1))/2};
/* print appropriate message */
std::cout << N_th_term << "\n";
}
return 0;
} | true |
58971e1e8ba6daad98919d0681c9a942e5223aff | C++ | chenyangjamie/Leetcode | /084. Sort Colors/Sort_Colors.cpp | UTF-8 | 1,903 | 4.09375 | 4 | [] | no_license | /*
Given an array with n objects colored red, white or blue, sort them so that objects of the same color are adjacent, with the colors in the order red, white and blue.
Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.
Note:
You are not suppose to use the library's sort function for this problem.
click to show follow up.
Follow up:
A rather straight forward solution is a two-pass algorithm using counting sort.
First, iterate the array counting number of 0's, 1's, and 2's, then overwrite array with total number of 0's, then 1's and followed by 2's.
Could you come up with an one-pass algorithm using only constant space?
*/
class Solution {
public:
void sortColors(vector<int>& nums) {
mergeSort(nums,0,nums.size()-1);
}
void mergeSort(vector<int>& nums, int left, int right) {
if(left==right) return;
if(right - left == 1) {
if(nums[left]>nums[right]) {
int temp = nums[left];
nums[left] = nums[right];
nums[right] = temp;
}
return;
}
int mid = (left+right)/2;
mergeSort(nums,left,mid-1);
mergeSort(nums,mid,right);
vector<int> new_nums;
int pleft = left, pmid = mid;
while(pleft <= mid-1 && pmid <= right) {
if(nums[pleft]<=nums[pmid]) {
new_nums.push_back(nums[pleft]);
pleft++;
}
else {
new_nums.push_back(nums[pmid]);
pmid++;
}
}
while(pleft != mid) {
new_nums.push_back(nums[pleft]);
pleft++;
}
while(pmid != right+1) {
new_nums.push_back(nums[pmid]);
pmid++;
}
for(int i=left;i<=right;i++) {
nums[i] = new_nums[i-left];
}
}
};
| true |
fcfb161f5145582fc358272b9cfd13677c91ee92 | C++ | CotletkaMan/pusko | /system/ModelingTime/Time.cpp | UTF-8 | 261 | 2.71875 | 3 | [] | no_license | #include "Time.h"
Time::Time(){
time = 0;
timeStep = changeTime();
}
double Time::getCurrentTime(){
return time;
}
double Time::getCurrentStep(){
return timeStep;
}
void Time::nextStep(){
time += timeStep;
timeStep = changeTime();
}
| true |
ef291335f28080ecf169f99b52a64ae48f52e42b | C++ | utkarshavardhana/30-day-leetcoding-challenge | /Week-4/Day-24-LRUCache.cpp | UTF-8 | 1,121 | 3.046875 | 3 | [
"MIT"
] | permissive | class LRUCache {
public:
int size;
list<pair<int,int>> dl;
unordered_map<int, list<pair<int,int>>::iterator> mp;
LRUCache(int capacity) {
size = capacity;
}
int get(int key) {
if(mp.find(key) == mp.end()){
return -1;
}else{
auto it = mp[key];
int val = it->second;
dl.erase(it);
dl.push_front({key,val});
mp[key] = dl.begin();
return val;
}
}
void put(int key, int value) {
if(mp.find(key) != mp.end()){
auto it = mp[key];
dl.erase(it);
}else{
if(mp.size() == size){
auto rit = dl.rbegin();
mp.erase(rit->first);
dl.pop_back();
}
}
dl.push_front({key, value});
mp[key] = dl.begin();
}
};
/**
* Your LRUCache object will be instantiated and called as such:
* LRUCache* obj = new LRUCache(capacity);
* int param_1 = obj->get(key);
* obj->put(key,value);
*/
| true |
bf6855c568a6063ee1d7ce191f7afb5c95eac85c | C++ | heyjing/IPK | /aufgabe1c.cc | UTF-8 | 692 | 3.828125 | 4 | [] | no_license | #include <iostream>
#include <vector>
#include <algorithm>
std::vector<double> reversed(const std::vector<double> &v)
{
std::vector<double> vectornew;
int size = v.size();
for (int i = size - 1; i >= 0; i--)
{
vectornew.push_back(v[i]);
}
for (double value : vectornew)
{
std::cout << value << ";";
}
std::cout << std::endl;
return vectornew;
}
int main()
{
std::vector<double> a = {1, 100, 22, 99};
reversed(a);
std::cout << "----Original-Variable bleibt unverändert-----" << std::endl;
for (double value : a)
{
std::cout << value << ";";
}
std::cout << std::endl;
} | true |
2ac4537a27d7a12ddf1168cab42070a527ccfd69 | C++ | IgorYunusov/Mega-collection-cpp-1 | /Beginning OpenGL Game Programming Source Code/Chapter10/FrustumCulling/md2.cpp | UTF-8 | 9,946 | 2.59375 | 3 | [] | no_license | #include "md2.h"
#include <cstdio>
#include <cmath>
#include <cfloat>
const float SPHERE_PADDING = 10.0;
// this is a bit of a hack, since the sphere isn't guaranteed to completely
// surround the model. However, the results for this demo are satisfactory
void CalculateBoundingSphere(sphere_t &sphere, GLfloat miny, GLfloat maxy)
{
sphere.center.x = 0;
sphere.center.y = (maxy + miny) / 2.0f;
sphere.center.z = 0;
sphere.radius = maxy - sphere.center.y + SPHERE_PADDING;
}
// CMD2Model constructor
CMD2Model::CMD2Model()
{
m_currentFrame = 0; // current keyframe
m_nextFrame = 1; // next keyframe
m_interpol = 0.0; // interpolation percent
m_tris = NULL; // triangle indices
m_texCoords = NULL; // texture coordinate indices
m_verts = NULL; // vertices
m_currentVerts = NULL;
m_texID = 0; // skin/texture
m_state = IDLE;
m_rotate = 0.0;
}
// CMD2Model destructor
CMD2Model::~CMD2Model()
{
Unload();
}
// CMD2Model::Load()
// access: public
// desc: loads model and skin
bool CMD2Model::Load(char *modelFile, char *skinFile, GLfloat scale)
{
// open the model file
FILE *pFile = fopen(modelFile, "rb");
if (pFile == NULL)
return false;
fread(&m_info, sizeof(modelHeader_t), 1, pFile);
m_verts = new xyz_t[m_info.numXYZ * m_info.numFrames];
char *buffer = new char[m_info.numFrames * m_info.framesize];
fseek(pFile, m_info.offsetFrames, SEEK_SET);
fread(buffer, m_info.numFrames, m_info.framesize, pFile);
int i, j;
frame_t *frame;
xyz_t *pVerts;
m_miny = FLT_MAX;
GLfloat maxy = FLT_MIN;
for (j = 0; j < m_info.numFrames; ++j) {
frame = (frame_t*)&buffer[m_info.framesize * j];
pVerts = (xyz_t*)&m_verts[m_info.numXYZ * j];
for (i = 0; i < m_info.numXYZ; i++) {
pVerts[i].x = scale * (frame->scale[0] * frame->fp[i].v[0] + frame->translate[0]);
pVerts[i].z = scale * (frame->scale[1] * frame->fp[i].v[1] + frame->translate[1]);
pVerts[i].y = scale * (frame->scale[2] * frame->fp[i].v[2] + frame->translate[2]);
if (j == 0) {
if (pVerts[i].y < m_miny)
m_miny = pVerts[i].y;
if (pVerts[i].y > maxy)
maxy = pVerts[i].y;
}
}
}
CalculateBoundingSphere(m_boundingSphere, m_miny, maxy);
Move(0, 0, 0);
m_tris = new mesh_t[m_info.numTris];
fseek(pFile, m_info.offsetTris, SEEK_SET);
fread(m_tris, m_info.numTris, sizeof(mesh_t), pFile);
stIndex_t *stTemp = new stIndex_t[m_info.numST];
m_texCoords = new texCoord_t[m_info.numTris * 3];
fseek(pFile, m_info.offsetST, SEEK_SET);
fread(stTemp, m_info.numST, sizeof(stIndex_t), pFile);
int index = 0;
for (i = 0; i < m_info.numTris; i++) {
m_texCoords[index].s = (float)stTemp[m_tris[i].stIndex[0]].s / m_info.skinwidth;
m_texCoords[index++].t = 1.0f - (float)stTemp[m_tris[i].stIndex[0]].t / m_info.skinheight;
m_texCoords[index].s = (float)stTemp[m_tris[i].stIndex[1]].s / m_info.skinwidth;
m_texCoords[index++].t = 1.0f - (float)stTemp[m_tris[i].stIndex[1]].t / m_info.skinheight;
m_texCoords[index].s = (float)stTemp[m_tris[i].stIndex[2]].s / m_info.skinwidth;
m_texCoords[index++].t = 1.0f - (float)stTemp[m_tris[i].stIndex[2]].t / m_info.skinheight;
}
m_currentVerts = new xyz_t[m_info.numTris * 3];
// close file and free memory
fclose(pFile);
delete[] buffer;
CTargaImage image;
image.Load(skinFile);
glGenTextures(1, &m_texID);
glBindTexture(GL_TEXTURE_2D, m_texID);
gluBuild2DMipmaps(GL_TEXTURE_2D, 3, image.GetWidth(), image.GetHeight(), GL_RGB, GL_UNSIGNED_BYTE, image.GetImage());
image.Release();
m_currentFrame = 0;
m_nextFrame = 1;
m_interpol = 0.0;
// animate at least one frame to make sure that m_currentVerts gets initialized
SetAnimation(IDLE);
Animate(0);
return TRUE;
}
void CMD2Model::SetAnimation(int state, int nextState)
{
switch (state) {
case RUN:
m_startFrame = 40;
m_endFrame = 45;
break;
case ATTACK:
m_startFrame = 46;
m_endFrame = 53;
break;
case PAIN1:
m_startFrame = 54;
m_endFrame = 57;
break;
case PAIN2:
m_startFrame = 58;
m_endFrame = 61;
break;
case PAIN3:
m_startFrame = 62;
m_endFrame = 65;
break;
case JUMP:
m_startFrame = 66;
m_endFrame = 71;
break;
case FLIPOFF:
m_startFrame = 72;
m_endFrame = 83;
break;
case SAULTE:
m_startFrame = 84;
m_endFrame = 94;
break;
case TAUNT:
m_startFrame = 95;
m_endFrame = 111;
break;
case WAVE:
m_startFrame = 112;
m_endFrame = 122;
break;
case POINT:
m_startFrame = 123;
m_endFrame = 134;
break;
case CROUCH_IDLE:
m_startFrame = 135;
m_endFrame = 153;
break;
case CROUCH_WALK:
m_startFrame = 154;
m_endFrame = 159;
break;
case CROUCH_ATTACK:
m_startFrame = 160;
m_endFrame = 168;
break;
case CROUCH_PAIN:
m_startFrame = 169;
m_endFrame = 172;
break;
case CROUCH_DEATH:
m_startFrame = 173;
m_endFrame = 177;
break;
case DEATH1:
m_startFrame = 178;
m_endFrame = 183;
break;
case DEATH2:
m_startFrame = 184;
m_endFrame = 189;
break;
case DEATH3:
m_startFrame = 190;
m_endFrame = 197;
break;
case IDLE:
m_startFrame = 0;
m_endFrame = 39;
break;
default:
return;
}
if (m_state != state) {
m_currentFrame = m_startFrame;
m_nextFrame = m_startFrame + 1;
}
m_state = state;
m_nextState = nextState;
}
void CMD2Model::SetAnimationCustom(int start, int end)
{
if (start < 0)
start = 0;
if (start >= m_info.numFrames)
start = m_info.numFrames - 1;
if (end < 0)
end = 0;
if (end >= m_info.numFrames)
end = m_info.numFrames - 1;
m_startFrame = start;
m_endFrame = end;
m_state = _CUSTOM;
m_nextState = _CUSTOM;
}
void CMD2Model::Animate(float seconds)
{
xyz_t *vList; // current frame vertices
xyz_t *nextVList; // next frame vertices
int i; // index counter
float x1, y1, z1; // current frame point values
float x2, y2, z2; // next frame point values
if (m_startFrame > m_currentFrame) {
m_currentFrame = m_startFrame;
}
if (m_startFrame < 0 || m_endFrame < 0)
return;
if (m_startFrame >= m_info.numFrames || m_endFrame >= m_info.numFrames)
return;
m_interpol += KEYFRAMES_PER_S * seconds; // increase percentage of interpolation between frames
if (m_interpol >= 1.0) {
m_interpol = 0.0f;
m_currentFrame++;
m_nextFrame = m_currentFrame + 1;
if (m_currentFrame > m_endFrame) {
if (m_nextState == _REPEAT || m_state == _CUSTOM) {
m_currentFrame = m_startFrame;
m_nextFrame = m_currentFrame + 1;
} else {
SetAnimation(m_nextState, _REPEAT);
}
}
if (m_nextFrame > m_endFrame)
m_nextFrame = m_startFrame;
}
vList = &m_verts[m_info.numXYZ * m_currentFrame];
nextVList = &m_verts[m_info.numXYZ * m_nextFrame];
for (i = 0; i < m_info.numTris * 3; i++) {
xyz_t &vertex = m_currentVerts[i];
// get first points of each frame
x1 = vList[m_tris[i / 3].meshIndex[i % 3]].x;
y1 = vList[m_tris[i / 3].meshIndex[i % 3]].y;
z1 = vList[m_tris[i / 3].meshIndex[i % 3]].z;
x2 = nextVList[m_tris[i / 3].meshIndex[i % 3]].x;
y2 = nextVList[m_tris[i / 3].meshIndex[i % 3]].y;
z2 = nextVList[m_tris[i / 3].meshIndex[i % 3]].z;
// store first interpolated vertex of triangle
vertex.x = x1 + m_interpol * (x2 - x1);
vertex.y = y1 + m_interpol * (y2 - y1);
vertex.z = z1 + m_interpol * (z2 - z1);
}
}
void CMD2Model::Render()
{
glPushMatrix();
glTranslatef(m_pos.x, m_pos.y, m_pos.z);
glRotatef(m_rotate, 0, 1, 0);
glBindTexture(GL_TEXTURE_2D, m_texID);
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glVertexPointer(3, GL_FLOAT, 0, m_currentVerts);
glTexCoordPointer(2, GL_FLOAT, 0, m_texCoords);
glDrawArrays(GL_TRIANGLES, 0, m_info.numTris * 3);
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
glDisableClientState(GL_VERTEX_ARRAY);
glPopMatrix();
}
// Unload()
// desc: unloads model data from memory
void CMD2Model::Unload()
{
delete [] m_tris;
m_tris = NULL;
delete [] m_verts;
m_verts = NULL;
delete [] m_texCoords;
m_texCoords = NULL;
delete [] m_currentVerts;
m_currentVerts = NULL;
glDeleteTextures(1, &m_texID);
}
void CMD2Model::Move(GLfloat x, GLfloat y, GLfloat z)
{
m_pos.x = x;
m_pos.y = y - m_miny;
m_pos.z = z;
m_boundingSphere.center.x = x;
m_boundingSphere.center.y = y + m_boundingSphere.radius - SPHERE_PADDING;
m_boundingSphere.center.z = z;
} | true |
52e013a2673f69c7575572e30a5395e7cc1ea893 | C++ | cache-tlb/problem_solving | /ZOJ/Switch#1622.cpp | UTF-8 | 337 | 2.890625 | 3 | [] | no_license | #include<iostream>
using namespace std;
int main()
{
int n;
while(cin >> n){
int a = 0, b = 0, temp = 0;
for(int i = 0; i < n; i++){
cin >> temp;
if(i%2){
if(temp == 1) a++;
else b++;
}
else{
if(temp == 1) b++;
else a++;
}
}
if(a < b) cout << a << endl;
else cout << b << endl;
}
return 0;
}
| true |
edf0335a86e5bcad81942c276bcb41b0b6d88ca7 | C++ | MORTAL2000/jubilant-funicular | /include/nta/SpriteFont.h | UTF-8 | 3,659 | 2.8125 | 3 | [
"MIT"
] | permissive | #ifndef NTA_SPRITEFONT_H_INCLUDED
#define NTA_SPRITEFONT_H_INCLUDED
#include <map>
#include <SDL2/SDL_ttf.h>
#include "nta/SpriteBatch.h"
#define FIRST_PRINTABLE_CHAR ((char)32) //space
#define LAST_PRINTABLE_CHAR ((char)126) //~
#define NUM_PRINTABLE_CHARS (LAST_PRINTABLE_CHAR-FIRST_PRINTABLE_CHAR+1)
#define SPRITE_FONT_TAB_SIZE 4
namespace nta {
class SpriteFont;
class ContextData;
/// represents a single char in the texture
struct CharGlyph {
/// the rectangle containing this glyph in the texture
glm::vec4 uvRect;
/// the size of the rendered glyph
glm::vec2 size;
};
/// represents the organization of a texture containing the characters
class FontMap {
private:
/// a rectangle representing the location of a char in the FontMap
struct CharRect {
CharRect(){}
CharRect(glm::vec2 tl, glm::vec2 d, bool a) : topLeft(tl), dimensions(d), addedToMap(a) {
}
glm::vec2 topLeft;
glm::vec2 dimensions;
bool addedToMap;
};
/// returns whether or not rect is overlapping with any existing CharRect
bool isOverlapping(const CharRect& rect) const;
/// the rectangles making up the FontMap
CharRect* m_rects = nullptr;
public:
/// constructor and destructor
FontMap();
~FontMap();
/// returns the dimensions of the rectangle that contains the FontMap
glm::vec2 getBoundingDimensions() const;
/// adds a rectangle and associates it with c (replacing any preexisting rectangle)
void addRect(char c, crvec2 dimensions);
/// positions map so that the topleft is at (0,0)
void position();
friend SpriteFont;
};
/// Loads in a .ttf file, creates a font texture from it which is then used to render text
class SpriteFont {
private:
/// Initializes the SpriteFont
///
/// Creates a texture from the font
void init(TTF_Font* font);
/// a collection of glyphs for each char
CharGlyph* m_charGlyphs = nullptr;
/// the idea of the generated texture
GLuint m_texId = 0;
/// the height of the font
int m_fontHeight = 0;
public:
SpriteFont() {}
/// destructor
~SpriteFont() { destroy(); }
/// returns the dimensions of the rectangle containing the text
glm::vec2 measure(crstring text) const;
/// returns m_fontHeight
int font_height() const { return m_fontHeight; }
/// Returns the (id of) the texture used for rendering font
GLuint getTexture() const { return m_texId; }
/// renders text with specified location, color, scale, etc.
void drawText(SpriteBatch& batch, crstring text, crvec2 topLeft, crvec2 scale,
crvec4 color = glm::vec4(1), float depth = NTA_DEFAULT_DEPTH) const;
void drawText(SpriteBatch& batch, crstring text, crvec4 posRect, crvec4 color = glm::vec4(1),
float depth = NTA_DEFAULT_DEPTH) const;
void drawText(SpriteBatch& batch, crvec2 corner1, crvec2 corner2, crstring text,
crvec4 color = glm::vec4(1), float depth = NTA_DEFAULT_DEPTH) const;
/// renders texture
void drawTexture(SpriteBatch& batch, crvec4 posRect = glm::vec4(-100, 100, 200, 200)) const;
/// Destroys this SpriteFont
void destroy();
friend ContextData;
};
}
#endif // NTA_SPRITEFONT_H_INCLUDED
| true |
88a5c288676ff35b14ec6a0c616b9851486d58f0 | C++ | TeodoraAleksic/n-body-problem | /src/quad.cpp | UTF-8 | 2,933 | 2.890625 | 3 | [] | no_license | #include "quad.hpp"
Quad::Quad(Quad *qp, const Particles& p, float w, float x, float y){
parent = qp;
width = w;
qx = x;
qy = y;
partIndexes = std::vector<int>();
initQuad(p);
}
Quad::~Quad(){
delete nw;
delete ne;
delete sw;
delete se;
}
void Quad::initQuad(const Particles& particles){
// Parent quad number of particles
int parentNumOfParticles;
// Parent particles indices
std::vector<int> parentIndexes = std::vector<int>();
// Gets number of particles and particle indices if quad is not the tree root
if (parent != nullptr){
parentNumOfParticles = (int)parent->partIndexes.size();
parentIndexes = parent->partIndexes;
}
else{
parentNumOfParticles = particles.numOfParticles;
}
// Numbers of particles in each sub-quad
int numNW = 0;
int numNE = 0;
int numSW = 0;
int numSE = 0;
// Searches parent particles and finds ones contained within the quad
for (int i = 0; i < parentNumOfParticles; ++i){
// Gets particle mass and position
float m = (parent != nullptr) ? particles.mass[parentIndexes[i]] : particles.mass[i];
float x = (parent != nullptr) ? particles.positionX[parentIndexes[i]] : particles.positionX[i];
float y = (parent != nullptr) ? particles.positionY[parentIndexes[i]] : particles.positionY[i];
// Checks if particle in quad
if (isPartInQuad(x, y, width, qx, qy)){
// Saves particle index
partIndexes.push_back((parent != nullptr) ? parentIndexes[i] : i);
// Calculates quad mass and center of mass
mass += m;
cx += m * x;
cy += m * y;
// Increases sub-quad particle number if particle is contained within sub-quad
numNW = isPartInQuad(x, y, width / 2, qx, qy + width / 2) ? (numNW + 1) : numNW;
numNE = isPartInQuad(x, y, width / 2, qx + width / 2, qy + width / 2) ? (numNE + 1) : numNE;
numSW = isPartInQuad(x, y, width / 2, qx, qy) ? (numSW + 1) : numSW;
numSE = isPartInQuad(x, y, width / 2, qx + width / 2, qy) ? (numSE + 1) : numSE;
}
}
// Calculates center of mass coordinates
cx /= mass;
cy /= mass;
// Creates sub-quads if they contain particles
if (partIndexes.size() > 1){
nw = (numNW > 0) ? new Quad(this, particles, width / 2, qx, qy + width / 2) : nw;
ne = (numNE > 0) ? new Quad(this, particles, width / 2, qx + width / 2, qy + width / 2) : ne;
sw = (numSW > 0) ? new Quad(this, particles, width / 2, qx, qy) : sw;
se = (numSE > 0) ? new Quad(this, particles, width / 2, qx + width / 2, qy) : se;
numOfQuads += (numNW > 0) ? (nw->numOfQuads) : 0;
numOfQuads += (numNE > 0) ? (ne->numOfQuads) : 0;
numOfQuads += (numSW > 0) ? (sw->numOfQuads) : 0;
numOfQuads += (numSE > 0) ? (se->numOfQuads) : 0;
}
++numOfQuads;
}
bool Quad::isPartInQuad(float x, float y, float w, float qx, float qy){
// Checks if particle is contained within quad
if (((x >= qx) && (x < (qx + w))) && ((y >= qy) && (y < (qy + w)))){
return true;
}
else{
return false;
}
} | true |
b517741eb8cebcb30119a2b914ad573bdd9ff4ae | C++ | r03er7/algorithms | /[Code] algorytmika praktyczna/Programy_z_komentarzami/programy_z_komentarzami/alchemy.cpp | WINDOWS-1250 | 5,804 | 2.9375 | 3 | [] | no_license | #include <cstdio>
#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
using namespace std;
// Dwa z najczesciej uzywanych typow o dlugich nazwach - ich skrocenie jest bardzo istotne
typedef vector<int> VI;
typedef long long LL;
// W programach bardzo rzadko mozna znalezc w pelni zapisana instrukcje petli. Zamiast niej, wykorzystywane sa trzy nastepujace makra:
// FOR - petla zwiekszajaca zmienna x od b do e wlacznie
#define FOR(x, b, e) for(int x = b; x <= (e); ++x)
// FORD - petla zmniejszajaca zmienna x od b do e wlacznie
#define FORD(x, b, e) for(int x = b; x >= (e); --x)
// REP - petla zwiekszajaca zmienna x od 0 do n. Jest ona bardzo czesto wykorzystywana do konstruowania i przegladania struktur danych
#define REP(x, n) for(int x = 0; x < (n); ++x)
// Makro VAR(v,n) deklaruje nowa zmienna o nazwie v oraz typie i wartosci zmiennej n. Jest ono czesto wykorzystywane podczas operowania na iteratorach struktur danych z biblioteki STL, ktorych nazwy typow sa bardzo dlugie
#define VAR(v, n) __typeof(n) v = (n)
// ALL(c) reprezentuje pare iteratorow wskazujacych odpowiednio na pierwszy i za ostatni element w strukturach danych STL. Makro to jest bardzo przydatne chociazby w przypadku korzystania z funkcji sort, ktora jako parametry przyjmuje pare iteratorow reprezentujacych przedzial elementow do posortowania.
#define ALL(c) (c).begin(), (c).end()
// Ponizsze makro sluzy do wyznaczania rozmiaru struktur danych STL. Uzywa sie go w programach, zamiast pisac po prostu x.size() z uwagi na fakt, iz wyrazenie x.size() jest typu unsigned int i w przypadku porownywania z typem int, w procesie kompilacji generowane jest ostrzezenie.
#define SIZE(x) ((int)(x).size())
// Bardzo pozyteczne makro, sluzace do iterowania po wszystkich elementach w strukturach danych STL.
#define FOREACH(i, c) for(VAR(i, (c).begin()); i != (c).end(); ++i)
// Skrot - zamiast pisac push_back podczas wstawiania elementow na koniec struktury danych, takiej jak vector, wystarczy napisac PB
#define PB push_back
// Podobnie - zamiast first bedziemy pisali po prostu ST
#define ST first
// a zamiast second - ND.
#define ND second
#include <set>
// Wartosc INF jest wykorzystywana jako reprezentacja nieskoczonosci. Ma ona wartosc 1000000001, a nie 2147483647 (najwieksza wartosc typu int) ze wzgledu na dwa fakty - prosty zapis oraz brak przepelnienia wartosci zmiennej w przypadku dodawania dwoch nieskoczonosci do siebie: ((int) 2147483647 + (int) 2147483647 = -2).
const int INF = 1000000001;
template<class V, class E> struct Graph {
// Typ krawedzi (Ed) dziedziczy po typie zawierajacym dodatkowe informacje zwiazane z krawedzia (E). Zawiera on rowniez pole v, okreslajace numer wierzcholka, do ktorego prowadzi krawedz. Zaimplementowany konstruktor pozwala na skrocenie zapisu wielu funkcji korzystajacych ze struktury grafu.
struct Ed : E {
int v;
Ed(E p, int w) : E(p), v(w) {}
};
// Typ wierzcholka (Ve) dziedziczy po typie zawierajacym dodatkowe informacje z nim zwiazane (V) oraz po wektorze krawedzi. To drugie dziedziczenie moze wydawac sie na pierwszy rzut oka stosunkowo dziwne, lecz jest ono przydatne - umozliwia latwe iterowanie po wszystkich krawedziach wychodzacych z wierzcholka v: FOREACH(it, g[v])
struct Ve : V,vector<Ed> {};
// Wektor wierzcholkow w grafie
vector<Ve> g;
// Konstruktor grafu - przyjmuje jako parametr liczbe wierzcholkow
Graph(int n=0) : g(n) {}
// Funkcja dodajaca do grafu nowa krawedz skierowana z wierzcholka b do e, zawierajaca dodatkowe informacje okreslone przez zmienna d.
void EdgeD(int b, int e, E d = E()) {g[b].PB(Ed(d,e));}
// Operator okreslajacy porzadek liniowy (w kolejnosci rosnacych odleglosci od zrodla) na wierzcholkach grafu
struct djcmp{
bool operator()(const Ve* a, const Ve* b) const{
return (a->t==b->t) ? a<b : a->t < b->t;
}
};
// Funkcja realizujaca algorytm Dijkstry. Dla kazdego wierzcholka wyznaczana jest odleglosc od zrodla wyszukiwania s i umieszczana w zmiennej t oraz numer wierzcholka-ojca w drzewie najkrotszych sciezek - umieszczany w zmiennej s. Dla wierzcholkow nieosiagalnych ze zrodla t = INF, s = -1
void Dijkstra(int s){
// Kolejka priorytetowa sluzaca do wyznaczania najblizszych wierzcholkow
set<Ve*, djcmp> k;
FOREACH(it, g) it->t = INF, it->s = -1;
// Na poczatku wstawiany jest do kolejki wierzcholek zrodlo
g[s].t = 0; g[s].s = -1; k.insert(&g[s]);
// Dopoki sa jeszcze nieprzetworzone wierzcholki...
while(!k.empty()){
// Wybierz wierzcholek o najmniejszej odleglosci i usu go z kolejki
Ve *y = *(k.begin());
k.erase(k.begin());
// Dla kazdej krawedzi, wychodzacej z aktualnie przetwarzanego wierzcholka, sprobuj zmniejszyc odleglosc do wierzcholka, do ktorego ta krawedz prowadzi
FOREACH(it, *y) if (g[it->v].t > y->t+it->l){
k.erase(&g[it->v]); g[it->v].t=y->t+it->l;
g[it->v].s=y-&g[0]; k.insert(&g[it->v]);
}
}
}
};
struct Vs {int t,s;};
struct Ve {int l;};
int main() {
int n,m,b,e;
// Wczytaj liczbe roznych metali
cin >> n;
int price[n];
// Wczytaj ceny metali
REP(x, n) cin >> price[x];
Graph<Vs,Ve> gr(n), grTr(n);
// Wczytaj liczbe znanych przemian
cin >> m;
Ve str;
// Stworz graf opisujacy dozwolone przemiany (grTr jest grafem transponowanym przemian)
REP(x, m) {
cin >> b >> e >> str.l;
gr.EdgeD(--b, --e, str);
grTr.EdgeD(e, b, str);
}
// Dla kazdego metalu wyznacz koszt uzyskania go ze zlota
gr.Dijkstra(0);
// Dla kazdego metalu wyznacz koszt przemiany go w zloto
grTr.Dijkstra(0);
int res = INF;
// Wyznacz najbardziej oplacalny koszt
REP(x, n) res = min(res, price[x]/2+gr.g[x].t+grTr.g[x].t);
// Wypisz wynik
cout << res << endl;
return 0;
}
| true |
1257eb8127fb41445607a4ef525c2a6b509aead4 | C++ | nickzuck/Data-Structures-and-Algorithms | /disjoint_set_union_basic.cpp | UTF-8 | 2,329 | 4 | 4 | [] | no_license | /*Basic and naive implementation of disjoint set data structure*/
//Time Complexity : O(n^2)
#include<iostream>
#include<algorithm>
#define MAX 1000
using namespace std ;
//Manage the connectivity of elements
//stores the set number corresponding to an element of array
//storage[i] gives the set number of ith element
int storage[MAX] ;
int lenStorage ;
//Makes the individual set for each element in the array ...for n elements of the array n sets are formed
void make_set(int a[] ){
int n = lenStorage;
for(int i = 0; i<n ; i++){
storage[i] = i ;
}
}
//union of destination(index) and source(index)...just like friendship of two more people..source element going to be friend with destinaton
//So the entire group(set number) of source will be changed
void union_set(int source , int destination)
{
int n = lenStorage;
//retrive the set number of source element
int temp = storage[source] ;
//if a element set number belongs to source set number..then change it's set number to destination set number
for(int i = 0 ;i<n ;i++){
if(storage[i] == temp){
storage[i] = storage[destination];
}
}
}
//find the set number of the given index
int find_set(int element){
return storage[element];
}
//checks wether A and B are connected or not
bool isConnected(int A , int B){
if(storage[A] == storage[B]){
return true ;
}
else
return false;
}
void displayStorage(){
for(int i = 0 ;i<lenStorage ; i++){
cout << storage[i] << " " ;
}
cout << endl;
}
//Driver program
int main()
{
int arr[MAX] , n , t;
//Minimum is 10 because the driver program contains the driver for numbers between 1 to 10
cout << "Enter the number of elements..Min - 10...Max limit(" << MAX << ")\t";
cin >> n ;
lenStorage = n ;
//cout << "Enter the elements of the array\n";
//for(int i = 0 ; i<n ;i++){
// cin >> arr[i];
//}
make_set(arr);
cout << "After make set\n";
displayStorage();
union_set(2,1);
cout << "After union of 1 and 2\n";
displayStorage();
union_set(4,3);
union_set(8,4);
union_set(9,3);
cout << "After union of 4 ,3 , 8 ,9\n" ;
displayStorage();
cout << "Set of element with index 4 = ";
cout << find_set(4) << endl;
cout << "Is 1 and 2 connected ? " ;
if(isConnected)
cout << "True" << endl ;
else
cout << "False" << endl;
return 0 ;
}
| true |
78b728e525e15810f15c24014e1f42b88903019c | C++ | danieljluna/Project-Perfect-Citizen | /Project-Perfect-Citizen/Code/Game/emailListElementRenderComponent.h | UTF-8 | 3,057 | 2.828125 | 3 | [] | no_license | #pragma once
#include "../Engine/renderComponent.h"
#include "Email.h"
#include <SFML/Graphics/Font.hpp>
#include <SFML/Graphics/RectangleShape.hpp>
namespace sf {
class Sprite;
class Text;
};
///////////////////////////////////////////////////////////////////////
/// @brief Designated render component for an email block in the inbox
/// @author Alex Vincent
/// @details Consists of a box, text, and an email sprite
///////////////////////////////////////////////////////////////////////
namespace ppc {
class emailListElementRenderComponent : public ppc::RenderComponent {
private:
///////////////////////////////////////////////////////////////////////
/// @brief The bounding box containing the emailListElement
///////////////////////////////////////////////////////////////////////
sf::RectangleShape emailListElementBox;
///////////////////////////////////////////////////////////////////////
/// @brief The sprite holding the text
///////////////////////////////////////////////////////////////////////
sf::Sprite* sprite;
///////////////////////////////////////////////////////////////////////
/// @brief The drawable text element for the subject line
///////////////////////////////////////////////////////////////////////
sf::Text* subjectText;
///////////////////////////////////////////////////////////////////////
/// @brief The drawable text element for the sender
///////////////////////////////////////////////////////////////////////
sf::Text* fromText;
///////////////////////////////////////////////////////////////////////
/// @brief The font of the drawable text element
///////////////////////////////////////////////////////////////////////
sf::Font font;
static const int size = 128;
int indent = 10;
public:
///////////////////////////////////////////////////////////////////////
/// @brief The font of the drawable text element
/// @param The reference to the drawable font
/// @param A reference to the email to display
/// @param An integer specifying the box's X position
/// @param An integer specifying the box's Y position
/// @param An integer specifying the box's Width
/// @param An integer specifying the box's Height
/// @param An integer specifying the text's x position
/// @param An integer specifying the text's y position
/// @param An integer specifying the text/font's size
///////////////////////////////////////////////////////////////////////
emailListElementRenderComponent(sf::Font& f, Email& email,
int boxX, int boxY, int boxWidth, int boxHeight, int x, int y, int size);
~emailListElementRenderComponent();
///////////////////////////////////////////////////////////////////////
/// @brief Simple getter returning the bounds of the element box
///////////////////////////////////////////////////////////////////////
sf::FloatRect getListElementBoxBounds();
virtual void draw(sf::RenderTarget & target, sf::RenderStates states) const;
virtual void recieveMessage(msgType code) override;
};
} | true |
91366b5e5574f5e0acbfbbb9c1c891aef9dfcbb5 | C++ | micgro42/KonGrad | /src/test.cc | UTF-8 | 14,144 | 2.59375 | 3 | [] | no_license | #define BOOST_TEST_MODULE kongrad_test
#include <boost/test/unit_test.hpp>
#include <boost/test/floating_point_comparison.hpp>
#include <boost/log/core.hpp>
#include <boost/log/trivial.hpp>
#include <boost/log/expressions.hpp>
#include "linsysequ.hh"
#define DEFINE_GLOBAL
//#include "global.h"
#include "geom_pbc.c"
#include <vector>
#include <algorithm> //std::sort
/**
* @file test.cc
*
* @brief this file contains the unit test suite for the LinSysEqu class
*
*
*
*
*/
/**
*
* @class F
*
* @brief Fixture to setup and teardown the class instances for the unit tests where neccesary
*
*
*/
namespace logging = boost::log;
struct F {
// F() : i( 0 ) { std::cout << "setup" << std::endl; }
F(){
cout << endl;
logging::core::get()->set_filter (logging::trivial::severity >= logging::trivial::info);
}
~F() { }
LinSysEqu testSLE;
};
struct scalarfield {
scalarfield(){
cout << endl;
logging::core::get()->set_filter (logging::trivial::severity >= logging::trivial::info);
ndim=2;
lsize = (int *) malloc((ndim+1) * sizeof(int));
lsize[1]=3;
lsize[2]=3;
geom_pbc();
}
~scalarfield() { free(lsize); }
LinSysEqu testSLE;
};
BOOST_AUTO_TEST_SUITE (kongrad_test)
/**
* @brief test if that the the Laplaceoperator is correctly applied to a small 2-D field
*
* @details The Input field looks like:<br>
* 1 2 1 <br>
* 2 3 2<br>
* 1 2 1
*
* The output field should look like:<br>
* -2 1 -2<br>
* 1 4 1<br>
* -2 1 -2
*
* This unittest tests the function LinSysEqu::matrixVectorLaplace
*/
BOOST_FIXTURE_TEST_CASE( matrixVectorLaplace_m0, scalarfield ){
vector <double> vecin;
vector <double> vecout;
testSLE.setmass(0);
vecin.push_back(1);
vecin.push_back(2);
vecin.push_back(1);
vecin.push_back(2);
vecin.push_back(3);
vecin.push_back(2);
vecin.push_back(1);
vecin.push_back(2);
vecin.push_back(1);
testSLE.matrixVectorLaplace(vecin, vecout);
BOOST_CHECK_EQUAL(vecout.at(0),-2);
BOOST_CHECK_EQUAL(vecout.at(1),1);
BOOST_CHECK_EQUAL(vecout.at(2),-2);
BOOST_CHECK_EQUAL(vecout.at(3),1);
BOOST_CHECK_EQUAL(vecout.at(4),4);
BOOST_CHECK_EQUAL(vecout.at(5),1);
BOOST_CHECK_EQUAL(vecout.at(6),-2);
BOOST_CHECK_EQUAL(vecout.at(7),1);
BOOST_CHECK_EQUAL(vecout.at(8),-2);
}
/**
* test if that the skalar product of (2;2) and (2;2) is indeed 8.
*
* This unittest tests the function LinSysEqu::skalarProd
*/
BOOST_FIXTURE_TEST_CASE( skalarProd, F ){
vector<double> b(2,2);
BOOST_CHECK_EQUAL( testSLE.skalarProd(b,b) , 8 );
}
/**
* test if that the skalar product of (2;2) and (2;2) is indeed 8.
*
* This unittest tests the function LinSysEqu::skalarProd
*/
BOOST_FIXTURE_TEST_CASE( skalarProd_2, F ){
vector<double> q;
q.push_back(1/9.);
q.push_back(4/9.);
q.push_back(7/9.);
BOOST_CHECK_CLOSE( testSLE.skalarProd(q,q) , 22/27. ,0.000001); //tolerance 10^-8
}
/**
* test if some small integers are subtracted from each other correctly.
*
* This unittest tests the function LinSysEqu::diffVector
*/
BOOST_FIXTURE_TEST_CASE( diffVector, F ){
vector<double> a,b,diff;
for (int i=1;i<=5;++i){
a.push_back(i);
b.push_back(i+1);
}
BOOST_REQUIRE(a.size()==b.size());
testSLE.diffVector(a, b, diff);
for (int i=0;i<5;++i){
BOOST_CHECK_EQUAL(diff.at(i),-1);
}
}
/**
* test if some small integers are summed correctly.
*
* This unittest tests the function LinSysEqu::sumVector
*/
BOOST_FIXTURE_TEST_CASE( sumVector, F ){
vector<double> a,b,sum;
for (int i=1;i<=5;++i){
a.push_back(i);
b.push_back(i+1);
}
BOOST_REQUIRE(a.size()==b.size());
testSLE.sumVector(a, b, sum);
for (int i=0;i<5;++i){
BOOST_CHECK_EQUAL(sum.at(i),(i+i+3));
}
}
/**
* test if some small integers are summed correctly.
*
* This unittest tests the function LinSysEqu::addVector
*/
BOOST_FIXTURE_TEST_CASE( addVector, F ){
vector<double> vecin1,vecin2,sum;
double alpha,beta;
alpha=0.5;
beta=-0.5;
for (int i=0;i<5;++i){
vecin1.push_back(i+0.75);
vecin2.push_back(i+0.5);
}
BOOST_REQUIRE(vecin1.size()==vecin2.size());
testSLE.addVector(alpha, vecin1, beta, vecin2, sum);
for (int i=0;i<5;++i){
BOOST_CHECK_EQUAL(sum.at(i),0.125);
}
}
/**
* test if this function is correct if the output-vector is one of the input-vectors
*
* This unittest tests the function LinSysEqu::addVector
*/
BOOST_FIXTURE_TEST_CASE( addVector_self, F ){
vector<double> vecin1,vecin2;
double alpha,beta;
alpha=0.5;
beta=-0.5;
for (int i=0;i<5;++i){
vecin1.push_back(i+0.75);
vecin2.push_back(i+0.5);
}
BOOST_REQUIRE(vecin1.size()==vecin2.size());
testSLE.addVector(alpha, vecin1, beta, vecin2, vecin1);
for (int i=0;i<5;++i){
BOOST_CHECK_EQUAL(vecin1.at(i),0.125);
}
}
/**
* test if this function is correct if the output-vector is one of the input-vectors, different set of numbers from addVector_self
*
*
* This unittest tests the function LinSysEqu::addVector
*/
BOOST_FIXTURE_TEST_CASE( addVector_self_2, F ){
vector<double> vecin1,vecin2;
double alpha,beta;
alpha=1;
beta=-2/3.;
vecin1.push_back(1/3.);
vecin1.push_back(2/3.);
vecin1.push_back(1);
vecin2.push_back(1/3.);
vecin2.push_back(1/3.);
vecin2.push_back(1/3.);
BOOST_REQUIRE(vecin1.size()==vecin2.size());
testSLE.addVector(alpha, vecin1, beta, vecin2, vecin1);
BOOST_CHECK_EQUAL(vecin1.at(0),1./9);
BOOST_CHECK_EQUAL(vecin1.at(1),4./9);
BOOST_CHECK_EQUAL(vecin1.at(2),7./9);
}
/**
* test if a vector of precise doubles is correctly multiplied by another double
*
* This unittest tests the function LinSysEqu::skalarVector .
*/
BOOST_FIXTURE_TEST_CASE( skalarVector, F ){
vector<double> vecin,prod;
double scalar=2.5;
for (int i=0;i<5;++i){
vecin.push_back(i+0.5);
}
testSLE.skalarVector(scalar, vecin, prod);
double truth;
for (int i=0;i<5;++i){
truth=(i+0.5)*2.5;
BOOST_CHECK_EQUAL(prod.at(i),truth);
}
}
/**
* test if the functions returns the correct result if the output-vector is also the input-vector
*
* This unittest tests the function LinSysEqu::skalarVector .
*/
BOOST_FIXTURE_TEST_CASE( skalarVector_self, F ){
vector<double> vecin;
double scalar=2.5;
for (int i=0;i<5;++i){
vecin.push_back(i+0.5);
}
testSLE.skalarVector(scalar, vecin, vecin);
double truth;
for (int i=0;i<5;++i){
truth=(i+0.5)*2.5;
BOOST_CHECK_EQUAL(vecin.at(i),truth);
}
}
/**
* @brief test that a diagonal matrix and a vector are multiplied correctly
*
* @details This unittest tests the function LinSysEqu::matrixVector
*/
BOOST_FIXTURE_TEST_CASE( matrixVector, F ){
vector<double> vecin(3,1);
vector<double> vecout;
vector< vector<double> > matrix;
vector<double> line;
for (int i=0;i<3;++i){
line.assign(3,0);
line.at(i)=i;
matrix.push_back(line);
}
testSLE.setMatrix(matrix);
testSLE.matrixVector(vecin, vecout);
for (int i=0;i<3;++i){
BOOST_CHECK_EQUAL(vecout.at(i),i);
}
}
/**
* @brief test that a diagonal matrix and a vector are multiplied correctly
*
* @details This unittest tests the function LinSysEqu::solveLSE(const vector<double> &startvec, vector<double> &vecout)
*/
BOOST_FIXTURE_TEST_CASE(solveSLE_sparseMatrix, F){
//create 10x10 unit matrix
vector< vector<double> > matrix;
vector<double> line,b,startvector;
for (int i=0;i<10;++i){
line.assign(10,0);
line.at(i)=i+1;
matrix.push_back(line);
b.push_back(i+1);
startvector.push_back(2);
}
testSLE.setMatrix(matrix);
testSLE.setb(b);
vector<double> resultvector;
int exitcode=testSLE.solveLSE("sparseMatrix",startvector, resultvector);
BOOST_REQUIRE(exitcode==0);
for( vector<double>::const_iterator i = resultvector.begin(); i != resultvector.end(); ++i){
BOOST_CHECK_CLOSE(*i,1,0.000001); //tolerance 10^-8
}
}
/**
*
*
* @details this test goes the opposite direction of the test BOOST_FIXTURE_TEST_CASE( matrixVectorLaplace_m0, scalarfield )
* the startvector is the "known right side"
*/
BOOST_FIXTURE_TEST_CASE(solveSLE_LaplaceOp_periodic_1, scalarfield){
vector <double> b,startvector,resultvector, controlvector;
testSLE.setmass(0);
b.push_back(-2);
b.push_back(1);
b.push_back(-2);
b.push_back(1);
b.push_back(4);
b.push_back(1);
b.push_back(-2);
b.push_back(1);
b.push_back(-2);
testSLE.setb(b);
controlvector.push_back(1);
controlvector.push_back(2);
controlvector.push_back(1);
controlvector.push_back(2);
controlvector.push_back(3);
controlvector.push_back(2);
controlvector.push_back(1);
controlvector.push_back(2);
controlvector.push_back(1);
int exitcode=testSLE.solveLSE("Laplace",b, resultvector);
BOOST_REQUIRE(exitcode==0);
double c=resultvector.at(0)-controlvector.at(0); // the field is only calculated upto a constant
for (int i=0;i<9;++i){
BOOST_CHECK_CLOSE(resultvector.at(i),controlvector.at(i)+c,0.000001); //tolerance 10^-8
}
}
/// the startvector is always the same number
BOOST_FIXTURE_TEST_CASE(solveSLE_LaplaceOp_periodic_2, scalarfield){
vector <double> b,startvector,resultvector, controlvector;
testSLE.setmass(0);
b.push_back(-2);
b.push_back(1);
b.push_back(-2);
b.push_back(1);
b.push_back(4);
b.push_back(1);
b.push_back(-2);
b.push_back(1);
b.push_back(-2);
testSLE.setb(b);
controlvector.push_back(1);
controlvector.push_back(2);
controlvector.push_back(1);
controlvector.push_back(2);
controlvector.push_back(3);
controlvector.push_back(2);
controlvector.push_back(1);
controlvector.push_back(2);
controlvector.push_back(1);
startvector.assign(9,1);
int exitcode=testSLE.solveLSE("Laplace",startvector, resultvector);
BOOST_REQUIRE(exitcode==0);
double c=resultvector.at(0)-controlvector.at(0); // the field is only calculated upto a constant
for (int i=0;i<9;++i){
BOOST_CHECK_CLOSE(resultvector.at(i),controlvector.at(i)+c,0.000001); //tolerance 10^-8
}
}
///this unittest tests if solve correctly returns the start vector if it already solves the problem.
BOOST_FIXTURE_TEST_CASE(solveSLE_LaplaceOp_periodic_3, scalarfield){
vector <double> b,startvector,resultvector;
testSLE.setmass(0);
b.push_back(-2);
b.push_back(1);
b.push_back(-2);
b.push_back(1);
b.push_back(4);
b.push_back(1);
b.push_back(-2);
b.push_back(1);
b.push_back(-2);
testSLE.setb(b);
startvector.push_back(1);
startvector.push_back(2);
startvector.push_back(1);
startvector.push_back(2);
startvector.push_back(3);
startvector.push_back(2);
startvector.push_back(1);
startvector.push_back(2);
startvector.push_back(1);
int exitcode=testSLE.solveLSE("Laplace",startvector, resultvector);
BOOST_CHECK_EQUAL(exitcode,81);
BOOST_CHECK_EQUAL(resultvector.at(0),1);
BOOST_CHECK_EQUAL(resultvector.at(1),2);
BOOST_CHECK_EQUAL(resultvector.at(2),1);
BOOST_CHECK_EQUAL(resultvector.at(3),2);
BOOST_CHECK_EQUAL(resultvector.at(4),3);
BOOST_CHECK_EQUAL(resultvector.at(5),2);
BOOST_CHECK_EQUAL(resultvector.at(6),1);
BOOST_CHECK_EQUAL(resultvector.at(7),2);
BOOST_CHECK_EQUAL(resultvector.at(8),1);
}
/**
* @brief test that a two consecutive random numbers are not the same
*
* @details This unittest tests the function LinSysEqu::getRandomUni
*/
BOOST_FIXTURE_TEST_CASE(getRandomUni, F){
testSLE.startRandomGenerator(10);
for (int i=0; i<100000;++i){
BOOST_CHECK(testSLE.getRandomUni()!=testSLE.getRandomUni());
}
}
/**
* @brief test that a the created matrix has the dimensions it is supposed to have.
*
* @details This unittest tests the function LinSysEqu::createRandomSparseSymmetricMatrix
*/
BOOST_FIXTURE_TEST_CASE(createRandomSparseSymmetricMatrix_dim, F){
vector< vector<double> > matrix;
int dim = 1000;
testSLE.createRandomSparseSymmetricMatrix(dim, matrix);
BOOST_CHECK_EQUAL(matrix.size(),dim);
for (int i=0;i<dim;++i){
BOOST_CHECK_EQUAL(matrix.at(i).size(),dim);
}
}
/**
* @brief test that a the created matrix has at most 2 non-zero entries per row
*
* @details This unittest tests the function LinSysEqu::createRandomSparseSymmetricMatrix
*/
BOOST_FIXTURE_TEST_CASE(createRandomSparseSymmetricMatrix_numNonZero, F){
vector< vector<double> > matrix;
int dim = 1000;
testSLE.createRandomSparseSymmetricMatrix(dim, matrix);
int nonZeroTotal=0;
for (int i=0;i<dim;++i){
int nonZero=0;
for (int j=0;j<dim;++j){
if (matrix.at(i).at(j)!=0){
++nonZero;
}
}
BOOST_CHECK(nonZero<3);
nonZeroTotal+=nonZero;
}
BOOST_LOG_TRIVIAL(info) << "The dim of testmatrix: " << dim << " nonZeroTotal: " << nonZeroTotal;
}
BOOST_FIXTURE_TEST_CASE(createRandomVector, F){
vector<double> a,b;
int dim = 1000;
testSLE.createRandomVector(dim, a);
testSLE.createRandomVector(dim, b);
for (int i=0;i<dim;++i){
BOOST_CHECK(a.at(i)!=b.at(i));
}
}
/**
*
*
* This unittest tests the function LinSysEqu::eigenvLanczos
*/
BOOST_FIXTURE_TEST_CASE( eigenvLanczos, F ){
vector< vector<double> > matrix;
vector<double> line;
const int dim=5;
for (int i=0;i<dim;++i){
line.assign(dim,0);
line.at(i)=i+1;
matrix.push_back(line);
}
testSLE.setMatrix(matrix);
vector<double> startvec,eigenv;
startvec.assign(dim,1);
int exitcode = testSLE.eigenvLanczos("sparseMatrix",startvec,eigenv);
cout << "eigenvLanczos: Exitcode: " << exitcode << endl;
BOOST_REQUIRE(exitcode==0);
sort(eigenv.begin(),eigenv.end());
for (unsigned int i=0;i<eigenv.size();++i){
BOOST_CHECK_CLOSE( eigenv.at(i) , i+1 ,0.000001); //tolerance 10^-8
}
}
BOOST_AUTO_TEST_SUITE_END( )
| true |
510cfa637a77ed72d40c7392362b820467b6803d | C++ | onexmaster/cp | /quicksort.cpp | UTF-8 | 535 | 3.203125 | 3 | [
"Apache-2.0",
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | #include<bits/stdc++.h>
using namespace std;
int partition(int *A, int start, int end)
{
int pivot=A[end];
int p_index=start;
for(int i=start;i<=end-1;i++)
{
if(A[i]<=pivot)
{
swap(A[i],A[p_index]);
p_index++;
}
}
swap(A[p_index],A[end]);
return(p_index);
}
void quick(int *A, int start, int end)
{
if(start<end)
{
int p_index=partition(A, start,end);
quick(A,start,p_index-1);
quick(A,p_index+1,end);
}
}
int main()
{
int A[]={3,2,3,1,2,4,5,5,6};
quick(A,0,8);
for(int i=0;i<9;i++)
cout<<A[i]<<" ";
}
| true |
05419e02d7d1685ef25ddc2ab32328cf206e8b76 | C++ | vslavik/poedit | /deps/boost/libs/fusion/test/sequence/io.cpp | UTF-8 | 3,668 | 2.828125 | 3 | [
"GPL-1.0-or-later",
"MIT",
"BSL-1.0"
] | permissive | /*=============================================================================
Copyright (C) 1999-2003 Jaakko Jarvi
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
==============================================================================*/
#include <boost/detail/lightweight_test.hpp>
#include <boost/fusion/container/vector/vector.hpp>
#include <boost/fusion/container/generation/make_vector.hpp>
#include <boost/fusion/sequence/comparison/equal_to.hpp>
#include <boost/fusion/sequence/io/out.hpp>
#include <boost/fusion/sequence/io/in.hpp>
#include <fstream>
#include <iterator>
#include <algorithm>
#include <string>
#if defined BOOST_NO_STRINGSTREAM
# include <strstream>
#else
# include <sstream>
#endif
using boost::fusion::vector;
using boost::fusion::make_vector;
using boost::fusion::tuple_close;
using boost::fusion::tuple_open;
using boost::fusion::tuple_delimiter;
#if defined BOOST_NO_STRINGSTREAM
using std::ostrstream;
using std::istrstream;
typedef ostrstream useThisOStringStream;
typedef istrstream useThisIStringStream;
#else
using std::ostringstream;
using std::istringstream;
typedef ostringstream useThisOStringStream;
typedef istringstream useThisIStringStream;
#endif
using std::endl;
using std::ofstream;
using std::ifstream;
using std::string;
int
main()
{
using boost::fusion::tuple_close;
using boost::fusion::tuple_open;
using boost::fusion::tuple_delimiter;
useThisOStringStream os1;
// Set format [a, b, c] for os1
os1 << tuple_open('[');
os1 << tuple_close(']');
os1 << tuple_delimiter(',');
os1 << make_vector(1, 2, 3);
BOOST_TEST (os1.str() == std::string("[1,2,3]") );
{
useThisOStringStream os2;
// Set format (a:b:c) for os2;
os2 << tuple_open('(');
os2 << tuple_close(')');
os2 << tuple_delimiter(':');
os2 << make_vector("TUPU", "HUPU", "LUPU", 4.5);
BOOST_TEST (os2.str() == std::string("(TUPU:HUPU:LUPU:4.5)") );
}
{
useThisOStringStream os2;
// Set format (a:b:c) for os2;
os2 << tuple_open('(');
os2 << tuple_close(')');
os2 << tuple_delimiter(':');
// overwrite previous setting
os2 << tuple_open("< ");
os2 << tuple_close('>');
os2 << tuple_delimiter(", ");
os2 << make_vector("TUPU", "HUPU", "LUPU", 4.5);
BOOST_TEST (os2.str() == std::string("< TUPU, HUPU, LUPU, 4.5>") );
}
// The format is still [a, b, c] for os1
os1 << make_vector(1, 2, 3);
BOOST_TEST (os1.str() == std::string("[1,2,3][1,2,3]") );
std::ofstream tmp("temp.tmp");
tmp << make_vector("One", "Two", 3);
tmp << tuple_delimiter(':');
tmp << make_vector(1000, 2000, 3000) << endl;
tmp.close();
// When reading tuples from a stream, manipulators must be set correctly:
ifstream tmp3("temp.tmp");
vector<string, string, int> j;
tmp3 >> j;
BOOST_TEST (tmp3.good() );
tmp3 >> tuple_delimiter(':');
vector<int, int, int> i;
tmp3 >> i;
BOOST_TEST (tmp3.good() );
tmp3.close();
// reading vector<int, int, int> in format (a b c);
useThisIStringStream is("(100 200 300)");
vector<int, int, int> ti;
BOOST_TEST(!!(is >> ti));
BOOST_TEST(ti == make_vector(100, 200, 300));
// Note that strings are problematic:
// writing a tuple on a stream and reading it back doesn't work in
// general. If this is wanted, some kind of a parseable string class
// should be used.
return boost::report_errors();
}
| true |
9e36fdbab31c57f01212d812a1e17f94601f3e69 | C++ | HoShiMin/HookLib | /HookLibTests/HookLibTests.cpp | UTF-8 | 10,404 | 2.53125 | 3 | [
"MIT"
] | permissive | #include <Windows.h>
#include <HookLib.h>
#include <cstdio>
#include <string>
constexpr bool k_testKernelMode = true;
namespace
{
template <unsigned int num>
__declspec(noinline) int func(int arg1, float arg2)
{
printf("Orig: %u %i %f\n", num, arg1, arg2);
return 0x1ee7c0de;
}
template <unsigned int num>
__declspec(noinline) int handler(int arg1, float arg2)
{
printf("Hook: %u %i %f\n", num, arg1, arg2);
return 1337;
}
template <typename Func>
Func hookFunc(Func fn, Func handler)
{
return static_cast<Func>(hook(fn, handler));
}
#define begin_test printf("%s:\n", __FUNCTION__)
#define end_test printf("\n")
#define hk_assert(cond) if (!(cond)) { printf("[X] %s\n", #cond); __int2c(); } __assume((cond))
#define log(fmt, ...) printf("[" __FILE__ ":%u]: " fmt "\n", __LINE__, __VA_ARGS__)
void testHookOnce()
{
begin_test;
func<0>(0, 0.123f);
const auto orig0 = hookFunc(func<0>, handler<0>);
hk_assert(orig0 != nullptr);
func<0>(0, 0.0f);
orig0(0, 0.0f);
unhook(orig0);
func<0>(0, 0.0f);
end_test;
}
void testSerialHooks()
{
begin_test;
const auto orig1 = hookFunc(func<1>, handler<1>);
const auto orig2 = hookFunc(func<2>, handler<2>);
func<1>(1, 0.1f);
orig1(1, 0.1f);
func<2>(2, 0.2f);
orig2(2, 0.2f);
unhook(orig2);
func<2>(2, 0.2f);
unhook(orig1);
func<1>(1, 0.1f);
end_test;
}
void testSerialHooksMultiunhook()
{
begin_test;
const auto orig1 = hookFunc(func<1>, handler<1>);
const auto orig2 = hookFunc(func<2>, handler<2>);
func<1>(1, 0.1f);
orig1(1, 0.1f);
func<2>(2, 0.2f);
orig2(2, 0.2f);
Unhook fns[2]{ orig1, orig2 };
multiunhook(fns, 2);
func<1>(1, 0.1f);
func<2>(2, 0.2f);
end_test;
}
void testMultihook()
{
begin_test;
Hook hooks[2]
{
{
.fn = func<1>,
.handler = handler<1>
},
{
.fn = func<2>,
.handler = handler<2>
}
};
const auto hooked = multihook(hooks, 2);
hk_assert(hooked == 2);
using Fn1 = decltype(func<1>)*;
using Fn2 = decltype(func<2>)*;
hk_assert(hooks[0].original != nullptr);
hk_assert(hooks[1].original != nullptr);
func<1>(1, 0.1f);
static_cast<Fn1>(hooks[0].original)(1, 0.1f);
func<2>(2, 0.2f);
static_cast<Fn2>(hooks[1].original)(2, 0.2f);
Unhook fns[2]{ hooks[0].original, hooks[1].original };
multiunhook(fns, 2);
func<1>(1, 0.1f);
func<2>(2, 0.2f);
end_test;
}
void testContextsFixup()
{
begin_test;
const HANDLE hThread = CreateThread(nullptr, 0, [](void* arg) -> unsigned long
{
return 0;
}, nullptr, CREATE_SUSPENDED, nullptr);
hk_assert(hThread != nullptr);
CONTEXT ctx{};
ctx.ContextFlags = CONTEXT_CONTROL;
const bool getStatus = !!GetThreadContext(hThread, &ctx);
hk_assert(getStatus);
#ifdef _AMD64_
const size_t origIp = ctx.Rip;
ctx.Rip = reinterpret_cast<size_t>(func<0>);
#else
const size_t origIp = ctx.Eip;
ctx.Eip = reinterpret_cast<size_t>(func<0>);
#endif
const bool setStatus = !!SetThreadContext(hThread, &ctx);
hk_assert(setStatus);
SwitchToThread();
const auto orig = hookFunc(func<0>, handler<0>);
const bool secondGetStatus = !!GetThreadContext(hThread, &ctx);
hk_assert(secondGetStatus);
#ifdef _AMD64_
hk_assert(ctx.Rip == reinterpret_cast<size_t>(orig));
#else
hk_assert(ctx.Eip == reinterpret_cast<size_t>(orig));
#endif
unhook(orig);
const bool thirdGetStatus = !!GetThreadContext(hThread, &ctx);
hk_assert(thirdGetStatus);
#ifdef _AMD64_
hk_assert(ctx.Rip == reinterpret_cast<size_t>(func<0>));
ctx.Rip = origIp;
#else
hk_assert(ctx.Eip == reinterpret_cast<size_t>(func<0>));
ctx.Eip = origIp;
#endif
const bool restoreOrigIpStatus = !!SetThreadContext(hThread, &ctx);
hk_assert(restoreOrigIpStatus);
SwitchToThread();
ResumeThread(hThread);
WaitForSingleObject(hThread, INFINITE);
CloseHandle(hThread);
end_test;
}
void driverTestKernelHooks(HANDLE hDev)
{
begin_test;
unsigned long returned = 0;
const bool testStatus = !!DeviceIoControl(hDev, CTL_CODE(0x8000, 0x800, METHOD_NEITHER, FILE_ANY_ACCESS), nullptr, 0, nullptr, 0, &returned, nullptr);
hk_assert(testStatus);
end_test;
}
void driverTestUserHooks(HANDLE hDev)
{
begin_test;
const HANDLE hThread = CreateThread(nullptr, 0, [](void* arg) -> unsigned long
{
return 0;
}, nullptr, CREATE_SUSPENDED, nullptr);
hk_assert(hThread != nullptr);
CONTEXT ctx{};
ctx.ContextFlags = CONTEXT_CONTROL;
const bool getStatus = !!GetThreadContext(hThread, &ctx);
hk_assert(getStatus);
#ifdef _AMD64_
const size_t origIp = ctx.Rip;
ctx.Rip = reinterpret_cast<size_t>(func<0>);
#else
const size_t origIp = ctx.Eip;
ctx.Eip = reinterpret_cast<size_t>(func<0>);
#endif
const bool setStatus = !!SetThreadContext(hThread, &ctx);
hk_assert(setStatus);
SwitchToThread();
struct HookRequest
{
struct Input
{
unsigned long long fn;
unsigned long long handler;
};
struct Output
{
unsigned long long original;
};
};
const HookRequest::Input hookIn{ .fn = reinterpret_cast<unsigned long long>(func<0>), .handler = reinterpret_cast<unsigned long long>(handler<0>) };
HookRequest::Output hookOut{};
unsigned long returned = 0;
const bool hookStatus = !!DeviceIoControl(hDev, CTL_CODE(0x8000, 0x801, METHOD_NEITHER, FILE_ANY_ACCESS), const_cast<HookRequest::Input*>(&hookIn), sizeof(hookIn), &hookOut, sizeof(hookOut), &returned, nullptr);
hk_assert(hookStatus);
const auto orig = reinterpret_cast<decltype(func<0>)*>(hookOut.original);
const bool secondGetStatus = !!GetThreadContext(hThread, &ctx);
hk_assert(secondGetStatus);
#ifdef _AMD64_
hk_assert(ctx.Rip == reinterpret_cast<size_t>(orig));
#else
hk_assert(ctx.Eip == reinterpret_cast<size_t>(orig));
#endif
struct UnhookRequest
{
struct Input
{
unsigned long long original;
};
struct Output
{
bool status;
};
};
const UnhookRequest::Input unhookIn{ .original = hookOut.original };
UnhookRequest::Output unhookOut{};
const bool unhookStatus = !!DeviceIoControl(hDev, CTL_CODE(0x8000, 0x802, METHOD_NEITHER, FILE_ANY_ACCESS), const_cast<UnhookRequest::Input*>(&unhookIn), sizeof(unhookIn), &unhookOut, sizeof(unhookOut), &returned, nullptr);
hk_assert(unhookStatus);
hk_assert(unhookOut.status);
const bool thirdGetStatus = !!GetThreadContext(hThread, &ctx);
hk_assert(thirdGetStatus);
#ifdef _AMD64_
hk_assert(ctx.Rip == reinterpret_cast<size_t>(func<0>));
ctx.Rip = origIp;
#else
hk_assert(ctx.Eip == reinterpret_cast<size_t>(func<0>));
ctx.Eip = origIp;
#endif
const bool restoreOrigIpStatus = !!SetThreadContext(hThread, &ctx);
hk_assert(restoreOrigIpStatus);
SwitchToThread();
ResumeThread(hThread);
WaitForSingleObject(hThread, INFINITE);
CloseHandle(hThread);
end_test;
}
void testCppHelpers()
{
begin_test;
auto holder = HookFactory::install(func<0>, handler<0>);
func<0>(111, 0.222f);
holder.call(111, 0.222f);
holder.disable();
func<0>(111, 0.222f);
end_test;
}
void runDriverTests()
{
const auto getExeFolder = []() -> std::wstring
{
std::wstring path(MAX_PATH, L'\0');
const auto len = GetModuleFileNameW(nullptr, path.data(), static_cast<unsigned int>(path.size()));
if (!len)
{
return {};
}
const auto lastDelim = path.rfind(L'\\');
if (lastDelim == std::wstring::npos)
{
return {};
}
path.resize(lastDelim);
return path;
};
const auto exeFolder = getExeFolder();
if (exeFolder.empty())
{
log("Unable to retrieve the current exe folder");
return;
}
const auto driverPath = exeFolder + L"\\HookLibDrvTests.sys";
const SC_HANDLE hScm = OpenSCManagerW(nullptr, nullptr, SC_MANAGER_ALL_ACCESS);
if (!hScm)
{
const auto lastError = GetLastError();
log("Unable to open the SC manager: 0x%X", lastError);
return;
}
const SC_HANDLE hSvc = CreateServiceW(hScm, L"HookLibTestDrv", L"HookLibTestDrv", SERVICE_ALL_ACCESS, SERVICE_KERNEL_DRIVER, SERVICE_DEMAND_START, SERVICE_ERROR_NORMAL, driverPath.c_str(), nullptr, nullptr, nullptr, nullptr, nullptr);
if (!hSvc)
{
const auto lastError = GetLastError();
log("Unable to create the service: 0x%X", lastError);
CloseServiceHandle(hScm);
return;
}
const bool startStatus = !!StartServiceW(hSvc, 0, nullptr);
if (!startStatus)
{
const auto lastError = GetLastError();
log("Unable to start the service: 0x%X", lastError);
DeleteService(hSvc);
CloseServiceHandle(hSvc);
CloseServiceHandle(hScm);
return;
}
const HANDLE hDev = CreateFileW(L"\\\\.\\HookLibTestDrv", FILE_ALL_ACCESS, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
if (hDev == INVALID_HANDLE_VALUE)
{
const auto lastError = GetLastError();
log("Unable to open the HookLibDrv device: 0x%X", lastError);
SERVICE_STATUS svcStatus{};
ControlService(hSvc, SERVICE_CONTROL_STOP, &svcStatus);
DeleteService(hSvc);
CloseServiceHandle(hSvc);
CloseServiceHandle(hScm);
return;
}
driverTestKernelHooks(hDev);
driverTestUserHooks(hDev);
CloseHandle(hDev);
SERVICE_STATUS svcStatus{};
ControlService(hSvc, SERVICE_CONTROL_STOP, &svcStatus);
DeleteService(hSvc);
CloseServiceHandle(hSvc);
CloseServiceHandle(hScm);
}
void runTests()
{
testHookOnce();
testSerialHooks();
testSerialHooksMultiunhook();
testMultihook();
testContextsFixup();
testCppHelpers();
if constexpr (k_testKernelMode)
{
runDriverTests();
}
}
} // namespace
auto g_holder = HookFactory::install(func<0>, handler<0>);
int main()
{
runTests();
log("Tests are finished");
return 0;
} | true |
2c7f229aea28033f912d4bd69966be848f488586 | C++ | borland/SerialQueueCPP | /SerialQueueCPP/SerialQueue.cpp | UTF-8 | 10,322 | 2.765625 | 3 | [] | no_license | //
// SerialQueue.cpp
// SerialQueueCPP
//
// Created by Orion Edwards on 1/11/15.
// Copyright © 2015 Orion Edwards. All rights reserved.
//
#include "SerialQueue.hpp"
#include <condition_variable>
#include <cassert>
using namespace std;
// C++ has no finally.
template<typename T>
class scope_exit final
{
T m_action;
public:
explicit scope_exit(T&& exitScope) : m_action(std::forward<T>(exitScope))
{}
~scope_exit()
{ m_action(); }
};
template <typename T>
scope_exit<T> create_scope_exit(T&& exitScope)
{ return scope_exit<T>(std::forward<T>(exitScope)); }
// ----- TaggedAction class -----
atomic<unsigned int> SerialQueueImpl::TaggedAction::s_lastActionTag;
SerialQueueImpl::TaggedAction::TaggedAction(Action act) : tag(++s_lastActionTag), action(std::move(act)) { }
bool SerialQueueImpl::TaggedAction::operator==(const TaggedAction& other) const noexcept {
return tag == other.tag;
}
bool SerialQueueImpl::TaggedAction::operator!=(const TaggedAction& other) const noexcept {
return !(*this == other);
}
void SerialQueueImpl::TaggedAction::operator()(){
action();
}
// ----- SerialQueue wrapper class -----
SerialQueue::SerialQueue(shared_ptr<IThreadPool> threadpool)
: m_sptr(make_shared<SerialQueueImpl>(threadpool))
{ }
void SerialQueue::DispatchSync(std::function<void ()> action) {
assert(m_sptr);
m_sptr->DispatchSync(move(action));
}
IDisposable SerialQueue::DispatchAsync(std::function<void ()> action ) {
assert(m_sptr);
return DispatchAsync(move(action));
}
void SerialQueue::VerifyQueue() {
assert(m_sptr);
m_sptr->VerifyQueue();
}
// ----- SerialQueueImpl class -----
thread_local_value<std::deque<SerialQueueImpl*>> SerialQueueImpl::s_queueStack;
SerialQueueImpl::SerialQueueImpl(shared_ptr<IThreadPool> threadpool)
: m_threadPool(threadpool)
{
if (threadpool == nullptr)
throw invalid_argument("threadpool");
}
SerialQueueImpl::SerialQueueImpl() : SerialQueueImpl(PlatformThreadPool::Default()) {
}
void SerialQueueImpl::VerifyQueue()
{
if (s_queueStack.get() == nullptr || find(s_queueStack->begin(), s_queueStack->end(), this) == s_queueStack->end())
throw logic_error("On the wrong queue");
}
IDisposable SerialQueueImpl::DispatchAsync(Action action)
{
{
lock_guard<mutex> guard(m_schedulerLock);
if (m_isDisposed)
throw logic_error("Cannot call DispatchSync on a disposed queue");
m_asyncActions.push_back(move(action));
if (m_asyncState == AsyncState::Idle)
{
// even though we don't hold m_schedulerLock when asyncActionsAreProcessing is set to false
// that should be OK as the only "contention" happens up here while we do hold it
m_asyncState = AsyncState::Scheduled;
m_threadPool->QueueWorkItem(bind(&SerialQueueImpl::ProcessAsync, this));
}
} // unlock
return AnonymousDisposable::CreateShared([&]{
// we can't "take it out" of the threadpool as not all threadpools support that
lock_guard<mutex> guard(m_schedulerLock);
auto iter = find(m_asyncActions.begin(), m_asyncActions.end(), action);
if(iter != m_asyncActions.end())
m_asyncActions.erase(iter);
});
}
void SerialQueueImpl::ProcessAsync()
{
bool schedulerLockTaken = false;
s_queueStack->push_back(this);
auto finally = create_scope_exit([&]{
m_asyncState = AsyncState::Idle;
if (schedulerLockTaken)
m_schedulerLock.unlock();
s_queueStack->pop_back(); // technically we leak the queue stack threadlocal, but it's probably OK. Windows will free it when the thread exits
});
m_schedulerLock.lock();
schedulerLockTaken = true;
m_asyncState = AsyncState::Processing;
if (m_isDisposed)
return; // the actions will have been dumped, there's no point doing anything
while (m_asyncActions.size() > 0)
{
// get the head of the queue, then release the lock
auto action = m_asyncActions[0];
m_asyncActions.erase(m_asyncActions.begin());
m_schedulerLock.unlock();
schedulerLockTaken = false;
// process the action
try
{
m_executionLock.lock(); // we must lock here or a DispatchSync could run concurrently with the last thing in the queue
action();
}
catch (const exception& exception) // we only catch std::exception here. If the caller throws something else, too bad
{
// TODO call unhandled exception filter
// var handler = UnhandledException;
// if (handler != null)
// handler(this, new UnhandledExceptionEventArgs(exception));
}
// now re-acquire the lock for the next thing
assert(!schedulerLockTaken);
m_schedulerLock.lock();
schedulerLockTaken = true;
}
}
void SerialQueueImpl::DispatchSync(Action action)
{
// copy the stack; might be a more optimal way of doing this, it seems to be fast enough
vector<SerialQueueImpl*> prevStack(s_queueStack->begin(), s_queueStack->end());
s_queueStack->push_back(this);
bool schedulerLockTaken = false;
auto finally = create_scope_exit([&]{
if (schedulerLockTaken)
m_schedulerLock.unlock();
s_queueStack->pop_back(); // technically we leak the queue stack threadlocal, but it's probably OK. Windows will free it when the thread exits
});
m_schedulerLock.lock();
schedulerLockTaken = true;
if (m_isDisposed)
throw logic_error("Cannot call DispatchSync on a disposed queue");
if(m_asyncState == AsyncState::Idle || find(prevStack.begin(), prevStack.end(), this) != prevStack.end()) // either queue is empty or it's a nested call
{
m_schedulerLock.unlock();
schedulerLockTaken = false;
// process the action
m_executionLock.lock();
action(); // DO NOT CATCH EXCEPTIONS. We're excuting synchronously so just let it throw
return;
}
// if there is any async stuff scheduled we must also schedule
// else m_asyncState == AsyncState.Scheduled, OR we fell through from Processing
condition_variable asyncReady;
condition_variable syncDone;
mutex syncMutex;
DispatchAsync([&]{
asyncReady.notify_one();
unique_lock<mutex> lock(syncMutex);
syncDone.wait(lock);
});
m_schedulerLock.unlock();
schedulerLockTaken = false;
auto finally2 = create_scope_exit([&]{
unique_lock<mutex> lock(syncMutex);
syncDone.notify_one(); // tell the dispatchAsync it can release the lock
});
unique_lock<mutex> lock(syncMutex);
syncDone.wait(lock);
action(); // DO NOT CATCH EXCEPTIONS. We're excuting synchronously so just let it throw
}
/// <summary>Internal implementation of Dispose</summary>
/// <remarks>We don't have a finalizer (and nor should we) but this method is just following the MS-recommended dispose pattern just in case someone wants to add one in a derived class</remarks>
/// <param name="disposing">true if called via Dispose(), false if called via a Finalizer.</param>
void SerialQueueImpl::Dispose()
{
// vector<IDisposable> timers;
// {
lock_guard<mutex> lock(m_schedulerLock);
if (m_isDisposed)
return; // double-dispose
m_isDisposed = true;
m_asyncActions.clear();
// timers = m_timers;
// m_timers.clear();
// }
// for(auto& t : timers) {
// t.Dispose();
// }
}
/// <summary>Schedules the given action to run asynchronously on the queue after dueTime.</summary>
/// <remarks>The function is not guaranteed to run at dueTime as the queue may be busy, it will run when next able.</remarks>
/// <param name="dueTime">Delay before running the action</param>
/// <param name="action">The function to run</param>
/// <returns>A disposable token which you can use to cancel the async action if it has not run yet.
/// It is always safe to dispose this token, even if the async action has already run</returns>
// virtual IDisposable DispatchAfter(TimeSpan dueTime, Action action)
// {
// IDisposable cancel = null;
// IDisposable timer = null;
//
// lock (m_schedulerLock)
// {
// if (m_isDisposed)
// throw new ObjectDisposedException("SerialQueue", "Cannot call DispatchAfter on a disposed queue");
//
// timer = m_threadPool.Schedule(dueTime, () => {
// lock(m_schedulerLock)
// {
// m_timers.Remove(timer);
// if (cancel == null || m_isDisposed) // we've been canceled OR the queue has been disposed
// return;
//
// // we must call DispatchAsync while still holding m_schedulerLock to prevent a window where we get disposed at this point
// cancel = DispatchAsync(action);
// }
// });
// m_timers.Add(timer);
// }
//
// cancel = new AnonymousDisposable(() => {
// lock (m_schedulerLock)
// m_timers.Remove(timer);
//
// timer.Dispose();
// });
//
// return new AnonymousDisposable(() => {
// lock (m_schedulerLock) {
// if (cancel != null) {
// cancel.Dispose(); // this will either cancel the timer or cancel the DispatchAsync depending on which stage it's in
// cancel = null;
// }
// }
// });
// }
// ----- SharedDisposable -----
SharedDisposable::SharedDisposable(std::shared_ptr<IDisposable> impl)
: m_impl(move(impl)) { }
void SharedDisposable::Dispose() {
assert(m_impl != nullptr);
m_impl->Dispose();
}
AnonymousDisposable::AnonymousDisposable(std::function<void()> action)
: m_action(move(action)) {}
SharedDisposable AnonymousDisposable::CreateShared(std::function<void()> action) {
shared_ptr<IDisposable> sptr(new AnonymousDisposable(action));
return sptr;
}
void AnonymousDisposable::Dispose() {
}
| true |
5f9271b03a1077fc6f06434bf616e14d6f6eaf64 | C++ | jp112sdl/FFSDL-WK-ZN-ESP32 | /WiFiSetup.h | UTF-8 | 1,763 | 2.671875 | 3 | [] | no_license | //
// 2018-11-22 jp112sdl Creative Commons - http://creativecommons.org/licenses/by-nc-sa/3.0/de/
//
#ifndef __WIFISETUP__H_
#define __WIFISETUP__H_
boolean arrayIncludeElement(uint8_t array[], uint8_t element, uint8_t sz);
boolean arrayIncludeElement(uint8_t array[], uint8_t element, uint8_t sz) {
for (int i = 0; i < sz; i++) {
if (array[i] == element) {
return true;
}
}
return false;
}
void initWiFi() {
uint8_t chs[13] = { 1, 6, 11, 2, 7, 12, 3, 8, 13, 4, 9, 5, 10 }; //list of channels
LOG("Scan for networks...");
WiFi.mode(WIFI_STA);
WiFi.disconnect();
delay(100);
uint8_t n = WiFi.scanNetworks(false, true);
int indices[n];
uint8_t occupied_chs[n];
for (int i = 0; i < n; i++) {
indices[i] = i;
}
//sort networks by channel
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
if (WiFi.channel(indices[j]) > WiFi.channel(indices[i])) {
std::swap(indices[i], indices[j]);
}
}
}
for (uint8_t num = 0; num < n; num++) {
occupied_chs[num] = WiFi.channel(num);
}
uint8_t selected_ch_idx = 0;
for (uint8_t num = 0; num < n; num++) {
uint8_t _ch = WiFi.channel(indices[num]);
if (chs[selected_ch_idx] == _ch)
if (selected_ch_idx < sizeof(chs))
selected_ch_idx++;
while (arrayIncludeElement(occupied_chs, chs[selected_ch_idx], n) == true) {
if (selected_ch_idx < sizeof(chs)) {
selected_ch_idx++;
} else {
break;
}
}
LOG("Found " + WiFi.SSID(indices[num]) + " (" + String(_ch) + ")");
}
LOG("Scan for networks... done");
LOG("Using network channel: " + String(chs[selected_ch_idx]));
WiFi.mode(WIFI_AP);
WiFi.softAP(ssid, password, chs[selected_ch_idx], 0, 4);
}
#endif
| true |
d8660f5c5e4489b0f5541cec3c8f29f6c8128a4c | C++ | marant/magicforest | /magicforest/IEvent.cpp | UTF-8 | 2,058 | 3.3125 | 3 | [] | no_license | #include "IEvent.h"
#include "IGameObject.h"
// Constructor, nothing interesting here
IEvent::IEvent( )
{
this->Description = "Not set";
this->Listener = NULL;
}
// Destructor frees the ObjectList and that's pretty much it
IEvent::~IEvent()
{
int i=0;
for (i = 0; i < ObjectList.size(); i++)
{
delete ObjectList[i];
ObjectList[i] = NULL;
}
ObjectList.clear();
}
/* NOTE! The return value is a pointer! */
std::string* IEvent::SetDescription( std::string newDescription )
{
this->Description = newDescription;
return &Description;
}
bool IEvent::SetListener(IEventNotifier* newListener)
{
if( !newListener )
{
return false;
}
this->Listener = newListener;
return true;
}
IGameObject* IEvent::AddObject( IGameObject* pNewObject )
{
if (pNewObject)
{
ObjectList.push_back( pNewObject );
return pNewObject;
}
return NULL;
}
/*
* Removes object that is specified in the parameter from the object list, if
* it is found. Returns a pointer to the removed object and is meant to be
* used when the player acquires something from an event (finds something for
* example).
*
*
*/
IGameObject* IEvent::RemoveObject( int index )
{
/* doesn't std::vector provide a cleaner way of doing this? All I found was
* a pop_back() function which really isn't what I'm looking for...
*/
IGameObject* tmp = NULL;
tmp = ObjectList.at( index );
if (tmp)
{
ObjectList.erase( ObjectList.begin()+index );
return tmp;
}
return NULL;
}
IGameObject* IEvent::RemoveObject( IGameObject* pRemoveThisObject )
{
/*
* iterates through the vector and compares the given pointer to all elements
* in the vector. Kinda ugly I know.
*/
//TODO: find a cleaner way to do this!
if( !pRemoveThisObject )
{
return NULL;
}
int i=0;
for (i = 0; i < ObjectList.size(); i++)
{
if (ObjectList[i] == pRemoveThisObject )
{
IGameObject* tmp = this->RemoveObject(i);
if (tmp)
{
return tmp;
}
}
}
return NULL;
}
| true |
88a80e95a88811e0c214f2d5e6d843d77708895d | C++ | k2font/atcoder | /abc080_C.cpp | UTF-8 | 1,485 | 2.671875 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
#define REP(i,n) for(int i=0, i##_len=(n); i<i##_len; ++i)
#define all(x) (x).begin(),(x).end()
using ll = long long;
string char_to_string(char val) {
return string(1, val);
}
int char_to_int(char val) {
return val - '0';
}
template<class T> inline bool chmin(T& a, T b) {
if (a > b) {
a = b;
return true;
}
return false;
}
template<class T> inline bool chmax(T& a, T b) {
if (a < b) {
a = b;
return true;
}
return false;
}
int vector_finder(std::vector<ll> vec, int number) {
auto itr = std::find(vec.begin(), vec.end(), number);
size_t index = std::distance( vec.begin(), itr );
if (index != vec.size()) { // 発見できたとき
return 1;
}
else { // 発見できなかったとき
return 0;
}
}
struct edge {
ll to, cost;
};
int main() {
int N; cin >> N;
vector<int> B(N);
vector<vector<int>> P(N, vector<int>(11));
REP(i, N) {
unsigned int b = 0;
REP(k, 10) {
int p; cin >> p;
if(p == 1) b |= (1 << k); // 1つ1つがORを表す
}
B[i] = b;
}
REP(i, N) {
REP(k, 11) {
cin >> P[i][k];
}
}
ll ans = -pow(10,17);
for(int bit = 0; bit < (1 << 10); ++bit) {
if(bit == 0) continue;
unsigned int c;
ll res = 0;
for(int i = 0; i < N; ++i) {
int cnt = 0;
c = (bit & B[i]);
cnt = __builtin_popcount( c );
res += P[i][cnt];
}
if(ans < res) ans = res;
}
cout << ans << endl;
} | true |
a6dd67d86ccb7ca4eb2e55530a53a5b653eb5120 | C++ | adayrabe/piscine-cpp | /day01/ex02/src/main.cpp | UTF-8 | 464 | 2.796875 | 3 | [] | no_license | #include "ZombieEvent.hpp"
int main()
{
ZombieEvent zombieEvent = ZombieEvent();
ZombieEvent tempZombieEvent = ZombieEvent();
zombieEvent.setZombieType("Necro");
tempZombieEvent.setZombieType("Runner");
Zombie *zombie1 = zombieEvent.newZombie("Alex");
Zombie *zombie2 = zombieEvent.newZombie("Danny");
zombieEvent.randomChump();
tempZombieEvent.randomChump();
zombie1->announce();
zombie2->announce();
delete zombie1;
delete zombie2;
return (0);
} | true |
9922295e0db23de4a487394f7d134118faea2457 | C++ | jsethi7133/OOPs | /compex_n.cpp | UTF-8 | 611 | 3.1875 | 3 | [] | no_license | //use of constructors
#include<iostream.h>
class complex{
int r,c;
public:
complex();
complex(int i)
{
r=i;
c=i;
}
complex(int i,int j)
{
r=i;
c=j;
}
void add(complex c1,complex c2)
{
cout<<c1.r+c2.r<<"+"<<c1.c+c2.c<<"i"<<endl;
}
};
void main()
{ int r1,r2,c1,c2;
//complex c3,c4;
cin>>r1;
cin>>c1;
cin>>r2;
cin>>c2;
if(r1==c1 && r2==c2)
{
complex c3(r1);
complex c4(r2);
c3.add(c3,c4);
}
else
{
complex c3(r1,c1);
complex c4(r2,c2);
c3.add(c3,c4);
}
} | true |
068e1dc60e170e3f2467718406a5e224f9d7e8dc | C++ | guzhoudiaoke/practice | /poj/poj/ID2000-3000/2593/2593.cpp | UTF-8 | 982 | 3.328125 | 3 | [] | no_license | /*
* problem: poj 2593
* author: guzhoudiaoke
* time: 2011-10-02
*/
#include <stdio.h>
int n, a[100000], sum1[100000], sum2[100000];
void get_sum1()
{
int i, temp;
sum1[0] = temp = a[0];
for (i = 1; i < n; i++)
{
if (temp > 0) temp += a[i];
else temp = a[i];
if (temp > sum1[i-1]) sum1[i] = temp;
else sum1[i] = sum1[i-1];
}
}
void get_sum2()
{
int i, temp;
sum2[n-1] = temp = a[n-1];
for (i = n-2; i >= 0; i--)
{
if (temp > 0) temp += a[i];
else temp = a[i];
if (temp > sum2[i+1]) sum2[i] = temp;
else sum2[i] = sum2[i+1];
}
}
int get_max()
{
int max = sum1[0] + sum2[1];
for (int i = 2; i < n; i++)
if (sum1[i-1] + sum2[i] > max)
max = sum1[i-1] + sum2[i];
return max;
}
int main()
{
int i;
while (1)
{
scanf("%d", &n);
if (n == 0) break;
for (i = 0; i < n; i++)
scanf("%d", &a[i]);
get_sum1();
get_sum2();
printf("%d\n", get_max());
}
return 0;
} | true |
10a4d99a4da03d51eef990ae240b91dce6765ed2 | C++ | keenite/cs | /stl/map.cc | UTF-8 | 991 | 3.65625 | 4 | [] | no_license | #include <iostream>
#include <map>
#include <string>
#include <iterator>
int main()
{
std::map<std::string, int> words_map;
words_map.insert(std::make_pair("earth", 1));
words_map.insert(std::make_pair("moon", 2));
words_map["sun"] = 3;
words_map["earth"] = 4;
// std::map<std::string, int>::iterator it = words_map.begin();
// while(it != words_map.end()) {
// std::cout << it->first << "::" << it->second << std::endl;
// it++;
// }
for (auto& it: words_map) {
std::cout << it.first << "::" << it.second << std::endl;
}
//The insert return first is iterator, second is bool
if (words_map.insert(std::make_pair("earth", 1)).second == false) {
std::cout << "Error: key existed" << std::endl;
}
if (words_map.find("sun") != words_map.end()) {
std::cout << "word sun found" << std::endl;
}
if (words_map.find("mars") == words_map.end()) {
std::cout << "word mars not found" << std::endl;
}
return 0;
}
| true |
36a42bd592e9066eee2862952bc0b1ed92bb7d3f | C++ | arielroque/RPG-PLP | /c++/leitor_de_arquivos.h | UTF-8 | 2,531 | 3.28125 | 3 | [] | no_license | #ifndef LEITOR_DE_ARQUIVOS_CPP_INCLUDED
#define LEITOR_DE_ARQUIVOS_CPP_INCLUDED
#include<bits/stdc++.h>
#include<fstream>
#include "constantes.h"
#define SEPARADOR '#'
#define SOBRESCRITA 1
#define APPEND 2
using namespace std;
/*
//reading test, le todo o arquivo
string texto = lerTexto((string)PATHQUIZ+"teste.txt",0);
int cnt = 1;
while(texto.size()>=1 && texto[0]!='#'){
cout<<texto<<endl;
texto = lerTexto((string)PATHQUIZ+"teste.txt",cnt++);
}
*/
string lerTexto(string path,int step){
std::ifstream file(path);
string retorno = "",line;
int cntStep = 0;
if(!file) return "";
while(getline(file,line)){
if(line[0] == SEPARADOR){
cntStep++;
if(cntStep>step) break;
}else{
if(cntStep>=step){
retorno+=line+"\n";
}
}
}
file.close();
return retorno;
}
string lerArquivo(string path,int maxStep){
if(maxStep == 0) return "";
string retorno = "";
string texto = lerTexto(path,0);
int cnt = 1;
while((texto.size()>=1 && texto[0]!='#') && cnt<maxStep){
retorno+=texto;
texto = lerTexto(path,cnt++);
}
return retorno;
}
bool escreverTexto(string path,string content,int mode){
/**
A variável mode vai ser usada para saber se eh uma operacao
de sobrescrita ou anexo.
1 - Sobrescrita
2 - Append
**/
ofstream file;
if(mode == SOBRESCRITA){
file.open(path);
}else{
file.open(path,std::ios_base::app);
}
if(!file.is_open()) return false;
if(content == "") return false;
file<<content;
file<<"\n#\n";
file.close();
return true;
}
/*
//writing test
int n;
cin>>n;
cin.ignore();
for(int i = 0;i<n;++i){
string s;
getline(cin,s);
escreverTexto(PATHTW,s,APPEND);
}
*/
/*
//escrever historias
while(true){
string titulo;
cout<<"Nome do Arquivo: ";
getline(cin,titulo);
cout<<"Conteudo:"<<endl;
string content = "";
while(true){
string enunciado;
getline(cin,enunciado);
if(enunciado[0] == '#') break;
content+=enunciado+"\n";
}
content.pop_back();
escreverTexto((string)PATHHISTORIA+titulo+".txt",content,SOBRESCRITA);
}
*/
#endif // LEITOR_DE_ARQUIVOS_CPP_INCLUDED
| true |
fd811d2b6a0073a3a7dea38bf5bedaeba16fabf7 | C++ | NealChalmers/course-project | /DataStructure/R(prim).cpp | UTF-8 | 1,972 | 2.78125 | 3 | [] | no_license | #include <iostream>
#include <memory.h>
using namespace std;
typedef struct linkv
{
int n;
int edge[50];
}linkv;
typedef struct
{
linkv lv[50];
int p;
}pict;
typedef struct
{
int f,t,q;
}egs;
void createpic(pict *,int,int);
int prim(pict *pic);
int main()
{
int p,e;
while(cin>>p&&p)
{
cin>>e;
pict *pic=new pict;
pic->p=p;
createpic(pic,p,e);
cout<<prim(pic)<<endl;
delete pic;
}
return 0;
}
void createpic(pict *pic,int p,int e)
{
for(int i=0;i!=50;++i)
{
for(int j=0;j!=50;++j)
pic->lv[i].edge[j]=0;
pic->lv[i].n=0;
}
int cp1,cp2,ce;
for(int i=0;i!=e;++i)
{
cin>>cp1>>cp2>>ce;
if(pic->lv[cp1-1].edge[cp2-1]==0&&pic->lv[cp2-1].edge[cp1-1]==0)
{
pic->lv[cp1-1].edge[cp2-1]=pic->lv[cp2-1].edge[cp1-1]=ce;
++pic->lv[cp1-1].n;
++pic->lv[cp2-1].n;
}
else
{
pic->lv[cp1-1].edge[cp2-1]=pic->lv[cp1-1].edge[cp2-1]<ce?pic->lv[cp1-1].edge[cp2-1]:ce;
pic->lv[cp2-1].edge[cp1-1]=pic->lv[cp1-1].edge[cp2-1];
}
}
}
/*
5 7
1 2 5
2 3 7
2 4 8
4 5 11
3 5 10
1 5 6
4 2 12
*/
int prim(pict *pic)
{
int re=0;
bool marked[50];
int lowest[50];
memset(marked,0,50*sizeof(bool));
memset(lowest,0,50*sizeof(int));
marked[0]=1;
for(int i=0;i!=pic->p;++i)
{
int tq;
for(int j=0;j!=pic->lv[i].n;++j)
if((tq=pic->lv[i].edge[j])!=0)
{
if(marked[j])
{
if(tq<lowest[j])
lowest[j]=tq;
}
else
{
marked[j]=1;
lowest[j]=tq;
}
}
}
for(int i=0;i!=pic->p;++i)
{
if(!marked[i])
continue;
re+=lowest[i];
}
return re;
}
| true |
d8ab3377de23ba0608bacd834d457cf2332fd9b0 | C++ | simple-coding-channel/BattleCity | /src/Renderer/VertexBufferLayout.h | UTF-8 | 751 | 2.671875 | 3 | [] | no_license | #pragma once
#include <vector>
#include <glad/glad.h>
namespace RenderEngine {
struct VertexBufferLayoutElement {
GLint count;
GLenum type;
GLboolean normalized;
unsigned int size;
};
class VertexBufferLayout {
public:
VertexBufferLayout();
void reserveElements(const size_t count);
unsigned int getStride() const { return m_stride; }
void addElementLayoutFloat(const unsigned int count, const bool normalized);
const std::vector<VertexBufferLayoutElement>& getLayoutElements() const { return m_layoutElments; }
private:
std::vector<VertexBufferLayoutElement> m_layoutElments;
unsigned int m_stride;
};
} | true |
982b3022f0cb7a514d2eed4567e0ea05309bbf9b | C++ | romka0017/TextFileProcessor | /include/inputparameters.h | UTF-8 | 561 | 2.578125 | 3 | [] | no_license | #ifndef __INPUT_PARAMETERS_H__
#define __INPUT_PARAMETERS_H__
#include <cstring>
#include <string>
#include <iostream>
// Mode
enum {
UNDEFINED_MODE = 0,
WORDS_MODE = 1,
CHECKSUM_MODE = 2
};
class InputParams
{
public:
int ParseInputString(int argc, char* argv[]);
unsigned char m_Mode = UNDEFINED_MODE;
std::string m_FileName;
std::string m_NeededWord;
private:
std::string GetStringArgument(char* argv[], unsigned char index, int nArgNum);
bool m_bPrintHelp = false;
};
#endif // __INPUT_PARAMETERS_H__
| true |
39c511ba6fde0043e8f4a58d9e957db200314155 | C++ | deissh/cpp-labs | /3-4/8a.cpp | UTF-8 | 669 | 3.390625 | 3 | [] | no_license | // Кудявцев К. А. ИПБ-20; 3.3 #8a
/*
Задача 8a.
С клавиатуры вводится строка.
a. Заменить все вхождения подстроки «я» на подстроку «ты».
*/
#include <iostream>
#include <string>
std::string readStr() {
std::string val;
std::cout << "> ";
std::string ch;
do {
std::cin >> ch;
val += ' ' + ch;
} while (!ch.ends_with("."));
return val;
}
int main() {
auto input = readStr();
auto i = input.find('i');
while (i != -1) {
input.replace(i, 1, "you");
i = input.find('i');
}
std::cout << "result=" << input;
return 0;
} | true |
b853e69efdeec4197c374de18481107ff09b06fe | C++ | PIesy/GameGl | /Framework/world.h | UTF-8 | 1,545 | 2.9375 | 3 | [] | no_license | #ifndef WORLD_H
#define WORLD_H
#include "worldobject.h"
#include "camera.h"
#include "drawableworldobject.h"
#include "light.h"
#include "material.h"
#include <list>
class World
{
std::list<Camera> cameras;
std::list<DrawableWorldObject> drawableObjects;
std::vector<Light> pointLights;
std::vector<Light> directionalLights;
std::vector<Light> spotlights;
Vec3 worldSize = {1000.0f, 1000.0f, 1000.0f};
float scaleFactor = 1;
public:
World();
std::list<Camera> GetCameras() const;
void SetCameras(const std::list<Camera>& value);
Camera& AddCamera(const Vec3& position);
void RemoveCamera(Camera& cam);
DrawableWorldObject& AddObject(const Mesh& obj, const Vec3& position, const Material& overrideMaterial = {});
DrawableWorldObject& AddObject(const std::vector<Mesh>& obj, const Vec3& position, const Material& overrideMaterial = {});
void removeObject(DrawableWorldObject& obj);
std::list<DrawableWorldObject>& GetDrawableObjects();
Light& AddPointLight(const Vec3& position, const Vec3& color);
Light& AddSpotlight(const Vec3& position, const Vec3& color, const Vec3& direction, float angle);
Light& AddDirectionalLight(const Vec3& color, const Vec3& direction);
std::vector<Light>& GetPointLights();
std::vector<Light>& GetDirectionalLights();
std::vector<Light>& GetSpotights();
Vec3 GetWorldSize() const;
void SetWorldSize(const Vec3& value);
float GetScaleFactor() const;
void SetScaleFactor(float value);
};
#endif // WORLD_H
| true |
197c99505e335c6c48eb4f3e9e3b8e841ed979fe | C++ | cheeseH/varisev | /src/concurrentqueue.h | UTF-8 | 2,961 | 3.03125 | 3 | [] | no_license | /*
* concurrentqueue.h
*
* Created on: 2015年11月19日
* Author: cheese
*/
#ifndef CONCURRENTQUEUE_H_
#define CONCURRENTQUEUE_H_
#include "varisheader.h"
#include <condition_variable>
#include <atomic>
#include <mutex>
#include <thread>
#include <iostream>
template <typename T>
class ConcurrentQueue
{
T* buffer;
size_t qmod;
std::atomic<size_t> head, tail, claimg, claimp;
std::condition_variable waitForEpt, waitForFll;
std::mutex emtx, fmtx;
std::atomic<size_t> popWaitCount, pushWaitCount;
private:
size_t i2p(size_t i) const;
public:
ConcurrentQueue(size_t minSize);
~ConcurrentQueue();
void pop(T& data);
void push(const T& data);
size_t getCapacity() const;
bool isEmpty() const;
bool isFull() const;
};
template <typename T>
inline size_t ConcurrentQueue<T>::i2p(size_t i) const
{
return i & qmod;
}
template <typename T>
ConcurrentQueue<T>::ConcurrentQueue(size_t minSize)
: head(0), tail(0), claimg(0), claimp(0), popWaitCount(0), pushWaitCount(0)
{
size_t capacity = 1;
while(minSize != 0)
{
capacity <<= 1;
minSize >>= 1;
}
buffer = new T[capacity];
qmod = capacity - 1;
}
template <typename T>
ConcurrentQueue<T>::~ConcurrentQueue()
{
delete[] buffer;
}
template <typename T>
void ConcurrentQueue<T>::pop(T& data)
{
size_t cg, tn;
do
{
++popWaitCount;
while((cg = claimg.load()) == (tn = i2p(tail.load())))
{
std::unique_lock<std::mutex> lck(emtx);
waitForEpt.wait(lck);
}
--popWaitCount;
} while(!claimg.compare_exchange_weak(cg, i2p(cg + 1)));
std::cout<<"after pop:"<<claimg.load()<<std::endl;
data = buffer[cg];
size_t oh = cg, nh = i2p(cg + 1);
while(!head.compare_exchange_weak(oh, nh))
{
std::this_thread::yield();
oh = cg;
}
size_t odwc = pushWaitCount.load();
while(odwc > 0 && odwc <= pushWaitCount.load() && !isEmpty())
{
odwc = pushWaitCount.load();
waitForFll.notify_all();
std::this_thread::yield();
}
}
template <typename T>
void ConcurrentQueue<T>::push(const T& data)
{
size_t cp, h;
do
{
++pushWaitCount;
while(i2p((cp = claimp.load()) + 1) == (h = head.load()))
{
std::cout<<"dead1"<<std::endl;
std::unique_lock<std::mutex> lck(fmtx);
waitForFll.wait(lck);
}
--pushWaitCount;
} while(!claimp.compare_exchange_weak(cp, i2p(cp + 1)));
buffer[cp] = data;
size_t ot = cp, nt = i2p(cp + 1);
while(!tail.compare_exchange_weak(ot, nt))
{
std::this_thread::yield();
ot = cp;
}
size_t odwc = popWaitCount.load();
if(odwc > 0 && odwc <= popWaitCount.load() && !isFull())
{
odwc = popWaitCount.load();
waitForEpt.notify_all();
std::this_thread::yield();
}
}
template <typename T>
inline size_t ConcurrentQueue<T>::getCapacity() const
{
return qmod + 1;
}
template <typename T>
inline bool ConcurrentQueue<T>::isEmpty() const
{
return head.load() == tail.load();
}
template <typename T>
inline bool ConcurrentQueue<T>::isFull() const
{
return head.load() == i2p(tail.load() + 1);
}
#endif
| true |
00f3130cc525e45e68d02b196bebd1f4c327d461 | C++ | msrshahrukh100/Iqra | /Hackerrank/counting2.cpp | UTF-8 | 332 | 2.703125 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main()
{
int n;
cin>>n;
int a[n+1];
for(int i=0; i<n; i++)
cin>>a[i];
int count[100] = {0};
for(int i=0; i<n; i++)
count[a[i]]++;
for(int i=0; i<100; i++)
{
if(count[i] == 0)
continue;
while(count[i]--)
cout<<i<<" ";
}
// cout<<count[i]<<" ";
return 0;
} | true |
2c1b624ad12344889f3ac1d0785ece6c77067902 | C++ | fantasiorona/ecs | /ecs/main.cpp | UTF-8 | 3,741 | 2.71875 | 3 | [] | no_license | #include <SFML/Graphics.hpp>
#include <cassert>
#include "RandomNumberGenerator.h"
#include "ColorPicker.h"
#include "ECSManager.h"
#include "CircleMoveSystem.h"
#include "RenderSystem.h"
#include "StatsSystem.h"
#include "CircleComponents.h"
#include "StatsComponent.h"
/**
* 2.6 GHz Quad-Core Intel Core i7
* In release build the old code ran smoothly with 33ms when there were 100.000 entities,
* whilst the new code could handle 155000 entites. There was a 55% improvement.
*
* Intel Core i7-8550U CPU @ 1.80GHz
* In release build the old code ran smoothly with 33ms when there were 85.000 entities,
* whilst the new code could handle 135000 entites. There was a 58% improvement.
*/
int main()
{
const unsigned int windowWidth = 1024;
const unsigned int windowHeight = 768;
const unsigned int numEntities = 155000;
const sf::Rect<float> bounds(0.f, 0.f, windowWidth, windowHeight);
sf::RenderWindow window(sf::VideoMode(windowWidth, windowHeight), "ECS Moving Circles");
// The ECSManager coordinates entities, components and systems
ECSManager manager;
// Register systems with the manager
manager.addSystem<CircleMoveSystem>();
manager.addSystem<RenderSystem>(&window);
manager.addSystem<StatsSystem>(&window);
// Generate circle entities
auto& rng = RandomNumberGenerator::getInstance();
for (unsigned int i = 0; i < numEntities; i++) {
// create the entity with random color, radius, and velocity
// always start from center position
const sf::Vector2f position((bounds.left + bounds.width) / 2.f, (bounds.top + bounds.height) / 2.f);
const auto color = ColorPicker::generateRandomColor();
const auto radius = rng.generateFloat(8.f, 32.f);
const auto twoPi = static_cast<float>(atan(1.0) * 4 * 2);
const auto angle = rng.generateFloat(0.f, twoPi);
const auto v = rng.generateFloat(5.f, 100.f);
// scale the unit vector by velocity
const sf::Vector2f velocity(cos(angle) * v, sin(angle) * v);
// --------------------------------
// Create the entity and components
auto entity = manager.createEntity();
auto& transform = manager.addComponent<TransformComponent>(entity);
transform.position = position;
transform.velocity = velocity;
auto& colorComponent = manager.addComponent<ColorComponent>(entity);
colorComponent.color = color;
auto& collisionComponent = manager.addComponent<CircleCollisionComponent>(entity);
collisionComponent.radius = radius;
collisionComponent.bounds = {
std::make_pair(sf::Vector2f(0.f, 1.f), bounds.top),
std::make_pair(sf::Vector2f(-1.f, 0.f), bounds.left + bounds.width),
std::make_pair(sf::Vector2f(0.f, -1.f), bounds.top + bounds.height),
std::make_pair(sf::Vector2f(1.f, 0.f), bounds.left)
};
}
// Entity for stats display
auto statsEntity = manager.createEntity();
auto& statsComponent = manager.addComponent<StatsComponent>(statsEntity);
const auto success = statsComponent.font.loadFromFile("fonts/JetBrainsMono-Regular.ttf");
assert(success);
// configure the font
statsComponent.text.setFont(statsComponent.font);
statsComponent.text.setCharacterSize(24);
statsComponent.text.setFillColor(sf::Color::Yellow);
sf::Clock clock;
while (window.isOpen())
{
const auto dt = clock.restart();
sf::Event event;
while (window.pollEvent(event))
{
if (event.type == sf::Event::Closed)
window.close();
}
manager.update(dt.asSeconds());
window.display();
}
return 0;
}
| true |
7e33188e396b46750c17327e73e507755211b598 | C++ | imdakshraj45/Practicer-Coding | /17EGICS021_ARRAY-5.cpp | UTF-8 | 366 | 3.03125 | 3 | [] | no_license | #include<iostream>
#include<vector>
using namespace std;
int main()
{
int n,i,t=0,sum=0;
vector<int> a[n];
cout<<"Enter size : ";
cin>>n;
cout<<"Enter an elements of array :\n";
for(i=0;i<n;i++)
a[i];
for(i=0;i<n;i++)
{
if(a[i]<a[i+1])
{
sum+=a[i];
}
else
{
t=a[i];
break;
}
}
cout<<(sum+t);
}
| true |
c9e7023c880c8c0df068829565216a3096c611f9 | C++ | Miserlou/RJModules | /src/Iir.h | UTF-8 | 6,764 | 2.609375 | 3 | [
"MIT"
] | permissive | #ifndef STK_IIR_H
#define STK_IIR_H
#include "Filter.h"
namespace stk {
/***************************************************/
/*! \class Iir
\brief STK general infinite impulse response filter class.
This class provides a generic digital filter structure that can be
used to implement IIR filters. For filters containing only
feedforward terms, the Fir class is slightly more efficient.
In particular, this class implements the standard difference
equation:
a[0]*y[n] = b[0]*x[n] + ... + b[nb]*x[n-nb] -
a[1]*y[n-1] - ... - a[na]*y[n-na]
If a[0] is not equal to 1, the filter coeffcients are normalized
by a[0].
The \e gain parameter is applied at the filter input and does not
affect the coefficient values. The default gain value is 1.0.
This structure results in one extra multiply per computed sample,
but allows easy control of the overall filter gain.
by Perry R. Cook and Gary P. Scavone, 1995--2019.
*/
/***************************************************/
class Iir : public Filter
{
public:
//! Default constructor creates a zero-order pass-through "filter".
Iir( void );
//! Overloaded constructor which takes filter coefficients.
/*!
An StkError can be thrown if either of the coefficient vector
sizes is zero, or if the a[0] coefficient is equal to zero.
*/
Iir( std::vector<StkFloat> &bCoefficients, std::vector<StkFloat> &aCoefficients );
//! Class destructor.
~Iir( void );
//! Set filter coefficients.
/*!
An StkError can be thrown if either of the coefficient vector
sizes is zero, or if the a[0] coefficient is equal to zero. If
a[0] is not equal to 1, the filter coeffcients are normalized by
a[0]. The internal state of the filter is not cleared unless the
\e clearState flag is \c true.
*/
void setCoefficients( std::vector<StkFloat> &bCoefficients, std::vector<StkFloat> &aCoefficients, bool clearState = false );
//! Set numerator coefficients.
/*!
An StkError can be thrown if coefficient vector is empty. Any
previously set denominator coefficients are left unaffected. Note
that the default constructor sets the single denominator
coefficient a[0] to 1.0. The internal state of the filter is not
cleared unless the \e clearState flag is \c true.
*/
void setNumerator( std::vector<StkFloat> &bCoefficients, bool clearState = false );
//! Set denominator coefficients.
/*!
An StkError can be thrown if the coefficient vector is empty or
if the a[0] coefficient is equal to zero. Previously set
numerator coefficients are unaffected unless a[0] is not equal to
1, in which case all coeffcients are normalized by a[0]. Note
that the default constructor sets the single numerator coefficient
b[0] to 1.0. The internal state of the filter is not cleared
unless the \e clearState flag is \c true.
*/
void setDenominator( std::vector<StkFloat> &aCoefficients, bool clearState = false );
//! Return the last computed output value.
StkFloat lastOut( void ) const { return lastFrame_[0]; };
//! Input one sample to the filter and return one output.
StkFloat tick( StkFloat input );
//! Take a channel of the StkFrames object as inputs to the filter and replace with corresponding outputs.
/*!
The StkFrames argument reference is returned. The \c channel
argument must be less than the number of channels in the
StkFrames argument (the first channel is specified by 0).
However, range checking is only performed if _STK_DEBUG_ is
defined during compilation, in which case an out-of-range value
will trigger an StkError exception.
*/
StkFrames& tick( StkFrames& frames, unsigned int channel = 0 );
//! Take a channel of the \c iFrames object as inputs to the filter and write outputs to the \c oFrames object.
/*!
The \c iFrames object reference is returned. Each channel
argument must be less than the number of channels in the
corresponding StkFrames argument (the first channel is specified
by 0). However, range checking is only performed if _STK_DEBUG_
is defined during compilation, in which case an out-of-range value
will trigger an StkError exception.
*/
StkFrames& tick( StkFrames& iFrames, StkFrames &oFrames, unsigned int iChannel = 0, unsigned int oChannel = 0 );
protected:
};
inline StkFloat Iir :: tick( StkFloat input )
{
size_t i;
outputs_[0] = 0.0;
inputs_[0] = gain_ * input;
for ( i=b_.size()-1; i>0; i-- ) {
outputs_[0] += b_[i] * inputs_[i];
inputs_[i] = inputs_[i-1];
}
outputs_[0] += b_[0] * inputs_[0];
for ( i=a_.size()-1; i>0; i-- ) {
outputs_[0] += -a_[i] * outputs_[i];
outputs_[i] = outputs_[i-1];
}
lastFrame_[0] = outputs_[0];
return lastFrame_[0];
}
inline StkFrames& Iir :: tick( StkFrames& frames, unsigned int channel )
{
#if defined(_STK_DEBUG_)
if ( channel >= frames.channels() ) {
oStream_ << "Iir::tick(): channel and StkFrames arguments are incompatible!";
handleError( StkError::FUNCTION_ARGUMENT );
}
#endif
StkFloat *samples = &frames[channel];
size_t i;
unsigned int hop = frames.channels();
for ( unsigned int j=0; j<frames.frames(); j++, samples += hop ) {
outputs_[0] = 0.0;
inputs_[0] = gain_ * *samples;
for ( i=b_.size()-1; i>0; i-- ) {
outputs_[0] += b_[i] * inputs_[i];
inputs_[i] = inputs_[i-1];
}
outputs_[0] += b_[0] * inputs_[0];
for ( i=a_.size()-1; i>0; i-- ) {
outputs_[0] += -a_[i] * outputs_[i];
outputs_[i] = outputs_[i-1];
}
*samples = outputs_[0];
}
lastFrame_[0] = *(samples-hop);
return frames;
}
inline StkFrames& Iir :: tick( StkFrames& iFrames, StkFrames& oFrames, unsigned int iChannel, unsigned int oChannel )
{
#if defined(_STK_DEBUG_)
if ( iChannel >= iFrames.channels() || oChannel >= oFrames.channels() ) {
oStream_ << "Iir::tick(): channel and StkFrames arguments are incompatible!";
handleError( StkError::FUNCTION_ARGUMENT );
}
#endif
StkFloat *iSamples = &iFrames[iChannel];
StkFloat *oSamples = &oFrames[oChannel];
size_t i;
unsigned int iHop = iFrames.channels(), oHop = oFrames.channels();
for ( unsigned int j=0; j<iFrames.frames(); j++, iSamples += iHop, oSamples += oHop ) {
outputs_[0] = 0.0;
inputs_[0] = gain_ * *iSamples;
for ( i=b_.size()-1; i>0; i-- ) {
outputs_[0] += b_[i] * inputs_[i];
inputs_[i] = inputs_[i-1];
}
outputs_[0] += b_[0] * inputs_[0];
for ( i=a_.size()-1; i>0; i-- ) {
outputs_[0] += -a_[i] * outputs_[i];
outputs_[i] = outputs_[i-1];
}
*oSamples = outputs_[0];
}
lastFrame_[0] = *(oSamples-oHop);
return iFrames;
}
} // stk namespace
#endif
| true |
7335cea305739ae1ab0731e08b1464b5d1d4bb1a | C++ | xSeanliux/CompetitiveProgramming | /UVa/272/272.cpp | UTF-8 | 644 | 2.65625 | 3 | [] | no_license | #include <iostream>
#include <string.h>
using namespace std;
string query;
int N;
int main(){
N = 0;
while(getline(cin, query)){
for(int i = 0; i < query.length(); i++){
if(query[i] == '"'){
string b = query.substr(0, i);
string k = query.substr(i+1);
if(N % 2 == 0){
query = b + "``" + k;
i++;
} else {
query = b + "''" + k;
i++;
}
N++;
//cout << N << endl;
}
}
cout << query << endl;
}
}
| true |
4dc39b2fda637259a405f66fcf237659a9964703 | C++ | Zilby/Graphics-Final | /monorepo-Zilby/Assignment5_SceneGraph/src/Camera.cpp | UTF-8 | 1,940 | 3.28125 | 3 | [] | no_license | #include "Camera.h"
#include "glm/gtx/transform.hpp"
#include <iostream>
// Camera constructor
Camera::Camera(){
std::cout << "(Camera.cpp) Constructor called\n";
eyePosition = glm::vec3(0.0f,2.0f, 5.0f); // FIX: Typically this should be 0,0,0, but I moved for our assignment.
viewDirection = glm::vec3(0.0f,0.0f, -1.0f);
upVector = glm::vec3(0.0f, 1.0f, 0.0f);
}
void Camera::mouseLook(int mouseX, int mouseY){
// Record our new position as a vector
glm::vec2 newMousePosition(mouseX, mouseY);
// Detect how much the mouse has moved since
// the last time
glm::vec2 mouseDelta = 0.01f*(newMousePosition-oldMousePosition)
;
viewDirection = glm::mat3(glm::rotate(-mouseDelta.x, upVector)) *
viewDirection;
// Update our old position after we have made changes
oldMousePosition = newMousePosition;
}
void Camera::moveForward(float speed){
eyePosition.z -= speed;
}
void Camera::moveBackward(float speed){
eyePosition.z += speed;
}
void Camera::moveLeft(float speed){
eyePosition.x -= speed;
}
void Camera::moveRight(float speed){
eyePosition.x += speed;
}
void Camera::moveUp(float speed){
eyePosition.y += speed;
}
void Camera::moveDown(float speed){
eyePosition.y -= speed;
}
float Camera::getEyeXPosition(){
return eyePosition.x;
}
float Camera::getEyeYPosition(){
return eyePosition.y;
}
float Camera::getEyeZPosition(){
return eyePosition.z;
}
float Camera::getViewXDirection(){
return viewDirection.x;
}
float Camera::getViewYDirection(){
return viewDirection.y;
}
float Camera::getViewZDirection(){
return viewDirection.z;
}
// Get our view matrix from this camera
glm::mat4 Camera::getWorldToViewmatrix() const{
// Think about the second argument and why that is
// setup as it is.
return glm::lookAt( eyePosition,
eyePosition + viewDirection,
upVector);
}
| true |
b95550771111d25e76431dd75cd655a2c4775158 | C++ | lij313/BattleShip | /Code/Camera.cpp | UTF-8 | 1,938 | 3.0625 | 3 | [] | no_license | #ifdef __APPLE__
# include <OpenGL/gl.h>
# include <OpenGL/glu.h>
# include <GLUT/glut.h>
#else
# include <GL/gl.h>
# include <GL/glu.h>
# include <GL/freeglut.h>
#endif
#include "Camera.h"
#include <ctime>
#include <cmath>
#include <iostream>
#define pi 3.1415926
Camera::Camera(Ship *ship){
this->ship=ship;
this->distance = 20;
this->angleAround = 0;
this->pitch = 20;
}
float Camera::calcHorizontalDistance(){
float radians = (pitch*pi)/180;
return distance*cos(radians);
}
float Camera::calcVerticalDistance(){
float radians = (pitch*pi)/180;
return distance*sin(radians);
}
void Camera::move(int dir, int x, int y){
calculateZoom(dir, x, y);
calculatePitch(x, y);
calcAngleAround(x, y);
float horizontalDistance = calcHorizontalDistance();
float verticalDistance = calcVerticalDistance();
calcCameraPos(horizontalDistance, verticalDistance);
lastX=x;
lastY=y;
}
void Camera::calculateZoom(int dir, int x, int y){
float zoomLevel = dir;
distance-=zoomLevel*0.3f;
if(distance < 10)
distance=10;
if(distance > 200)
distance = 200;
}
void Camera::calculatePitch(int x, int y){
int dy=y-lastY;
float deltaPitch = dy*0.3;
pitch += deltaPitch;
}
void Camera::calcAngleAround(int x, int y){
int dx=x-lastX;
float angleChange = dx*0.3;
angleAround-=angleChange;
angleAround=std::fmod(angleAround,360);
}
void Camera::calcCameraPos(float horizontalDistance, float verticalDistance){
float theta = ship->getCurrentPos().getY() + angleAround;
float radians = (theta*pi)/180;
float offsetX = horizontalDistance*sin(radians);
float offsetZ = horizontalDistance*cos(radians);
float x = ship->getCurrentPos().getX() - offsetX;
float z = ship->getCurrentPos().getZ() - offsetZ;
if(verticalDistance < 0)
verticalDistance = 1;
position = Point3D(x, verticalDistance, z);
} | true |
10ace56c9d60c76a11cdd62a806c921a581535f6 | C++ | KorbenC/InterviewQuestions | /Numbers/Fibonacci.cpp | UTF-8 | 524 | 3.515625 | 4 | [] | no_license | #include <iostream>
using namespace std;
int fib(unsigned long int n)
{
if (n <= 1)
{
return 1;
}
else
{
return fib(n-1)+ fib(n-2);
}
}
int main()
{
unsigned long int n;
while(1)
{
cout << "Enter a number (0 to quit): ";
cin >> n;
if(n == 0)
exit(0);
for(int i = 0; i <= n; i++)
{
cout << fib(i) << endl;
}
}
return 0;
}
| true |
adddffcf8b9e260079b9214597060364061f3ce6 | C++ | cielavenir/procon | /atcoder/abc/tyama_atcoderABC018D.cpp | UTF-8 | 1,851 | 3.0625 | 3 | [
"0BSD"
] | permissive | #include <algorithm>
using namespace std;
template <class BidirectionalIterator>
bool next_combination(BidirectionalIterator first1,
BidirectionalIterator last1,
BidirectionalIterator first2,
BidirectionalIterator last2)
{
if(( first1 == last1 ) || ( first2 == last2 ))return false;
BidirectionalIterator m1 = last1;
BidirectionalIterator m2 = last2; --m2;
while(--m1 != first1 && !(* m1 < *m2 ));
bool result = (m1 == first1 ) && !(* first1 < *m2 );
if(!result){
while( first2 != m2 && !(* m1 < * first2 ))++first2;
first1 = m1;
iter_swap(first1 , first2 );
++ first1;
++ first2;
}
if(( first1 != last1 ) && ( first2 != last2 )){
m1 = last1 ; m2 = first2 ;
while(( m1 != first1 ) && (m2 != last2 )){
iter_swap (--m1 , m2 );
++m2;
}
reverse(first1 , m1);
reverse(first1 , last1);
reverse(m2 , last2);
reverse(first2 , last2);
}
return !result;
}
template <class BidirectionalIterator>
bool next_combination (BidirectionalIterator first,
BidirectionalIterator middle,
BidirectionalIterator last)
{return next_combination(first , middle , middle , last);}
#include <iostream>
#include <string>
#include <vector>
#include <set>
#include <numeric>
int main(){
int N,M,P,Q,R;
cin>>N>>M>>P>>Q>>R;
vector<pair<pair<int,int>,int> >w(R);
for(int i=0;i<R;i++){
int x,y,r;
cin>>x>>y>>r;
w[i]=make_pair(make_pair(x-1,y-1),r);
}
vector<int>female(N);
iota(female.begin(),female.end(),0);
int r=0;
do{
set<int>females;
for(int i=0;i<P;i++)females.insert(female[i]);
vector<int>s(M);
for(int i=0;i<R;i++){
if(females.find(w[i].first.first)!=females.end()){
s[w[i].first.second]+=w[i].second;
}
}
sort(s.begin(),s.end(),greater<int>());
int z=0;
for(int i=0;i<Q;i++)z+=s[i];
if(r<z)r=z;
}while(next_combination(female.begin(),female.begin()+P,female.end()));
cout<<r<<endl;
}
| true |
9440dc1e9f5a1421d3ca2f0b5abee99fef1a7f1e | C++ | fhsmartking/Leetcode | /offer_T49.cpp | UTF-8 | 649 | 3.203125 | 3 | [] | no_license | #include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
class Solution {
public:
int nthUglyNumber(int n) {
if (n <= 0) return -1;
vector<int> uglyVec(n);
uglyVec[0] = 1;
int a = 0, b = 0, c = 0;
for (int i = 1; i < n; i++) {
uglyVec[i] = min(uglyVec[a] * 2, uglyVec[b] * 3);
uglyVec[i] = min(uglyVec[i], uglyVec[c] * 5);
if (uglyVec[i] == uglyVec[a] * 2) a++;
if (uglyVec[i] == uglyVec[b] * 3) b++;
if (uglyVec[i] == uglyVec[c] * 5) c++;
}
return uglyVec[n - 1];
}
}; | true |
c06e57879c24537721d29fd915370400af68ac00 | C++ | hsoj/hamclock | /plot.cpp | UTF-8 | 15,601 | 2.609375 | 3 | [
"MIT"
] | permissive | /* handle each plotting area.
*/
#include "HamClock.h"
#define BORDER_COLOR GRAY
#define TICKLEN 2 // length of plot tickmarks, pixels
#define LGAP 21 // left gap for labels
#define BGAP 15 // bottom gap for labels
#define FONTW 6 // font width with gap
#define FONTH 8 // font height
#define NBRGAP 15 // large plot overlay number top gap
static int tickmarks (float min, float max, int numdiv, float ticks[]);
/* plot the given data within the given box.
* return whether had anything to plot.
* N.B. if both labels are NULL, use same labels and limits as previous call
*/
bool plotXY (const SBox &box, float x[], float y[], int nxy, const char *xlabel, const char *ylabel,
uint16_t color, float label_value)
{
char buf[32];
sprintf (buf, "%.*f", label_value >= 1000 ? 0 : 1, label_value);
return (plotXYstr (box, x, y, nxy, xlabel, ylabel, color, buf));
}
/* same as plotXY but label is a string
*/
bool plotXYstr (const SBox &box, float x[], float y[], int nxy, const char *xlabel, const char *ylabel,
uint16_t color, char *label_str)
{
resetWatchdog();
// no labels implies overlay previous plot
bool overlay = xlabel == NULL && ylabel == NULL;
// persistent scale info in case of subsequent overlay
# define MAXTICKS 10
static float xticks[MAXTICKS+2], yticks[MAXTICKS+2];
static uint8_t nxt, nyt;
static float minx, maxx;
static float miny, maxy;
static float dx, dy;
char buf[32];
uint8_t bufl;
// set font and color
selectFontStyle (BOLD_FONT, FAST_FONT);
tft.setTextColor(color);
// report if no data
if (nxy < 1 || !x || !y) {
plotMessage (box, color, "No data");
return (false);
}
// find new limits unless this is an overlay
if (!overlay) {
// find data extrema
minx = x[0]; maxx = x[0];
miny = y[0]; maxy = y[0];
for (int i = 1; i < nxy; i++) {
if (x[i] > maxx) maxx = x[i];
if (x[i] < minx) minx = x[i];
if (y[i] > maxy) maxy = y[i];
if (y[i] < miny) miny = y[i];
}
minx = floor(minx);
maxx = ceil(maxx);
if (maxx < minx + 1) {
minx -= 1;
maxx += 1;
}
miny = floor(miny);
maxy = ceil(maxy);
if (maxy < miny + 1) {
miny -= 1;
maxy += 1;
}
// find tickmarks
nxt = tickmarks (minx, maxx, MAXTICKS, xticks);
nyt = tickmarks (miny, maxy, MAXTICKS, yticks);
// handy ends
minx = xticks[0];
maxx = xticks[nxt-1];
miny = yticks[0];
maxy = yticks[nyt-1];
dx = maxx-minx;
dy = maxy-miny;
// erase all except bottom line which is map border
tft.fillRect (box.x, box.y, box.w, box.h-1, RA8875_BLACK);
// y tickmarks just to the left of the plot
bufl = sprintf (buf, "%d", (int)maxy);
tft.setCursor (box.x+LGAP-TICKLEN-bufl*FONTW, box.y); tft.print (buf);
bufl = sprintf (buf, "%d", (int)miny);
tft.setCursor (box.x+LGAP-TICKLEN-bufl*FONTW, box.y+box.h-BGAP-FONTH); tft.print (buf);
for (int i = 0; i < nyt; i++) {
uint16_t ty = (uint16_t)(box.y + (box.h-BGAP)*(1 - (yticks[i]-miny)/dy) + 0.5);
tft.drawLine (box.x+LGAP-TICKLEN, ty, box.x+LGAP, ty, color);
}
// y label is down the left side
uint8_t ylen = strlen(ylabel);
uint16_t ly0 = box.y + (box.h - BGAP - ylen*FONTH)/2;
for (uint8_t i = 0; i < ylen; i++) {
tft.setCursor (box.x+LGAP/3, ly0+i*FONTH);
tft.print (ylabel[i]);
}
// x tickmarks just below plot
uint16_t txty = box.y+box.h-FONTH-2;
tft.setCursor (box.x+LGAP, txty); tft.print (minx,0);
bufl = sprintf (buf, "%c%d", maxx > 0 ? '+' : ' ', (int)maxx);
tft.setCursor (box.x+box.w-2-bufl*FONTW, txty); tft.print (buf);
for (int i = 0; i < nxt; i++) {
uint16_t tx = (uint16_t)(box.x+LGAP + (box.w-LGAP-1)*(xticks[i]-minx)/dx);
tft.drawLine (tx, box.y+box.h-BGAP, tx, box.y+box.h-BGAP+TICKLEN, color);
}
// always label 0 if within larger range
if (minx < 0 && maxx > 0) {
uint16_t zx = (uint16_t)(box.x+LGAP + (box.w-LGAP)*(0-minx)/dx + 0.5);
tft.setCursor (zx-FONTW/2, txty); tft.print (0);
}
// x label is centered about the plot across the bottom
uint8_t xlen = strlen(xlabel);
uint16_t lx0 = box.x + LGAP + (box.w - LGAP - xlen*FONTW)/2;
for (uint8_t i = 0; i < xlen; i++) {
tft.setCursor (lx0+i*FONTW, box.y+box.h-FONTH-2);
tft.print (xlabel[i]);
}
}
// draw plot
uint16_t last_px = 0, last_py = 0;
resetWatchdog();
for (int i = 0; i < nxy; i++) {
uint16_t px = (uint16_t)(box.x+LGAP + (box.w-LGAP-1)*(x[i]-minx)/dx + 0.5);
uint16_t py = (uint16_t)(box.y + 1 + (box.h-BGAP-2)*(1 - (y[i]-miny)/dy) + 0.5);
if (i > 0 && (last_px != px || last_py != py))
tft.drawLine (last_px, last_py, px, py, color); // avoid bug with 0-length lines
else if (nxy == 1)
tft.drawLine (box.x+LGAP, py, box.x+box.w-1, py, color); // one point clear across
last_px = px;
last_py = py;
}
// draw plot border
tft.drawRect (box.x+LGAP, box.y, box.w-LGAP, box.h-BGAP, BORDER_COLOR);
if (!overlay) {
// overlay large center value on top in gray
tft.setTextColor(BRGRAY);
selectFontStyle (BOLD_FONT, LARGE_FONT);
uint16_t bw, bh;
getTextBounds (label_str, &bw, &bh);
uint16_t text_x = box.x+LGAP+(box.w-LGAP-bw)/2;
uint16_t text_y = box.y+NBRGAP+bh;
tft.setCursor (text_x, text_y);
tft.print (label_str);
}
// printFreeHeap (F("plotXYstr"));
// ok
return (true);
}
/* plot values of geomagnetic Kp index in boxy form in box b.
* 8 values per day, nhkp historical followed by npkp predicted.
* ala http://www.swpc.noaa.gov/products/planetary-k-index
*/
void plotKp (SBox &box, uint8_t kp[], uint8_t nhkp, uint8_t npkp, uint16_t color)
{
resetWatchdog();
# define MAXKP 9
// N.B. null font origin is upper left
selectFontStyle (BOLD_FONT, FAST_FONT);
tft.setTextColor(color);
// erase all except bottom line which is map border
tft.fillRect (box.x, box.y, box.w, box.h-1, RA8875_BLACK);
// y tickmarks just to the left of the plot
tft.setCursor (box.x+LGAP-TICKLEN-2-FONTW, box.y); tft.print (MAXKP);
tft.setCursor (box.x+LGAP-TICKLEN-2-FONTW, box.y+box.h-BGAP-FONTH); tft.print (0);
for (uint8_t k = 0; k <= MAXKP; k++) {
uint16_t h = k*(box.h-BGAP)/MAXKP;
uint16_t ty = box.y + box.h - BGAP - h;
tft.drawLine (box.x+LGAP-TICKLEN, ty, box.x+LGAP, ty, color);
}
// y label is down the left side
static const char ylabel[] = "Planetary Kp";
uint8_t ylen = sizeof(ylabel)-1;
uint16_t ly0 = box.y + (box.h - BGAP - ylen*FONTH)/2;
for (uint8_t i = 0; i < ylen; i++) {
tft.setCursor (box.x+LGAP/3, ly0+i*FONTH);
tft.print (ylabel[i]);
}
// x labels
uint8_t nkp = nhkp + npkp;
tft.setCursor (box.x+LGAP, box.y+box.h-FONTH-2);
tft.print (-nhkp/8);
tft.setCursor (box.x+box.w-2*FONTW, box.y+box.h-FONTH-2);
tft.print('+'); tft.print (npkp/8);
tft.setCursor (box.x+LGAP+(box.w-LGAP)/2-2*FONTW, box.y+box.h-FONTH-2);
tft.print (F("Days"));
// label now if within wider range
if (nhkp > 0 && npkp > 0) {
uint16_t zx = box.x + LGAP + nhkp*(box.w-LGAP)/nkp;
tft.setCursor (zx-FONTW/2, box.y+box.h-FONTH-2);
tft.print(0);
}
// x ticks
for (uint8_t i = 0; i < nkp/8; i++) {
uint16_t tx = box.x + LGAP + 8*i*(box.w-LGAP)/nkp;
tft.drawLine (tx, box.y+box.h-BGAP, tx, box.y+box.h-BGAP+TICKLEN, color);
}
// plot Kp values as colored vertical bars depending on strength
resetWatchdog();
for (uint8_t i = 0; i < nkp; i++) {
int8_t k = kp[i];
uint16_t c = k < 4 ? RA8875_GREEN : k == 4 ? RA8875_YELLOW : RA8875_RED;
uint16_t x = box.x + LGAP + i*(box.w-LGAP)/nkp;
uint16_t w = (box.w-LGAP)/nkp-1;
uint16_t h = k*(box.h-BGAP)/MAXKP;
uint16_t y = box.y + box.h - BGAP - h;
if (w > 0 || h > 0)
tft.fillRect (x, y, w, h, c);
}
// data border
tft.drawRect (box.x+LGAP, box.y, box.w-LGAP, box.h-BGAP, BORDER_COLOR);
// overlay large current value on top in gray
tft.setTextColor(BRGRAY);
selectFontStyle (BOLD_FONT, LARGE_FONT);
char buf[32];
sprintf (buf, "%d", kp[nhkp-1]);
uint16_t bw, bh;
getTextBounds (buf, &bw, &bh);
uint16_t text_x = box.x+LGAP+(box.w-LGAP-bw)/2;
uint16_t text_y = box.y+NBRGAP+bh;
tft.setCursor (text_x, text_y);
tft.print (buf);
// printFreeHeap (F("plotKp"));
}
/* shorten str IN PLACE as needed to be less that maxw pixels wide.
* return final width in pixels.
*/
static uint16_t maxStringW (char *str, uint16_t maxw)
{
uint8_t strl = strlen (str);
uint16_t bw;
while ((bw = getTextWidth(str)) > maxw)
str[strl--] = '\0';
return (bw);
}
/* print weather info in the given box
*/
void plotWX (const SBox &box, uint16_t color, const WXInfo &wi)
{
resetWatchdog();
// erase all except bottom line which is map border then add border
tft.fillRect (box.x, box.y, box.w, box.h-1, RA8875_BLACK);
tft.drawRect (box.x, box.y, box.w, box.h, GRAY);
const uint8_t indent = FONTW+2; // allow for attribution
uint16_t dy = box.h/3;
uint16_t ddy = box.h/5;
float f;
char buf[32];
uint16_t w;
// large temperature with degree symbol and units
tft.setTextColor(color);
selectFontStyle (BOLD_FONT, LARGE_FONT);
f = useMetricUnits() ? wi.temperature_c : 9*wi.temperature_c/5+32;
sprintf (buf, "%.0f %c", f, useMetricUnits() ? 'C' : 'F');
w = maxStringW (buf, box.w-indent);
tft.setCursor (box.x+indent+(box.w-indent-w)/2-8, box.y+dy);
tft.print(buf);
uint16_t bw, bh;
getTextBounds (buf+strlen(buf)-2, &bw, &bh);
selectFontStyle (BOLD_FONT, SMALL_FONT);
tft.setCursor (tft.getCursorX()-bw, tft.getCursorY()-2*bh/3);
tft.print('o');
dy += ddy;
// remaining info smaller
selectFontStyle (LIGHT_FONT, SMALL_FONT);
// humidity
sprintf (buf, "%.0f%% RH", wi.humidity_percent);
w = maxStringW (buf, box.w-indent);
tft.setCursor (box.x+indent+(box.w-indent-w)/2, box.y+dy);
tft.print (buf);
dy += ddy;
// wind
f = (useMetricUnits() ? 3.6 : 2.237) * wi.wind_speed_mps; // kph or mph
sprintf (buf, "%s @ %.0f %s", wi.wind_dir_name, f, useMetricUnits() ? "kph" : "mph");
w = maxStringW (buf, box.w-indent);
tft.setCursor (box.x+indent+(box.w-indent-w)/2, box.y+dy);
tft.print (buf);
dy += ddy;
// nominal conditions
strcpy (buf, wi.conditions);
w = maxStringW (buf, box.w-indent);
tft.setCursor (box.x+indent+(box.w-indent-w)/2, box.y+dy);
tft.print(buf);
// attribution very small down the left side
selectFontStyle (LIGHT_FONT, FAST_FONT);
uint8_t ylen = strlen(wi.attribution);
uint16_t ly0 = box.y + (box.h - ylen*FONTH)/2;
for (uint8_t i = 0; i < ylen; i++) {
tft.setCursor (box.x+2, ly0+i*FONTH);
tft.print (wi.attribution[i]);
}
// printFreeHeap (F("plotWX"));
}
/* plotBandConditions helper to plot one band condition
*/
static void BChelper (uint8_t band, uint16_t b_col, uint16_t r_col, uint16_t y, float rel)
{
#define RELCOL(r) ((r) < 0.33 ? RA8875_RED : ((r) < 0.66 ? RA8875_YELLOW : RA8875_GREEN))
selectFontStyle (LIGHT_FONT, SMALL_FONT);
tft.setTextColor(GRAY);
tft.setCursor (b_col, y);
tft.print(band);
tft.setTextColor(RELCOL(rel));
tft.setCursor (r_col, y);
if (rel > 0.99F)
rel = 0.99F; // 100 doesn't fit
char relbuf[10];
if (band == 80)
snprintf (relbuf, sizeof(relbuf), "%2.0f%%", 100*rel);
else
snprintf (relbuf, sizeof(relbuf), "%3.0f", 100*rel);
tft.print(relbuf);
}
/* print the band conditions in the given box.
* response is CSV short-path reliability 80-10.
* if response does not match expected format print it as an error message.
*/
bool plotBandConditions (const SBox &box, char response[], char config[])
{
resetWatchdog();
// erase all then draw border
tft.fillRect (box.x, box.y, box.w, box.h, RA8875_BLACK);
tft.drawRect (box.x, box.y, box.w, box.h, GRAY);
// crack
float bc80, bc60, bc40, bc30, bc20, bc17, bc15, bc12, bc10;
if (sscanf (response, "%f,%f,%f,%f,%f,%f,%f,%f,%f",
&bc80, &bc60, &bc40, &bc30, &bc20, &bc17, &bc15, &bc12, &bc10) != 9) {
plotMessage (box, RA8875_RED, response);
return (false);
}
// title
tft.setTextColor(RA8875_WHITE);
selectFontStyle (LIGHT_FONT, SMALL_FONT);
uint16_t h = box.h/5-2; // text row height
char *title = (char *) "VOACAP DE-DX";
uint16_t bw = getTextWidth (title);
tft.setCursor (box.x+(box.w-bw)/2, box.y+h);
tft.print (title);
// column locations
uint16_t bcol1 = box.x + 7; // band column 1
uint16_t rcol1 = bcol1 + box.w/4-10; // path reliability column 1
uint16_t bcol2 = rcol1 + box.w/4+14; // band column 2
uint16_t rcol2 = bcol2 + box.w/4-10; // path reliability column 2
uint16_t y = box.y + 2*h; // text y
// 8 bands, skip 60m
BChelper (80, bcol1, rcol1, y, bc80);
BChelper (40, bcol1, rcol1, y+h, bc40);
BChelper (30, bcol1, rcol1, y+2*h, bc30);
BChelper (20, bcol1, rcol1, y+3*h, bc20);
BChelper (17, bcol2, rcol2, y, bc17);
BChelper (15, bcol2, rcol2, y+h, bc15);
BChelper (12, bcol2, rcol2, y+2*h, bc12);
BChelper (10, bcol2, rcol2, y+3*h, bc10);
// notes
tft.setTextColor(GRAY);
selectFontStyle (LIGHT_FONT, FAST_FONT);
bw = maxStringW (config, box.w);
tft.setCursor (box.x+(box.w-bw)/2, box.y+box.h-10); // beware comma descender
tft.print (config);
// printFreeHeap (F("plotBC"));
// ok
return (true);
}
/* print a message in a box, take care not to go outside
*/
void plotMessage (const SBox &box, uint16_t color, const char *message)
{
// prep font
selectFontStyle (BOLD_FONT, FAST_FONT);
tft.setTextColor(color);
// make a copy so we can use maxStringW
int ml = strlen(message);
char msg_cpy[ml+1];
strcpy (msg_cpy, message);
uint16_t msgw = maxStringW (msg_cpy, box.w-2);
// draw centered
resetWatchdog();
tft.fillRect (box.x, box.y, box.w+1, box.h-1, RA8875_BLACK);
tft.setCursor (box.x+(box.w-msgw)/2, box.y+box.h/2-FONTH);
tft.print(msg_cpy);
// check for up to one more line
int cl = strlen (msg_cpy);
if (cl < ml) {
strcpy (msg_cpy, message+cl);
msgw = maxStringW (msg_cpy, box.w-2);
tft.setCursor (box.x+(box.w-msgw)/2, box.y+box.h/2+2);
tft.print(msg_cpy);
}
}
/* given min and max and an approximate number of divisions desired,
* fill in ticks[] with nicely spaced values and return how many.
* N.B. return value, and hence number of entries to ticks[], might be as
* much as 2 more than numdiv.
*/
static int
tickmarks (float min, float max, int numdiv, float ticks[])
{
static int factor[] = { 1, 2, 5 };
# define NFACTOR (sizeof(factor)/sizeof(factor[0]))
float minscale;
float delta;
float lo;
float v;
int n;
minscale = fabs(max - min);
if (minscale == 0) {
/* null range: return ticks in range min-1 .. min+1 */
for (n = 0; n < numdiv; n++)
ticks[n] = min - 1.0 + n*2.0/numdiv;
return (numdiv);
}
delta = minscale/numdiv;
for (n=0; n < (int)NFACTOR; n++) {
float scale;
float x = delta/factor[n];
if ((scale = (powf(10.0F, ceilf(log10f(x)))*factor[n])) < minscale)
minscale = scale;
}
delta = minscale;
lo = floor(min/delta);
for (n = 0; (v = delta*(lo+n)) < max+delta; )
ticks[n++] = v;
return (n);
}
| true |
9652d7a4cf8b4c4b63f686e9ca831bb516c91ee4 | C++ | deanlee-practice/Sprint4---C-Programing | /BankingSystem/Bank_7/BankingSystem.h | UHC | 663 | 2.671875 | 3 | [] | no_license | #pragma once
#include <iostream>
#include <string>
#pragma warning(disable:4996)
#include "Account.h"
using namespace std;
class BankingSystem {
// ü 迭 : Ҵ
Account* accList[100];
int accNum;// = 0; // ʱⰪ
public:
BankingSystem(); // ϰ, ؿ ۼ
void showMenu() const; //
void makeAccount(); // °
void makeNormalAccount();
void makeHighAccount();
void depositMoney(); // Աó
void withdrawMoney(); // ó
void showAllAccount() const; // ü ܾȸ
~BankingSystem();
}; | true |
b39efbfec848fadf9abc32bd1d827a29e95caa21 | C++ | wangqian1992511/LeetCode | /367 Valid Perfect Square/001.cpp | UTF-8 | 174 | 2.765625 | 3 | [] | no_license | class Solution {
public:
bool isPerfectSquare(int num) {
if (num < 0) return false;
double x = sqrt(num);
return int(x) * int(x) == num;
}
};
| true |
57f4994d6183abfcec0d55c36177bdb4e6767daa | C++ | KyungminYu/Algorithm | /BOJ/6588 골드바흐의 추측.cpp | UTF-8 | 725 | 2.953125 | 3 | [] | no_license | #include <stdio.h>
#include <vector>
using namespace std;
vector<int> primeSet;
int prime[1000001];
int main(){
for(int i = 2; i <= 1000000; i++) prime[i] = 1;
for(int i = 2; i <= 1000000; i++){
if(prime[i]){
for(int j = i * 2; j <= 1000000; j += i)
prime[j] = 0;
primeSet.push_back(i);
}
}
while(1){
int n, i; scanf("%d", &n);
if(n == 0) break;
for(i = 0; primeSet[i] <= n; i++){
if(prime[n - primeSet[i]]){
printf("%d = %d + %d\n", n, primeSet[i], n - primeSet[i]);
break;
}
}
if(i == n) printf("Goldbach's conjecture is wrong.\n");
}
return 0;
} | true |
543fa2cfee66e4699f57cc945b14652c63d804ac | C++ | ChemicalWonders/CS14 | /lab03/lab03_4.cpp | UTF-8 | 609 | 3.578125 | 4 | [] | no_license | // Name: Kevin Chan
// CS 14 Lab Section: Tue 8:10AM - 11:00AM
// Problem # 5: Circular Linked List
#include <iostream>
#include <list>
#include <vector>
using namespace std;
int main(){
list<int> A;
A.push_back(1);
A.push_back(2);
A.push_back(3);
A.push_back(5);
//A.end() = A.begin();
for (list<int>::iterator f = A.begin(); f != A.end(); ++f){
if(A.end() == A.begin()){
cout << "LIST IS CIRCULAR! EXITING NOW!" << endl;
exit(1);
}
}
cout << "List is not circular! Returning to main program" << endl;
return 0;
}
| true |
fbc368368ca5a0a3540d241b8f7e23bb30c120f9 | C++ | rkkautsar/cp-solutions | /TOKILearning/v1/1C/toki1c10.cpp | UTF-8 | 375 | 2.984375 | 3 | [
"MIT"
] | permissive | #include <iostream>
#include <cmath>
using namespace std;
int jmlfaktor(long n) {
int jf=0;
int s=trunc(sqrt(n));
if (s*s==n) jf++;
else if (n%s==0) jf+=2;
for(int j=1;j<trunc(sqrt(n));j++) if(!(n%j)) jf+=2;
return jf;
}
int main(){
int n;
long x;
cin>>n;
for(int i=0;i<n;i++){
cin>>x;
if(jmlfaktor(x)<5) cout<<"YA\n";
else cout<<"TIDAK\n";
}
return 0;
}
| true |
ac63287223fb4a31426bbdbb0db748daff85b884 | C++ | iTakeshi/ecell4 | /bd/BDWorld.hpp | UTF-8 | 5,772 | 2.546875 | 3 | [] | no_license | #ifndef __ECELL4_BD_BD_WORLD_HPP
#define __ECELL4_BD_BD_WORLD_HPP
#include <boost/scoped_ptr.hpp>
#include <boost/shared_ptr.hpp>
#include <ecell4/core/extras.hpp>
#include <ecell4/core/RandomNumberGenerator.hpp>
#include <ecell4/core/SerialIDGenerator.hpp>
#include <ecell4/core/ParticleSpace.hpp>
namespace ecell4
{
namespace bd
{
struct MoleculeInfo
{
const Real radius;
const Real D;
};
class BDWorld
{
public:
typedef MoleculeInfo molecule_info_type;
typedef ParticleSpace::particle_container_type particle_container_type;
public:
BDWorld(
const Position3& edge_lengths,
boost::shared_ptr<RandomNumberGenerator> rng)
: ps_(new ParticleSpaceVectorImpl(edge_lengths)), rng_(rng)
{
;
}
BDWorld(const Position3& edge_lengths)
: ps_(new ParticleSpaceVectorImpl(edge_lengths))
{
rng_ = boost::shared_ptr<RandomNumberGenerator>(
new GSLRandomNumberGenerator());
(*rng_).seed();
}
/**
* create and add a new particle
* @param p a particle
* @return pid a particle id
*/
ParticleID new_particle(const Particle& p)
{
ParticleID pid(pidgen_());
// if (has_particle(pid))
// {
// throw AlreadyExists("particle already exists");
// }
(*ps_).update_particle(pid, p);
return pid;
}
/**
* draw attributes of species and return it as a molecule info.
* @param sp a species
* @return info a molecule info
*/
MoleculeInfo get_molecule_info(const Species& sp) const
{
const Real radius(std::atof(sp.get_attribute("radius").c_str()));
const Real D(std::atof(sp.get_attribute("D").c_str()));
MoleculeInfo info = {radius, D};
return info;
}
// SpaceTraits
const Real& t() const
{
return (*ps_).t();
}
void set_t(const Real& t)
{
(*ps_).set_t(t);
}
// ParticleSpaceTraits
const Position3& edge_lengths() const
{
return (*ps_).edge_lengths();
}
Integer num_particles() const
{
return (*ps_).num_particles();
}
Integer num_particles(const Species& species) const
{
return (*ps_).num_particles(species);
}
bool has_particle(const ParticleID& pid) const
{
return (*ps_).has_particle(pid);
}
std::vector<std::pair<ParticleID, Particle> > list_particles() const
{
return (*ps_).list_particles();
}
std::vector<std::pair<ParticleID, Particle> >
list_particles(const Species& species) const
{
return (*ps_).list_particles(species);
}
// ParticleSpace member functions
bool update_particle(const ParticleID& pid, const Particle& p)
{
return (*ps_).update_particle(pid, p);
}
std::pair<ParticleID, Particle>
get_particle(const ParticleID& pid) const
{
return (*ps_).get_particle(pid);
}
void remove_particle(const ParticleID& pid)
{
(*ps_).remove_particle(pid);
}
std::vector<std::pair<std::pair<ParticleID, Particle>, Real> >
list_particles_within_radius(
const Position3& pos, const Real& radius) const
{
return (*ps_).list_particles_within_radius(pos, radius);
}
std::vector<std::pair<std::pair<ParticleID, Particle>, Real> >
list_particles_within_radius(
const Position3& pos, const Real& radius, const ParticleID& ignore) const
{
return (*ps_).list_particles_within_radius(pos, radius, ignore);
}
std::vector<std::pair<std::pair<ParticleID, Particle>, Real> >
list_particles_within_radius(
const Position3& pos, const Real& radius,
const ParticleID& ignore1, const ParticleID& ignore2) const
{
return (*ps_).list_particles_within_radius(pos, radius, ignore1, ignore2);
}
inline Position3 periodic_transpose(
const Position3& pos1, const Position3& pos2) const
{
return (*ps_).periodic_transpose(pos1, pos2);
}
inline Position3 apply_boundary(const Position3& pos) const
{
return (*ps_).apply_boundary(pos);
}
inline Real distance_sq(const Position3& pos1, const Position3& pos2) const
{
return (*ps_).distance_sq(pos1, pos2);
}
inline Real distance(const Position3& pos1, const Position3& pos2) const
{
return (*ps_).distance(pos1, pos2);
}
// CompartmentSpaceTraits
Integer num_molecules(const Species& sp) const
{
return num_particles(sp);
}
void add_molecules(const Species& sp, const Integer& num)
{
extras::throw_in_particles(*this, sp, num, *rng());
}
// Optional members
inline boost::shared_ptr<RandomNumberGenerator> rng()
{
return rng_;
}
const particle_container_type& particles() const
{
return (*ps_).particles();
}
void save(const std::string& filename) const
{
boost::scoped_ptr<H5::H5File>
fout(new H5::H5File(filename, H5F_ACC_TRUNC));
std::ostringstream ost_hdf5path;
ost_hdf5path << "/" << t();
boost::scoped_ptr<H5::Group> parent_group(
new H5::Group(fout->createGroup(ost_hdf5path.str())));
rng_->save(fout.get(), ost_hdf5path.str());
ost_hdf5path << "/ParticleSpace";
boost::scoped_ptr<H5::Group>
group(new H5::Group(parent_group->createGroup(ost_hdf5path.str())));
ps_->save(fout.get(), ost_hdf5path.str());
}
protected:
boost::scoped_ptr<ParticleSpace> ps_;
boost::shared_ptr<RandomNumberGenerator> rng_;
SerialIDGenerator<ParticleID> pidgen_;
};
} // bd
} // ecell4
#endif /* __ECELL4_BD_BD_WORLD_HPP */
| true |
715cd436fa5e6a85f4a5ac0c61950ae05adee462 | C++ | jack5661/SDL_ChasetheSpiders | /TitleCard.cpp | UTF-8 | 1,943 | 2.921875 | 3 | [] | no_license | #include "TitleCard.h"
TitleCard::TitleCard(SDL_Renderer* renderer, SDL_Texture* font) {
fontTexture = font;
this->renderer = renderer;
if (!ReadOldScores()) {
scoreBoard[0] = 0;
scoreBoard[1] = 0;
scoreBoard[2] = 0;
}
}
TitleCard::~TitleCard() {
}
bool TitleCard::ReadOldScores() {
scoreFile = new std::fstream("scores.txt", std::ios::in | std::ios::out);
int data;
if (scoreFile->is_open()) {
int i;
for (i = 0; (*scoreFile) >> data; i++) {
scoreBoard[i] = data;
}
while (i < MAX_SCORES) {
scoreBoard[i++] = 0;
}
}
else {
printf("Could not open file\n");
return false;
}
}
void TitleCard::UpdateScoreBoard() {
int temp = scoreBoard[0];
scoreBoard[0] = score;
scoreBoard[2] = scoreBoard[1];
scoreBoard[1] = temp;
}
void TitleCard::WriteScoresToFile() {
scoreFile->clear();
scoreFile->seekg(0, std::ios::beg);
(*scoreFile) << scoreBoard[0] << ' ' << scoreBoard[1] << ' ' << scoreBoard[2] << std::endl;
if ((scoreFile->rdstate() & std::ifstream::failbit) != 0)
std::cerr << "Error opening 'test.txt'\n";
scoreFile->close();
delete scoreFile;
}
void TitleCard::DisplayBoard() {
char buf[15];
size_t bufSize = sizeof(buf);
TextureLoader::RenderText(renderer, fontTexture, HIGHSCORE_X, HIGHSCORE_Y, "SCORES");
sprintf_s(buf, bufSize, "1... #%d", scoreBoard[0]);
TextureLoader::RenderText(renderer, fontTexture, HIGHSCORE_X, HIGHSCORE_Y + TextureLoader::CHAR_HEIGHT, buf);
sprintf_s(buf, bufSize, "2... #%d", scoreBoard[1]);
TextureLoader::RenderText(renderer, fontTexture, HIGHSCORE_X, HIGHSCORE_Y + 2 * TextureLoader::CHAR_HEIGHT, buf);
sprintf_s(buf, bufSize, "3... #%d", scoreBoard[2]);
TextureLoader::RenderText(renderer, fontTexture, HIGHSCORE_X, HIGHSCORE_Y + 3 * TextureLoader::CHAR_HEIGHT, buf);
TextureLoader::RenderText(renderer, fontTexture, HIGHSCORE_X - 4 * TextureLoader::CHAR_WIDTH,
HIGHSCORE_Y + 5 * TextureLoader::CHAR_HEIGHT, "PRESS SPACE TO EXIT");
}
| true |
60f1ee0888b1ca7071e4d5127d31ccfea76af98d | C++ | propah/AgeOfWar | /Entity.cpp | UTF-8 | 4,664 | 2.640625 | 3 | [] | no_license | #include "Entity.h"
Resources<Texture, int> Entity::textures;
void Entity::initVariables()
{
}
void Entity::initSprites()
{
int texture_id = this->type;
this->e_sprite.setTexture(Entity::textures.get(texture_id));
this->e_sprite.setScale(0.5f, 0.5f);
}
void Entity::initTextures() {
textures.load(1, "r_graphics/clubman.png");
}
Entity::Entity(const vector<float>& f_atri, const vector<Vector2i>& frame_sizes,const int type, const int side, const Vector2f& spawn_pos)
{
//floats
this->health = f_atri[0];
this->dmg_melee = f_atri[1];
this->dmg_ranged = f_atri[2];
this->speed = f_atri[3];
this->attack_speed = f_atri[4];
this->range = f_atri[5];
this->frame_count_atk = static_cast<unsigned int>(f_atri[6]);
this->frame_count_walk = static_cast<unsigned int>(f_atri[7]);
this->frame_count_stand = static_cast<unsigned int>(f_atri[8]);
//Frame sizes
this->size_per_frame_atk = frame_sizes[0];
this->size_per_frame_walk = frame_sizes[1];
this->size_per_frame_stand = frame_sizes[2];
//Int
this->type = type;
this->side = side;
//State
this->is_in_attack_range = false;
this->is_attaking = false;
this->is_walking = false;
this->is_standing = false;
//Spawn position
this->e_pos = spawn_pos;
this->initTextures();
this->initSprites();
this->initVariables();
}
Entity::~Entity()
{
}
Vector2f Entity::getPosition()
{
return this->e_pos;
}
void Entity::updateStates(float dt)
{
if (Keyboard::isKeyPressed(Keyboard::A)) {
this->is_attaking = true;
this->is_walking = false;
}
if (Keyboard::isKeyPressed(Keyboard::W)) {
this->is_attaking = false;
this->is_walking = true;
}
if (Keyboard::isKeyPressed(Keyboard::S)) {
this->is_attaking = false;
this->is_walking = false;
this->is_standing = true;
}
}
void Entity::updateAnimation(float dt)
{
if (this->is_attaking) {
this->frame_index_walk = 0;
this->frame_index_stand = 0;
if (anim_last_atk.getElapsedTime().asSeconds()>(dt*7/this->attack_speed)) {
this->frame_index_atk++;
if (this->frame_index_atk >= this->frame_count_atk) {
this->frame_index_atk = 0;
//this->is_attaking = false;
}
this->anim_last_atk.restart();
}
this->e_sprite.setTextureRect(IntRect(this->frame_index_atk * this->size_per_frame_atk.x, 0,
this->size_per_frame_atk.x, this->size_per_frame_atk.y));
this->e_sprite.setOrigin(Vector2f(this->size_per_frame_atk.x / 2, this->size_per_frame_atk.y / 2));
return;
}
if (this->is_walking) {
this->frame_index_atk = 0;
this->frame_index_stand = 0;
if (this->anim_last_walk.getElapsedTime().asSeconds()>=dt*7) {
this->frame_index_walk++;
if (this->frame_index_walk >= this->frame_count_walk) {
this->frame_index_walk = 0;
//this->is_attaking = false;
}
this->anim_last_walk.restart();
}
this->e_sprite.setTextureRect(IntRect(this->frame_index_walk * this->size_per_frame_walk.x, this->size_per_frame_atk.y,
this->size_per_frame_walk.x, this->size_per_frame_walk.y));
this->e_sprite.setOrigin(Vector2f(this->size_per_frame_walk.x / 2, this->size_per_frame_walk.y / 2));
return;
}
this->frame_index_atk = 0;
this->frame_index_walk = 0;
if (this->anim_last_stand.getElapsedTime().asSeconds()>=dt*6) {
this->frame_index_stand++;
if (this->frame_index_stand >= this->frame_count_stand) {
this->frame_index_stand = 0;
//this->is_attaking = false;
}
this->anim_last_stand.restart();
}
this->e_sprite.setTextureRect(IntRect(this->frame_index_stand * this->size_per_frame_stand.x, this->size_per_frame_atk.y+this->size_per_frame_stand.y+1,
this->size_per_frame_stand.x, this->size_per_frame_stand.y));
this->e_sprite.setOrigin(Vector2f(this->size_per_frame_stand.x / 2, this->size_per_frame_stand.y / 2));
}
void Entity::updatePosition(float dt)
{
if (this->is_walking) {
this->e_pos.x += 50 * dt;
}
this->e_sprite.setPosition(this->e_pos);
}
void Entity::update(float dt)
{
this->updateStates(dt);
this->updatePosition(dt);
this->updateAnimation(dt);
}
void Entity::render(RenderTarget* target)
{
target->draw(this->e_sprite);
}
| true |
6e49100d6e085719fcf0a164f3d5122cea479be3 | C++ | CASC-Lang/CAScript-Native | /include/binding/BoundBinaryOperator.h | UTF-8 | 4,065 | 2.984375 | 3 | [] | no_license | //
// Created by ChAoS-UnItY on 8/12/2021.
//
#ifndef COLLAGE_CPP_BOUNDBINARYOPERATOR_H
#define COLLAGE_CPP_BOUNDBINARYOPERATOR_H
#include "syntax/TokenType.h"
#include "BinaryOperatorType.h"
#include "Type.h"
namespace cascript::binding {
struct BoundBinaryOperator {
public:
syntax::TokenType type;
BinaryOperatorType operator_type{};
Type left_type;
Type right_type;
Type result_type;
BoundBinaryOperator(syntax::TokenType type, BinaryOperatorType operator_type, Type io_type) :
type(type), operator_type(operator_type), left_type(io_type),
right_type(io_type), result_type(io_type) {};
BoundBinaryOperator(syntax::TokenType type, BinaryOperatorType operator_type, Type io_type, Type result_type) :
type(type), operator_type(operator_type), left_type(io_type),
right_type(io_type), result_type(result_type) {};
};
static const BoundBinaryOperator binary_ops[] = {
BoundBinaryOperator(syntax::TokenType::Plus, BinaryOperatorType::Addition, Type::Number),
BoundBinaryOperator(syntax::TokenType::Minus, BinaryOperatorType::Minus, Type::Number),
BoundBinaryOperator(syntax::TokenType::Star, BinaryOperatorType::Multiplication, Type::Number),
BoundBinaryOperator(syntax::TokenType::DoubleStar, BinaryOperatorType::Exponent, Type::Number),
BoundBinaryOperator(syntax::TokenType::Slash, BinaryOperatorType::Division, Type::Number),
BoundBinaryOperator(syntax::TokenType::DoubleSlash, BinaryOperatorType::FloorDivision, Type::Number),
BoundBinaryOperator(syntax::TokenType::Percent, BinaryOperatorType::Modulus, Type::Number),
BoundBinaryOperator(syntax::TokenType::DoubleEqual, BinaryOperatorType::Equal, Type::Number, Type::Bool),
BoundBinaryOperator(syntax::TokenType::DoubleEqual, BinaryOperatorType::Equal, Type::Bool),
BoundBinaryOperator(syntax::TokenType::BangEqual, BinaryOperatorType::NotEqual, Type::Number, Type::Bool),
BoundBinaryOperator(syntax::TokenType::BangEqual, BinaryOperatorType::NotEqual, Type::Bool),
BoundBinaryOperator(syntax::TokenType::DoubleGreaterThan, BinaryOperatorType::RightShift, Type::Number),
BoundBinaryOperator(syntax::TokenType::TripleGreaterThan, BinaryOperatorType::UnsignedRightShift, Type::Number),
BoundBinaryOperator(syntax::TokenType::DoubleLessThan, BinaryOperatorType::LeftShift, Type::Number),
BoundBinaryOperator(syntax::TokenType::Ampersand, BinaryOperatorType::BitwiseAnd, Type::Number),
BoundBinaryOperator(syntax::TokenType::Caret, BinaryOperatorType::BitwiseExclusiveOr, Type::Number),
BoundBinaryOperator(syntax::TokenType::Pipe, BinaryOperatorType::BitwiseInclusiveOr, Type::Number),
BoundBinaryOperator(syntax::TokenType::DoubleAmpersand, BinaryOperatorType::LogicalAnd, Type::Bool),
BoundBinaryOperator(syntax::TokenType::DoublePipe, BinaryOperatorType::LogicalOr, Type::Bool),
BoundBinaryOperator(syntax::TokenType::GreaterThan, BinaryOperatorType::Greater, Type::Number, Type::Bool),
BoundBinaryOperator(syntax::TokenType::GreaterEqualThan, BinaryOperatorType::GreaterEqual, Type::Number, Type::Bool),
BoundBinaryOperator(syntax::TokenType::LessThan, BinaryOperatorType::Less, Type::Number, Type::Bool),
BoundBinaryOperator(syntax::TokenType::LessEqualThan, BinaryOperatorType::LessEqual, Type::Number, Type::Bool),
BoundBinaryOperator(syntax::TokenType::LessEqualGreater, BinaryOperatorType::ThreeWayComparison, Type::Number),
};
static const BoundBinaryOperator *bind(syntax::TokenType type, Type left_type, Type right_type) {
for (const auto &op : binary_ops)
if (op.type == type && op.left_type == left_type && op.right_type == right_type)
return &op;
return nullptr;
}
}
#endif //COLLAGE_CPP_BOUNDBINARYOPERATOR_H
| true |
863f8237ded793e49ff700042ea55471ae9a3bcf | C++ | keremdayi/experiments | /list-alternative/main.cpp | UTF-8 | 329 | 2.859375 | 3 | [] | no_license | #include <iostream>
#include "List.h"
using namespace std;
int main(){
List<int> myList;
myList.append(4);
myList.append(3);
myList.append(5);
myList.append(1);
myList.append(6);
myList[1] = 0;
cout<<myList.size()<<endl;
for(int i = 0; i < myList.size(); i++) cout<<myList[i]<<" ";
} | true |
df30b9f23daa80505c786587121059f1447eef7a | C++ | devnguy/nova | /src/Augment.cpp | UTF-8 | 907 | 2.921875 | 3 | [] | no_license | /*******************************************************************************
** Description: Implementation of Augment base class.
*******************************************************************************/
#include <iostream>
#include <string>
#include "Item.hpp"
#include "Augment.hpp"
#include "constants.hpp"
using std::cout;
using std::endl;
/**
* Default constructor with no ID.
*/
Augment::Augment()
{
}
/**
* Overloaded constructor initializes spaceID.
*/
Augment::Augment
( int itemID, std::string name, int modifierHealth
, int modifierAttack, int modiferDefense, int modifierArmor
, int modifierInitiative, int modifierCrit
)
: Item(itemID, name, modifierHealth, modifierAttack
, modiferDefense, modifierArmor, modifierInitiative, modifierCrit)
{
}
/**
* Setter functions.
*/
/**
* Getter functions.
*/
/**
* Destructor.
*/
Augment::~Augment()
{
} | true |
2a3d631989fcbf4768440986710c6b1a39aeb785 | C++ | skyformat99/ccinfra | /test/TestPlainTransData.cpp | UTF-8 | 4,962 | 3.15625 | 3 | [] | no_license | #include "gtest/gtest.h"
#include <ccinfra/mem/PlainTransData.h>
namespace
{
struct Foo
{
int a, b;
};
}
struct PlainTransDataTest : testing::Test
{
protected:
virtual void SetUp()
{
foo.a = 10;
foo.b = 20;
}
const int* getConstPointer() const
{
return intData.operator->();
}
const int& getConstReference() const
{
return *intData;
}
void enableModifiable()
{
intData.update(10);
intData.confirm();
intData.modify();
}
protected:
PlainTransData<int> intData;
PlainTransData<Foo> fooData;
Foo foo;
};
TEST_F(PlainTransDataTest, an_uninitialized_trans_data_should_be_invalid)
{
ASSERT_FALSE(intData.isPresent());
}
TEST_F(PlainTransDataTest, an_uninitialized_trans_data_should_be_null_if_accessed_by_pointer)
{
ASSERT_TRUE(0 == intData.operator->());
}
TEST_F(PlainTransDataTest, an_uninitialized_trans_data_should_be_null_if_accessed_by_a_constant_pointer)
{
ASSERT_TRUE(0 == getConstPointer());
}
TEST_F(PlainTransDataTest, once_set_value_it_should_become_valid)
{
intData.update(10);
ASSERT_TRUE(intData.isPresent());
}
TEST_F(PlainTransDataTest, once_set_value_it_should_be_able_to_be_accessed_by_reference)
{
intData.update(10);
ASSERT_TRUE(10 == getConstReference());
}
TEST_F(PlainTransDataTest, if_revert_a_updated_value_should_become_invalid)
{
intData.update(10);
intData.revert();
ASSERT_FALSE(intData.isPresent());
}
TEST_F(PlainTransDataTest, before_a_updated_value_is_confirmed_if_it_reverted_should_become_invalid_again)
{
intData.update(10);
intData.update(20);
intData.revert();
ASSERT_FALSE(intData.isPresent());
}
TEST_F(PlainTransDataTest, once_a_updated_value_is_confirmed_it_should_will_become_valid)
{
intData.update(10);
intData.confirm();
ASSERT_TRUE(intData.isPresent());
}
TEST_F(PlainTransDataTest, a_confirmed_value_can_not_be_reverted)
{
intData.update(10);
intData.confirm();
intData.revert();
ASSERT_TRUE(intData.isPresent());
ASSERT_TRUE(10 == (*intData));
}
TEST_F(PlainTransDataTest, a_confirmed_value_can_be_updated_again)
{
intData.update(10);
intData.confirm();
intData.update(20);
ASSERT_TRUE(intData.isPresent());
ASSERT_TRUE(20 == (*intData));
}
TEST_F(PlainTransDataTest, if_a_confirmed_value_is_updated_again_then_reverting_should_be_able_to_rollback)
{
intData.update(10);
intData.confirm();
intData.update(20);
intData.revert();
ASSERT_TRUE(intData.isPresent());
ASSERT_TRUE(10 == (*intData));
}
TEST_F(PlainTransDataTest, once_a_confirmed_value_is_reset_it_should_become_invalid)
{
intData.update(10);
intData.confirm();
intData.reset();
ASSERT_FALSE(intData.isPresent());
}
TEST_F(PlainTransDataTest, an_unstable_data_should_not_be_able_to_be_modified)
{
intData.update(10);
ASSERT_NE(CCINFRA_SUCCESS, intData.modify());
}
TEST_F(PlainTransDataTest, a_stable_data_should_be_able_to_be_modified)
{
intData.update(10);
intData.confirm();
ASSERT_EQ(CCINFRA_SUCCESS, intData.modify());
}
TEST_F(PlainTransDataTest, after_clone_for_modification_it_is_value_keep_unchanged)
{
enableModifiable();
ASSERT_EQ(10, *intData);
}
TEST_F(PlainTransDataTest, after_clone_for_modification_should_be_able_modify_actually)
{
enableModifiable();
(*intData) = 20;
ASSERT_EQ(20, *intData);
}
TEST_F(PlainTransDataTest, after_modification_if_revert_should_roll_back)
{
enableModifiable();
(*intData) = 20;
intData.revert();
ASSERT_EQ(10, *intData);
}
TEST_F(PlainTransDataTest, for_an_uninitialized_trans_data_its_old_value_should_be_invalid)
{
ASSERT_FALSE(fooData.isOldPresent());
}
TEST_F(PlainTransDataTest, for_an_initialized_trans_data_its_old_value_is_still_be_invalid)
{
fooData.update(foo);
ASSERT_FALSE(fooData.isOldPresent());
}
TEST_F(PlainTransDataTest, for_an_initialized_PlainTransData_after_confirmation_its_old_value_is_still_be_invalid)
{
fooData.update(foo);
fooData.confirm();
ASSERT_FALSE(fooData.isOldPresent());
}
TEST_F(PlainTransDataTest, after_confirmation_if_update_again_its_old_value_should_be_valid)
{
fooData.update(foo);
fooData.confirm();
foo.a = 1;
foo.b = 2;
fooData.update(foo);
ASSERT_TRUE(fooData.isOldPresent());
}
TEST_F(PlainTransDataTest, after_confirmation_if_update_again_its_old_value_should_be_the_previous_one)
{
fooData.update(foo);
fooData.confirm();
foo.a = 1;
foo.b = 2;
fooData.update(foo);
ASSERT_EQ(10, fooData.getOldValue().a);
ASSERT_EQ(20, fooData.getOldValue().b);
}
TEST_F(PlainTransDataTest, after_confirmation_if_update_again_its_new_value_should_be_the_new_one)
{
fooData.update(foo);
fooData.confirm();
foo.a = 1;
foo.b = 2;
fooData.update(foo);
ASSERT_EQ(1, fooData->a);
ASSERT_EQ(2, fooData->b);
}
| true |
47603cb849fc82da9b8d081785513f90dce19073 | C++ | ccanete/tpheritage | /src/Models/Figure.cpp | ISO-8859-1 | 2,174 | 2.65625 | 3 | [] | no_license | /*************************************************************************
Figure - description
-------------------
dbut : 21/01/2015
copyright : (C) 2015 par Accardo & Canete
*************************************************************************/
//---------- Interface de la classe <Figure> (fichier Figure.cpp) ------
//---------------------------------------------------------------- INCLUDE
//-------------------------------------------------------- Include systme
#include <iostream>
using namespace std;
//------------------------------------------------------ Include personnel
#include "Figure.h"
//------------------------------------------------------------- Constantes
//---------------------------------------------------- Variables de classe
//----------------------------------------------------------- Types privs
//----------------------------------------------------------------- PUBLIC
//-------------------------------------------------------- Fonctions amies
//----------------------------------------------------- Mthodes publiques
// type Figure::Mthode ( liste de paramtres )
// Algorithme :
//
//{
//} //----- Fin de Mthode
string Figure::GetName()
// Algorithme :
//
{
return name;
}
//----- Fin de Mthode
//------------------------------------------------- Surcharge d'oprateurs
bool Figure::operator < ( const Figure &f )
// Algorithme :
//
{
return name > f.name;
} //----- Fin de operator =
//-------------------------------------------- Constructeurs - destructeur
Figure::Figure ( string name )
// Algorithme :
//
{
this->name = name;
#ifdef MAP
cout << "Appel au constructeur de <Figure>" << endl;
#endif
} //----- Fin de Figure
Figure::~Figure ( )
// Algorithme :
//
{
#ifdef MAP
cout << "Appel au destructeur de <Figure>" << endl;
#endif
} //----- Fin de ~Figure
//------------------------------------------------------------------ PRIVE
//----------------------------------------------------- Mthodes protges
//------------------------------------------------------- Mthodes prives
| true |
d1dc2d48055c67b4b73a701c363590f9c1035da9 | C++ | spencerwhyte/cuCareClient | /CUPage.cpp | UTF-8 | 3,166 | 2.625 | 3 | [] | no_license | #include"CUPage.h"
CUPage::CUPage(QString title, bool containsBackButton, CUNavigationProvisioningInterface *pNavigator) : QWidget(), backButton(NULL), request(NULL)
{
setMinimumSize(800, 600); // a smaller window would be unusable, a bigger window would be ugly
layout = new QGridLayout(this);
titleLabel = new QLabel(title, this);
contentPane = new CUContentPane(this);
titleLabel->setGeometry(10,10,300,30);
titleLabel->setFont(QFont("Sans Serif", 20, 1));
//change the color of the title
QPalette titlePalette;
titlePalette.setColor(QPalette::WindowText, Qt::darkGray);
titleLabel->setPalette(titlePalette);
//if there is a back button, then assign the layout accordingly
if(containsBackButton)
{
// set the button to have a default back arrow on it
backButton = new CUNavigationButton("",this);
backButton->setIcon(backButton->style()->standardIcon(QStyle::SP_ArrowBack));
backButton->setMaximumWidth(60);
//add the elements to the lay out and align the content pane in the middle
layout->addWidget(titleLabel, 0, 1);
layout->addWidget(backButton, 0, 0);
layout->addWidget(contentPane, 1, 0, 1, 2);
//connect back button to navigator
QObject::connect(backButton, SIGNAL(clicked()), pNavigator, SLOT(back()));
}
else
{
layout->addWidget(titleLabel, 0, 0);
layout->addWidget(contentPane, 1, 0);
}
layout->setAlignment(contentPane, Qt::AlignCenter);
layout->setRowStretch(0, 0); // the title should be stuck up no matter how the screen is resized
layout->setRowStretch(1, 1); // the contents should always be in the center
setLayout(layout);
}
// Never know what you might want to fill into a destructor
CUPage::~CUPage()
{
if(request){
delete request;
}
}
void CUPage::setPageTitle(QString newTitle)
{
titleLabel->setText(newTitle);
}
CUNavigationProvisioningInterface* CUPage::getNavigator()
{
}
void CUPage::setRequest(ClientObjectRequest * r){
if(request){
delete request;
}
request = r;
}
ClientObjectRequest * CUPage::getRequest(){
return request;
}
QGridLayout* CUPage::getLayout()
{
return layout;
}
// setup the title of the page
void CUPage::setTitle(QString title)
{
titleLabel->setText(title);
}
// insert an element at the bottom of the contentpane
void CUPage::addElement(QWidget *element, int xPosition)
{
contentPane->addElement(element, xPosition);
}
// calls the addElement of the content pane of that page, adding an element to the pane itself
void CUPage::addElement(QWidget *element, int xPosition, int yPosition, int xSpan, int ySpan)
{
contentPane->addElement(element, xPosition, yPosition, xSpan, ySpan);
}
// add an element, and specify its alignment
void CUPage::addElement(QWidget *element, int xPosition, int yPosition, int xSpan, int ySpan, Qt::AlignmentFlag alignment)
{
contentPane->addElement(element, xPosition, yPosition, xSpan, ySpan, alignment);
}
void CUPage::addToTable(StorableInterface* object)
{
}
void CUPage::updateTable(StorableInterface *object)
{
}
| true |
ee7ccbc20c591d7e60e30153603dd8be6709309c | C++ | lonelybinary/ESP8266 | /Basic/Digital_Pin/Digital_Pin.ino | UTF-8 | 900 | 2.859375 | 3 | [] | no_license | /***************************************************************************
Written by Taylor for http://lonelybinary.com
BSD license, all text above must be included in any redistribution
***************************************************************************/
//D0 is conncted to GPIO3. you can refer this pin by using D0 or 3 directly.
#define ledpin D0
//#define ledpin 3
// the setup function runs once when you press reset or power the board
void setup() {
// initialize digital pin as an output.
pinMode(ledpin, OUTPUT);
}
// the loop function runs over and over again forever
void loop() {
digitalWrite(ledpin, HIGH); // turn the LED on (HIGH is the voltage level)
delay(500); // wait for half second
digitalWrite(ledpin, LOW); // turn the LED off by making the voltage LOW
delay(500); // wait for half second
}
| true |
2c902294bf1023c05e9c58c32bdfa0310ac16aea | C++ | mehediishere/Competitive-Programming | /C & C++/which point is closest to the center.cpp | UTF-8 | 572 | 3.546875 | 4 | [] | no_license | /*
Time : Around 40 minutes
Problem_11 : Given the coordinate of two points p1(x1,y1) and p2(x2,y2). Find which point is closest to the center (0,0).
*/
#include<stdio.h>
#include<math.h>
int main()
{
double x1, y1, x2, y2, distance1, distance2;
scanf("%lf %lf %lf %lf",&x1, &y1, &x2, &y2);
distance1 = sqrt(pow((x1-0),2)+pow((y1-0),2));
distance2 = sqrt(pow((x2-0),2)+pow((y2-0),2));
if(distance1<distance2)
{
printf("%.0lf %.0lf \n",x1, y1);
}
else
{
printf("%.0lf %.0lf \n",x2, y2);
}
return 0;
}
| true |
8a19720caac68f6a089f2e422b37ce1facb5147c | C++ | MikamiYuto/ReTraining | /Ex01Chapter03/List-Test/IteratorTest.h | SHIFT_JIS | 1,213 | 3.0625 | 3 | [] | no_license | /**
* @file IteratorTest.h
* @breif ev[gCe[^NX̃eXg`t@C
* @author MikamiYuto
* @date 2021.10.13
*/
#pragma once
//----- CN[h
#include "gtest/gtest.h"
#include "../List/List.h"
#include "../List/Iterator.h"
/** Ce[^eXgptBNX`̃x[XNX */
class BaseIteratorTest : public ::testing::Test
{
protected:
/**
* @brief
* @details eeXgڂ̎sOɁAvfXgpӂ
*/
virtual void SetUp()
{
for (int i = 0; i < 3; ++i)
{
for (int j = 0; j < 2; ++j)
{
Iterator<int> itr = m_Lists[i].GetEnd();
m_Lists[i].Insert(itr, j);
}
}
}
protected:
List<int> m_Lists[3]; //!< vfXg(vf2,evf̗͂vfʒulƂĊi[
};
/** Ce[^Xg̖ɌĈi߂鋓eXgptBNX`NX */
class IteratorIncrementTest : public BaseIteratorTest {};
/** Ce[^Xg̐擪ɌĈi߂鋓eXgptBNX`NX */
class IteratorDecrementTest : public BaseIteratorTest {};
| true |
651818e3f8f1ff813cdae4fdc8cd822f84254f01 | C++ | Yang92047111/tutor | /0629/math_operators.cpp | UTF-8 | 572 | 3.203125 | 3 | [] | no_license | #include <iostream>
int main()
{
int a = 21;
int b = 10;
int c ;
c = a + b;
std::cout << "Line 1 - c is : " << c << std::endl;
c = a - b;
std::cout << "Line 2 - c is : " << c << std::endl;
c = a * b;
std::cout << "Line 3 - c is : " << c << std::endl;
c = a / b;
std::cout << "Line 4 - c is : " << c << std::endl;
c = a % b;
std::cout << "Line 5 - c is : " << c <<std::endl;
c = a++;
std::cout << "Line 6 - c is : " << c << std::endl;
c = a--;
std::cout << "Line 7 - c is : " << c << std::endl;
return 0;
} | true |
64ab4653c7524d51c13867d6ab450613b7dbb440 | C++ | brotherb/myleetcode | /Merge Sorted Array.cpp | UTF-8 | 906 | 2.984375 | 3 | [] | no_license | //
// main.cpp
// leet
//
// Created by brotherb on 14-1-11.
// Copyright (c) 2014 brotherb. All rights reserved.
//
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
void merge(int A[], int m, int B[], int n) {
int i = 0;
int j = 0;
while(j < m + i && i < n){
if(B[i] < A[j]){
for (int k = m - 1 + i; k >= j; k--){
A[k+1] = A[k];
}
A[j] = B[i];
i++;
}
j++;
}
while(i < n){
A[j++] = B[i++];
}
}
int main(int argc, const char * argv[])
{
int a[3] ={1,3,5};
int b[1] = {};
merge(a, 3, b, 0);
return 0;
}
| true |