hexsha stringlengths 40 40 | size int64 19 11.4M | ext stringclasses 13 values | lang stringclasses 1 value | max_stars_repo_path stringlengths 3 270 | max_stars_repo_name stringlengths 5 110 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 3 270 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 270 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 9 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 19 11.4M | avg_line_length float64 1.93 229k | max_line_length int64 12 688k | alphanum_fraction float64 0.07 0.99 | matches listlengths 1 10 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
dd0d086ee6b505118f1f7ec80dfc918c78d733d8 | 7,649 | cpp | C++ | src/GLSandbox/GLSandbox.cpp | AlbertoRivadulla/OpenGL-base-library | ca8fac07c91642cdba40a66c99db87073240e449 | [
"MIT"
] | null | null | null | src/GLSandbox/GLSandbox.cpp | AlbertoRivadulla/OpenGL-base-library | ca8fac07c91642cdba40a66c99db87073240e449 | [
"MIT"
] | null | null | null | src/GLSandbox/GLSandbox.cpp | AlbertoRivadulla/OpenGL-base-library | ca8fac07c91642cdba40a66c99db87073240e449 | [
"MIT"
] | null | null | null | #include "GLSandbox.h"
using namespace GLBase;
using namespace GLGeometry;
using namespace GLUtils;
//==============================
// Methods of the GLSandbox class that depend on the scene to render
//==============================
// Setup the scene
// - Create the camera
// - Create/load geometry
// - World
// - Skymap
// - Objects
// - Load shaders
// - Create lights
void GLSandbox::setupScene()
{
// Create the cubemap for the sky
mSkymap = new GLCubemap();
// // Skymap with textures. To use this, comment the constructor without textures
// // in GLCubemap.h and GLCubemap.cpp
// mSkymap = new GLCubemap("../resources/textures/skybox");
// Set the position of the camera
mCamera.Position = glm::vec3(0.f, 0.f, 5.f);
// Create a quad
mElementaryObjects.push_back(new GLQuad());
// Create a cube
mElementaryObjects.push_back(new GLCube());
// Create a cylinder
mElementaryObjects.push_back(new GLCylinder(32));
// Create a sphere
mElementaryObjects.push_back(new GLSphere(16));
// Create a cone
mElementaryObjects.push_back(new GLCone(32));
// Load a shader
mShaders.push_back(Shader("../shaders/vertex.glsl", "../shaders/fragment.glsl"));
// Load a shader for the geometry pass
mGPassShaders.push_back(Shader("../shaders/GLBase/defGeometryPassVertex.glsl",
"../shaders/GLBase/defGeometryPassFragment.glsl"));
// Add some point lights
for (int i = 0; i < 10; ++i)
{
mLights.push_back(new PointLight( {getRandom0To1(), getRandom0To1(), getRandom0To1()},
{10.f * getRandom0To1() - 5.f, 10.f * getRandom0To1() - 2.f, 10.f * getRandom0To1() - 5.f},
0.2f, 0.01f, 0.02f ) );
}
// Add a directional light
mLights.push_back(new DirectionalLight( {1., 1., 1.}, // Color
{10., 10., 10.}, // Position
{-1., -1., -1.}, // Direction
0.5f, 0.f, 0.f) ); // Intensity, attenuation linear, attenuation quadratic
// Add a spotlight
mLights.push_back(new SpotLight( {0., 1., 0.}, // Color
{0., 4., 0.}, // Position
{0., -1., 0.}, // Direction
25.f, 90.f, // Angles
3.f, 0.05f, 0.1f) ); // Intensity, attenuation linear, attenuation quadratic
// Create some materials
mMaterials.push_back(Material( {1., 1., 0.}, 1.0 ));
mMaterials.push_back(Material( {1., 0., 0.}, 1.0 ));
mMaterials.push_back(Material( {0., 0., 1.}, 1.0 ));
mMaterials.push_back(Material( {0., 1., 1.}, 1.0 ));
mMaterials.push_back(Material( {0., 1., 0.}, 0.5 ));
}
// Pass pointers to objects to the application, for the input processing
// Also pass the pointer to the camera
void GLSandbox::setupApplication()
{
// Pass a pointer to the camera
mApplication.setCamera(&mCamera);
// Pass a pointer to the input handler
mApplication.setInputHandler(&mInputHandler);
// // Configure the frustum of the camera
// mCamera.setFrustum(0.1f, 50.f);
// Pass pointers to the input handler of the camera
mInputHandler.addKeyboardHandler(&mCamera.mKeyboardHandler);
mInputHandler.addMouseHandler(&mCamera.mMouseHandler);
mInputHandler.addScrollHandler(&mCamera.mScrollHandler);
// Pass the list of lights to the renderer, to configure the lighting shader
mRenderer.configureLights(mLights);
}
// Method to run on each frame, to update the scene
void GLSandbox::updateScene()
{
// // Set the camera to be orthographic
// mCamera.setOrthographic();
// Get the view and projection matrices
mProjection = mCamera.getProjectionMatrix();
mView = mCamera.getViewMatrix();
// Update the skymap
mSkymap->setViewProjection(mView, mProjection);
// Move the quad
mElementaryObjects[0]->setModelMatrix(glm::vec3(0., -1., 0.), -90., glm::vec3(1.,0.,0.), glm::vec3(15.,15.,15.));
// Move the cube
mElementaryObjects[1]->setModelMatrix(glm::vec3(2.,0.,0.), 0., glm::vec3(1.,0.,0.), glm::vec3(2.,2.,2.));
// Move the cylinder
mElementaryObjects[2]->setModelMatrix({3.,1.,0.}, 0., glm::vec3(1.,0.,0.), glm::vec3(2.,2.,2.));
// Move the sphere
mElementaryObjects[3]->setModelMatrix(glm::vec3(-1.,0.,0.), 0., glm::vec3(1.,0.,0.), glm::vec3(2.,2.,2.));
// Move the cone
mElementaryObjects[4]->setModelMatrix(glm::vec3(-3.,0.,0.), 0., glm::vec3(1.,0.,0.), glm::vec3(2.,2.,2.));
}
// Render the geometry that will use deferred rendering
void GLSandbox::renderDeferred()
{
// Configure the common uniforms in the shaders
mGPassShaders[0].use();
mGPassShaders[0].setMat4("view", mView);
mGPassShaders[0].setMat4("projection", mProjection);
// Draw the quad
mGPassShaders[0].setMat4("model", mElementaryObjects[0]->getModelMatrix());
mMaterials[0].configShader(mGPassShaders[0]);
mElementaryObjects[0]->draw();
// Draw the cube
mGPassShaders[0].setMat4("model", mElementaryObjects[1]->getModelMatrix());
mMaterials[1].configShader(mGPassShaders[0]);
mElementaryObjects[1]->draw();
// Draw the cylinder
mGPassShaders[0].setMat4("model", mElementaryObjects[2]->getModelMatrix());
mMaterials[2].configShader(mGPassShaders[0]);
mElementaryObjects[2]->draw();
// Draw the sphere
mGPassShaders[0].setMat4("model", mElementaryObjects[3]->getModelMatrix());
mMaterials[3].configShader(mGPassShaders[0]);
mElementaryObjects[3]->draw();
// Draw the cone
mGPassShaders[0].setMat4("model", mElementaryObjects[4]->getModelMatrix());
mMaterials[4].configShader(mGPassShaders[0]);
mElementaryObjects[4]->draw();
}
// Render the geometry that will use forward rendering
void GLSandbox::renderForward()
{
// // Draw a point
// mAuxElements.drawPoint(glm::vec3(-0., 0., -5.), mView, mProjection);
// mAuxElements.drawPoint(glm::vec3(2., 1., -1.), mView, mProjection);
// // Draw a line
// mAuxElements.drawLine(glm::vec3(-1, 0., -5.), glm::vec3(2., 1., -1.), mView, mProjection);
// // Draw a parallelepiped
// mAuxElements.drawParallelepiped(glm::vec3(-2., 0., 0.), glm::vec3(1., 0., 0.), glm::vec3(0., 1., 1.),
// mView, mProjection);
// // Draw a rectangle
// mAuxElements.drawRectangle(glm::vec3(-2., 1., 0.), -45., glm::vec3(1., 0., 0.), glm::vec3(1., 2., 1.),
// mView, mProjection);
// // Draw a box
// mAuxElements.drawBox(glm::vec3(2., 1., 0.), -45., glm::vec3(1., 0., 0.), glm::vec3(1., 2., 1.),
// mView, mProjection);
// // Draw a cylinder
// mAuxElements.drawCylinder(glm::vec3(-2., 3., 0.), -45., glm::vec3(1., 0., 0.), glm::vec3(1., 2., 1.),
// mView, mProjection);
// // Draw a sphere
// mAuxElements.drawSphere(glm::vec3(-2., 1., 0.), 0., glm::vec3(1., 0., 0.), glm::vec3(1., 1., 1.),
// mView, mProjection);
// Draw a cone
mAuxElements.drawCone(glm::vec3(-2., 0., 0.), 0., glm::vec3(1., 0., 0.), glm::vec3(1., 1., 1.),
mView, mProjection);
// Draw points in the positions of the lights
for (auto light : mLights)
{
mAuxElements.drawPoint(light->getPosition(), mView, mProjection);
}
}
| 40.04712 | 134 | 0.583736 | [
"geometry",
"render",
"model"
] |
dd19f2bfba0846d31d7eb9b24572a3069059fc73 | 12,195 | cpp | C++ | Previous Contests/IMMC-Grup-main/Core/Tabela.cpp | stOOrz-Mathematical-Modelling-Group/IMMC_2022_Autumn | 4430eec4940055e434d8c6183332fc55601937d2 | [
"MIT"
] | null | null | null | Previous Contests/IMMC-Grup-main/Core/Tabela.cpp | stOOrz-Mathematical-Modelling-Group/IMMC_2022_Autumn | 4430eec4940055e434d8c6183332fc55601937d2 | [
"MIT"
] | null | null | null | Previous Contests/IMMC-Grup-main/Core/Tabela.cpp | stOOrz-Mathematical-Modelling-Group/IMMC_2022_Autumn | 4430eec4940055e434d8c6183332fc55601937d2 | [
"MIT"
] | null | null | null | #include "Tabela.h"
#include "../IO/FileManager.h"
const string Tabela::REPORT_PREFIX = "select_";
const string Tabela::REPORT_EXTENSION = ".txt";
Tabela::Tabela(const char *numeTabela, int id, vector<Celula*> celule) : ID_TABELA(id)
{
strcpy(this->numeTabela, numeTabela);
this->celule = celule;
}
//operatorul =
Tabela& Tabela::operator=(const Tabela& t)
{
strcpy(this->numeTabela, t.numeTabela);
this->celule = t.celule;
return *this;
}
Tabela::~Tabela()
{
}
//setterii si getteri
void Tabela::addRecord(vector<string> values)//delimitatorul e constant, virgula spatiu -> ", "
{
size_t len = values.size();
string tmp = "Eroare in sintaxa comenzii INSERT! -> numarul valorilor nu corespunde numarul campurilor tabelului ";
tmp += numeTabela;
if (len != celule.size())throw Exception(tmp.c_str());
vector<DataCelula*> dataValues;
for (size_t i = 0; i < len; ++i)
{
string val = values.at(i);
DataCelula *dataCelula;
if (celule.at(i)->getTipCelula() == TipCelula::NUMBER)
{
if (!is_number(val))
{
tmp = "Eroare in sintaxa comenzii INSERT! -> tipurile valorilor nu corespund tipurilor campurilor tabelului ";
tmp += numeTabela;
throw Exception(tmp.c_str());
}
double *tempVal = new double;
*tempVal = atof(val.c_str());
void * tempVoidVal = (void*)tempVal;
dataCelula = new DataCelula(TipCelula::NUMBER, tempVoidVal);
}
else
{
string *tempVal = new string;
*tempVal = val;
void * tempVoidVal = (void*)tempVal;
dataCelula = new DataCelula(TipCelula::TEXT, tempVoidVal);
}
dataValues.push_back(dataCelula);
}
inregistrari.push_back(new Inregistrare(dataValues));
cout << "Inserarea in tabelul " << numeTabela << " a fost efectuata cu succes. ID: " << inregistrari.size() - 1 << endl;
FileManager::serializeTable(numeTabela, getSerialisedTable());
TableReport::log("Metoda addRecord(vector<string> values)", "S-a inserat o noua inregistrare in tabelul " + string(numeTabela) + " ID: " + to_string(inregistrari.size() - 1));
}
void Tabela::deleteAtIndex(size_t index)
{
celule.erase(celule.begin() + index);
TableReport::log("Metoda deleteAtIndex(size_t index)", "S-a sters o celula din tabelul " + string(numeTabela) + " la indexul: " + to_string(index));
}
void Tabela::setAtIndex(size_t index, Celula *c)
{
celule.at(index) = c;
TableReport::log("Metoda setAtIndex(size_t index, Celula *c)", "S-a modificat o celula din " + string(numeTabela) + " la indexul: " + to_string(index));
}
char* Tabela::getNumeTabela()
{
return numeTabela;
}
Celula* Tabela::getCelulaAtIndex(size_t index)
{
return celule.at(index);
}
Celula* Tabela::getCelulaByName(string name)
{
size_t len = celule.size();
for (size_t i = 0; i < len; ++i)
{
if (!celule.at(i)->getNume().compare(name))
{
return celule.at(i);
}
}
return nullptr;
}
TipCelula Tabela::getTipCelulaByName(string name)
{
size_t len = celule.size();
for (size_t i = 0; i < len; ++i)
{
if (!celule.at(i)->getNume().compare(name))
{
return celule.at(i)->getTipCelula();
}
}
return TipCelula::TEXT;
}
bool Tabela::checkForCelula(string name)
{
size_t len = celule.size();
for (size_t i = 0; i < len; ++i)
{
if (!celule.at(i)->getNume().compare(name))
{
return true;
}
}
return false;
}
void Tabela::deleteRecords(string celula, string value)
{
size_t len = celule.size(), index;
TipCelula tipCelula;
for (size_t i = 0; i < len; ++i)
{
if (!celule.at(i)->getNume().compare(celula))
{
index = i;
tipCelula = celule.at(i)->getTipCelula();
break;
}
}
bool first = false;
len = inregistrari.size();
for (size_t i = 0; i < len; ++i)
{
if (tipCelula == TipCelula::NUMBER)
{
if (!areNumbersEqual(inregistrari.at(i)->getAtIndex(index)->dData, atof(value.c_str())))
{
continue;
}
}
else
{
if (inregistrari.at(i)->getAtIndex(index)->sData.compare(value))
{
continue;
}
}
if (!first)first = true;
inregistrari.erase(inregistrari.begin() + i);
--i;
--len;
}
if (first)
{
cout << "Inregistrarile cu coloana '" << celula << "' cu valoarea '" << value << "' au fost sterse." << endl;
FileManager::serializeTable(numeTabela, getSerialisedTable());
TableReport::log("Metoda deleteRecords(string celula, string value)", "Inregistrarile cu coloana '" + celula + "' cu valoarea '" + value + "' au fost sterse.");
}
else
{
cout << "Nu s-a sters nimic deoarece nu exista nici o valoare '" << value << "' pe coloana '" << celula << "'. " << endl;
}
}
void Tabela::setInregistrareByCondition(string celula, string valueCelula, string celulaCautare, string valueCelulaCautare)
{
size_t len = celule.size(), index = -1, index2 = -1;
bool foundFirst = false, foundSecond = false;
for (size_t i = 0; i < len; ++i)
{
if (!celule.at(i)->getNume().compare(celula))
{
index = i;
foundFirst = true;
if (foundSecond)break;
}
if (!celule.at(i)->getNume().compare(celulaCautare))
{
index2 = i;
foundSecond = true;
if (foundFirst)break;
}
}
bool first = false;
len = inregistrari.size();
for (size_t i = 0; i < len; ++i)
{
TipCelula tipCelulaCautare = celule.at(index2)->getTipCelula();
if (tipCelulaCautare == TipCelula::NUMBER)
{
if (!areNumbersEqual(inregistrari.at(i)->getAtIndex(index2)->dData, atof(valueCelulaCautare.c_str())))
{
continue;
}
}
else
{
if (inregistrari.at(i)->getAtIndex(index2)->sData.compare(valueCelulaCautare))
{
continue;
}
}
if (!first)first = true;
TipCelula tipCelula = celule.at(index)->getTipCelula();
if (tipCelula == TipCelula::NUMBER)
{
if (!is_number(valueCelula))
{
throw Exception("Eroare in sintaxa comenzii UPDATE! -> tipul celulei care trebuie actualizata este diferita de tipul valorii");
}
double *tempVal = new double;
*tempVal = atof(valueCelula.c_str());
void * tempVoidVal = (void*)tempVal;
inregistrari.at(i)->setDataAtIndex(index, tipCelula, tempVoidVal);
}
else
{
string *tempVal = new string;
*tempVal = valueCelula;
void * tempVoidVal = (void*)tempVal;
inregistrari.at(i)->setDataAtIndex(index, tipCelula, tempVoidVal);
}
}
if (first)
{
cout << "Celulele cu numele '" << celula << "' cu conditia ca celula '" << celulaCautare << "' sa aiba valoarea '" << valueCelulaCautare << "' au fost actualizate cu valoarea '" << valueCelula << "'." << endl;
FileManager::serializeTable(numeTabela, getSerialisedTable());
TableReport::log("Metoda setInregistrareByCondition(string celula, string valueCelula, string celulaCautare, string valueCelulaCautare)", "Celulele cu numele '" + celula + "' cu conditia ca celula '" + celulaCautare + "' sa aiba valoarea '" + valueCelulaCautare + "' au fost actualizate cu valoarea '" + valueCelula + "'.");
}
else
{
cout << "Nu s-a actualizat nimic deoarece nu exista nici o valoare '" << valueCelulaCautare << "' pe coloana '" << celulaCautare << "'. " << endl;
}
}
Inregistrare* Tabela::getAtIndex(size_t index)
{
return inregistrari.at(index);
}
string Tabela::printRecordAt(size_t index, vector<string> filters)
{
string output;
size_t filtersLen = filters.size();
if (filtersLen)
{
size_t celuleLen = celule.size();
string msg = "\nInregistrarea #";
msg += to_string(index);
msg += "\n";
for (size_t i = 0; i < filtersLen; ++i)
{
for (size_t j = 0; j < celuleLen; ++j)
{
if (!celule.at(j)->getNume().compare(filters.at(i)))
{
if (celule.at(j)->getTipCelula() == TipCelula::NUMBER)
{
msg += to_string(inregistrari.at(index)->getAtIndex(j)->dData);
msg += " | ";
}
else
{
msg += inregistrari.at(index)->getAtIndex(j)->sData;
msg += " | ";
}
}
}
}
msg.erase(msg.size() - 2, msg.size() - 1);
cout << msg << endl;
output += msg + "\n";
}
else
{
size_t celuleLen = celule.size();
string msg = "\nInregistrarea #";
msg += to_string(index);
msg += "\n";
for (size_t i = 0; i < celuleLen; ++i)
{
if (celule.at(i)->getTipCelula() == TipCelula::NUMBER)
{
msg += to_string(inregistrari.at(index)->getAtIndex(i)->dData);
msg += " | ";
}
else
{
msg += inregistrari.at(index)->getAtIndex(i)->sData;
msg += " | ";
}
}
msg.erase(msg.size() - 2, msg.size() - 1);
output += msg + "\n";
cout << msg << endl;
}
return output;
}
void Tabela::printRecords(vector<string> filters, Filter filter, size_t celulaIndex)
{
string output;
if (celulaIndex != -1 && !filter.celula.empty() && !filter.value.empty())
{
size_t len = inregistrari.size();
bool first = false;
for (size_t i = 0; i < len; ++i)
{
if (!inregistrari.at(i)->getAtIndex(celulaIndex)->sData.compare(filter.value) ||
celule.at(celulaIndex)->getTipCelula() == TipCelula::NUMBER && areNumbersEqual(inregistrari.at(i)->getAtIndex(celulaIndex)->dData, atof(filter.value.c_str())))
{
if (!first)
{
first = true;
string msg = "Se afiseaza tabelul " + string(numeTabela) + " cu conditia ca '" + filter.celula + "' sa fie '" + filter.value + "'.";
output += msg + "\n";
cout << msg << endl;
size_t filtersLen = filters.size();
if (filtersLen)
{
msg.clear();
msg.assign("Se afiseaza coloanele ");
output += msg;
cout << msg;
for (size_t j = 0; j < filtersLen; ++j)
{
msg.clear();
msg.assign(filters.at(j));
output += msg;
cout << msg;
if (j != filtersLen - 1)
{
msg.clear();
msg.assign(", ");
output += msg;
cout << msg;
}
}
output += "\n";
cout << endl;
}
}
++inregistrariGasite;
output += printRecordAt(i, filters);
}
}
}
else
{
string msg = "Se afiseaza tot tabelul " + string(numeTabela) + ".";
output += msg + "\n";
cout << msg << endl;
size_t filtersLen = filters.size();
if (filtersLen)
{
msg.clear();
msg.assign("Se afiseaza coloanele ");
output += msg;
cout << msg;
for (size_t j = 0; j < filtersLen; ++j)
{
msg.clear();
msg.assign(filters.at(j));
output += msg;
cout << msg;
if (j != filtersLen - 1)
{
msg.clear();
msg.assign(", ");
output += msg;
cout << msg;
}
}
output += "\n";
cout << endl;
}
size_t len = inregistrari.size();
for (size_t i = 0; i < len; ++i)
{
output += printRecordAt(i, filters);
}
inregistrariGasite = len;
}
if (!inregistrariGasite)
{
if (!filter.celula.empty() && !filter.value.empty())
{
string msg = "Nu s-au gasit inregistrari cu coloana '" + filter.celula + "' sa aiba valoarea '" + filter.value + "'!";
output += msg + "\n";
cout << msg << endl;
}
else
{
string msg = "Tabelul este gol!";
TableReport::log("Meotda printRecordAt(size_t index, vector<string> filters)", msg);
output += msg + "\n";
cout << msg << endl;
}
}
else
{
if (inregistrariGasite != inregistrari.size())
{
string msg = "S-au gasit " + to_string(inregistrariGasite) + " inregistrari cu coloana '" + filter.celula + "' avand valoarea '" + filter.value + "'.";
TableReport::log("Meotda printRecordAt(size_t index, vector<string> filters)", msg);
output += "\n" + msg + "\n";
cout << endl << msg << endl;
}
}
output += "\n";
cout << endl;
inregistrariGasite = 0;
FileManager::generateReport(numeTabela, output, REPORT_PREFIX + to_string(queries++) + REPORT_EXTENSION);
}
size_t Tabela::getCeluleSize()
{
return celule.size();
}
vector<Celula*> Tabela::getCelule()
{
return celule;
}
size_t Tabela::getLast()
{
return inregistrari.size() - 1;
}
int Tabela::getId()
{
return ID_TABELA;
}
string Tabela::getSerialisedTable()
{
string output;
size_t len = inregistrari.size();
for (size_t i = 0; i < len; ++i)
{
size_t len2 = getCeluleSize();
for (size_t j = 0; j < len2; ++j)
{
if (celule.at(j)->getTipCelula() == TipCelula::NUMBER)
{
output += to_string(inregistrari.at(i)->getAtIndex(j)->dData);
}
else
{
output += inregistrari.at(i)->getAtIndex(j)->sData;
}
if (j != len2 - 1)
{
output += ", ";
}
}
if (i != len - 1)
{
output += "\n";
}
}
return output;
} | 24.586694 | 326 | 0.620336 | [
"vector"
] |
dd1ed3d87b9ea0c14e00cf5f002a95645f4a9e68 | 805 | cpp | C++ | Leetcode2/097.cpp | nolink/algorithm | 29d15403a2d720771cf266a1ab04b0ab29d4cb6c | [
"MIT"
] | null | null | null | Leetcode2/097.cpp | nolink/algorithm | 29d15403a2d720771cf266a1ab04b0ab29d4cb6c | [
"MIT"
] | null | null | null | Leetcode2/097.cpp | nolink/algorithm | 29d15403a2d720771cf266a1ab04b0ab29d4cb6c | [
"MIT"
] | null | null | null | class Solution {
public:
bool isInterleave(string s1, string s2, string s3) {
int n1 = s1.length(), n2 = s2.length(), n3 = s3.length();
if(n1 + n2 != n3) return false;
vector<vector<bool>> dp(n1+1, vector<bool>(n2+1, false));
for(int i=0;i<=n1;i++){
for(int j=0;j<=n2;j++){
if(i == 0 && j == 0){
dp[i][j] = true;
}else if(i == 0){
dp[i][j] = dp[i][j-1] && s2[j-1] == s3[j-1];
}else if(j == 0){
dp[i][j] = dp[i-1][j] && s1[i-1] == s3[i-1];
}else{
dp[i][j] = (dp[i-1][j] && s1[i-1] == s3[i+j-1]) || (dp[i][j-1] && s2[j-1] == s3[i+j-1]);
}
}
}
return dp[n1][n2];
}
};
| 35 | 108 | 0.35528 | [
"vector"
] |
dd27541fc40d670282a01d40129f1974906f6efb | 33,692 | cpp | C++ | src/ssdp/ssdp_device.cpp | neheb/npupnp | d00aaf2c5af8b9453cda32f9ed3981d49ef1d01c | [
"BSD-3-Clause"
] | null | null | null | src/ssdp/ssdp_device.cpp | neheb/npupnp | d00aaf2c5af8b9453cda32f9ed3981d49ef1d01c | [
"BSD-3-Clause"
] | null | null | null | src/ssdp/ssdp_device.cpp | neheb/npupnp | d00aaf2c5af8b9453cda32f9ed3981d49ef1d01c | [
"BSD-3-Clause"
] | null | null | null | /**************************************************************************
*
* Copyright (c) 2000-2003 Intel Corporation
* All rights reserved.
* Copyright (C) 2011-2012 France Telecom All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* - Neither name of Intel Corporation nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL INTEL OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
**************************************************************************/
#include "config.h"
#ifdef INCLUDE_DEVICE_APIS
#if EXCLUDE_SSDP == 0
#include "httputils.h"
#include "ssdplib.h"
#include "statcodes.h"
#include "ThreadPool.h"
#include "upnpapi.h"
#include "UpnpInet.h"
#include "upnpdebug.h"
#include "TimerThread.h"
#include "genut.h"
#include "inet_pton.h"
#include "netif.h"
#include "upnpapi.h"
#include <cassert>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <sstream>
#include <string>
#include <thread>
#include <algorithm>
#include <chrono>
struct SsdpSearchReply {
int MaxAge;
UpnpDevice_Handle handle;
struct sockaddr_storage dest_addr;
SsdpEntity event;
};
struct SSDPPwrState {
int PowerState;
int SleepPeriod;
int RegistrationState;
};
// A bundle to simplify arg lists
struct SSDPCommonData {
SOCKET sock;
struct sockaddr *DestAddr;
const char *DevOrServType;
SSDPPwrState pwr;
std::string prodvers;
};
static void del_ssdpsearchreply(void *p)
{
delete static_cast<SsdpSearchReply *>(p);
}
static void *thread_advertiseandreply(void *data)
{
auto arg = static_cast<SsdpSearchReply *>(data);
AdvertiseAndReply(arg->handle, MSGTYPE_REPLY,
arg->MaxAge,
reinterpret_cast<struct sockaddr *>(&arg->dest_addr),
arg->event);
return nullptr;
}
void ssdp_handle_device_request(SSDPPacketParser& parser,
struct sockaddr_storage *dest_addr)
{
int handle, start;
struct Handle_Info *dev_info = nullptr;
int mx;
SsdpEntity event;
int maxAge;
/* check man hdr. */
if (!parser.man || strcmp(parser.man, R"("ssdp:discover")") != 0) {
/* bad or missing hdr. */
UpnpPrintf(UPNP_ALL, API, __FILE__, __LINE__,
"ssdp_handle_device_req: no/bad MAN header\n");
return;
}
/* MX header. Must be >= 1*/
if (!parser.mx || (mx = atoi(parser.mx)) <= 0) {
UpnpPrintf(UPNP_ALL, API, __FILE__, __LINE__,
"ssdp_handle_device_req: no/bad MX header\n");
return;
}
/* ST header. */
if (!parser.st || ssdp_request_type(parser.st, &event) == -1) {
UpnpPrintf(UPNP_ALL, API, __FILE__, __LINE__,
"ssdp_handle_device_req: no/bad ST header\n");
return;
}
// Loop to dispatch the packet to each of our configured devices
// by starting the handle search at the last processed
// position. each device response is scheduled by the ThreadPool
// with a random delay based on the MX header of the search packet.
start = 0;
for (;;) {
HandleLock();
/* device info. */
switch (GetDeviceHandleInfo(start, &handle, &dev_info)) {
case HND_DEVICE:
break;
default:
HandleUnlock();
/* no info found. */
return;
}
maxAge = dev_info->MaxAge;
HandleUnlock();
UpnpPrintf(UPNP_DEBUG, API, __FILE__, __LINE__,
"MAX-AGE = %d\n", maxAge);
UpnpPrintf(UPNP_DEBUG, API, __FILE__, __LINE__,
"MX = %d\n", maxAge);
UpnpPrintf(UPNP_DEBUG, API, __FILE__, __LINE__,
"DeviceType = %s\n", event.DeviceType.c_str());
UpnpPrintf(UPNP_DEBUG, API, __FILE__, __LINE__,
"DeviceUuid = %s\n", event.UDN.c_str());
UpnpPrintf(UPNP_DEBUG, API, __FILE__, __LINE__,
"ServiceType = %s\n", event.ServiceType.c_str());
SsdpSearchReply *threadArg = new SsdpSearchReply;
if (threadArg == nullptr)
return;
threadArg->handle = handle;
memcpy(&threadArg->dest_addr, dest_addr, sizeof(threadArg->dest_addr));
threadArg->event = event;
threadArg->MaxAge = maxAge;
mx = std::max(1, mx);
/* Subtract a bit from the mx to allow for network/processing delays */
int delayms = rand() % (mx * 1000 - 100);
UpnpPrintf(UPNP_ALL, API, __FILE__, __LINE__,
"ssdp_handle_device_req: scheduling resp in %d ms\n",delayms);
gTimerThread->schedule(
TimerThread::SHORT_TERM, std::chrono::milliseconds(delayms),
nullptr, thread_advertiseandreply, threadArg, del_ssdpsearchreply);
start = handle;
}
}
// Create the reply socket and determine the appropriate host address
// for setting the LOCATION header
static SOCKET createMulticastSocket4(
const struct sockaddr_in *srcaddr, std::string& lochost)
{
char ttl = 2;
#ifdef _WIN32
BOOL bcast = TRUE;
#else
int bcast = 1;
#endif
const NetIF::IPAddr
ipaddr(reinterpret_cast<const struct sockaddr *>(srcaddr));
lochost = ipaddr.straddr();
SOCKET sock = socket(AF_INET, SOCK_DGRAM, 0);
if (sock == INVALID_SOCKET) {
return INVALID_SOCKET;
}
uint32_t srcAddr = srcaddr->sin_addr.s_addr;
if (setsockopt(sock, IPPROTO_IP, IP_MULTICAST_IF,
reinterpret_cast<char *>(&srcAddr), sizeof(srcAddr)) < 0) {
goto error;
}
if (setsockopt(sock, IPPROTO_IP, IP_MULTICAST_TTL, &ttl, sizeof(ttl)) < 0) {
goto error;
}
if(setsockopt(sock, SOL_SOCKET, SO_BROADCAST, reinterpret_cast<char *>(&bcast), sizeof(bcast)) < 0) {
goto error;
}
if (bind(sock, reinterpret_cast<const struct sockaddr *>(srcaddr),
sizeof(struct sockaddr_in)) < 0) {
goto error;
}
return sock;
error:
UpnpCloseSocket(sock);
return INVALID_SOCKET;
}
static SOCKET createReplySocket4(
struct sockaddr_in *destaddr, std::string& lochost)
{
SOCKET sock = socket(static_cast<int>(destaddr->sin_family), SOCK_DGRAM, 0);
if (sock == INVALID_SOCKET) {
return INVALID_SOCKET;
}
// Determine the proper interface and compute the location string
NetIF::IPAddr dipaddr(reinterpret_cast<struct sockaddr*>(destaddr));
NetIF::IPAddr hostaddr;
const auto netif =
NetIF::Interfaces::interfaceForAddress(dipaddr, g_netifs, hostaddr);
if (netif && hostaddr.ok()) {
lochost = hostaddr.straddr();
} else {
lochost = apiFirstIPV4Str();
}
return sock;
}
#ifdef UPNP_ENABLE_IPV6
static std::string strInBrackets(const std::string& straddr)
{
return std::string("[") + straddr + "]";
}
static SOCKET createMulticastSocket6(int index, std::string& lochost)
{
int hops = 1;
SOCKET sock = socket(AF_INET6, SOCK_DGRAM, 0);
if (sock == INVALID_SOCKET) {
return INVALID_SOCKET;
}
if (setsockopt(sock, IPPROTO_IPV6, IPV6_MULTICAST_IF,
reinterpret_cast<char *>(&index), sizeof(index)) < 0) {
goto error;
}
if (setsockopt(sock, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
reinterpret_cast<char *>(&hops), sizeof(hops)) < 0) {
goto error;
}
lochost.clear();
for (const auto& netif : g_netifs) {
if (netif.getindex() == index) {
const auto ipaddr =
netif.firstipv6addr(NetIF::IPAddr::Scope::LINK);
if (ipaddr) {
lochost = strInBrackets(ipaddr->straddr());
break;
}
}
}
if (lochost.empty()) {
lochost = strInBrackets(apiFirstIPV6Str());
}
return sock;
error:
UpnpCloseSocket(sock);
return INVALID_SOCKET;
}
static SOCKET createReplySocket6(
struct sockaddr_in6 *destaddr, std::string& lochost)
{
SOCKET sock = socket(AF_INET6, SOCK_DGRAM, 0);
if (sock == INVALID_SOCKET) {
return INVALID_SOCKET;
}
int index = destaddr->sin6_scope_id;
lochost.clear();
for (const auto& netif : g_netifs) {
if (netif.getindex() == index) {
const auto ipaddr =
netif.firstipv6addr(NetIF::IPAddr::Scope::LINK);
if (ipaddr) {
lochost = strInBrackets(ipaddr->straddr());
break;
}
}
}
if (lochost.empty()) {
lochost = strInBrackets(apiFirstIPV6Str());
}
return sock;
}
#else // ! ENABLE_IPV6 ->
static SOCKET createReplySocket6(
struct sockaddr_in6 *destaddr, std::string& lochost)
{
return INVALID_SOCKET;
}
#endif // ! ENABLE_IPV6
// Set the UPnP predefined multicast destination addresses
static bool ssdpMcastAddr(struct sockaddr_storage& ss, int AddressFamily)
{
ss = {};
switch (AddressFamily) {
case AF_INET:
{
auto DestAddr4 = reinterpret_cast<struct sockaddr_in *>(&ss);
DestAddr4->sin_family = static_cast<sa_family_t>(AF_INET);
inet_pton(AF_INET, SSDP_IP, &DestAddr4->sin_addr);
DestAddr4->sin_port = htons(SSDP_PORT);
}
break;
case AF_INET6:
{
auto DestAddr6 = reinterpret_cast<struct sockaddr_in6 *>(&ss);
DestAddr6->sin6_family = static_cast<sa_family_t>(AF_INET6);
inet_pton(AF_INET6, SSDP_IPV6_LINKLOCAL, &DestAddr6->sin6_addr);
DestAddr6->sin6_port = htons(SSDP_PORT);
}
break;
default:
return false;
}
return true;
}
static int sendPackets(
SOCKET sock, struct sockaddr *daddr, int cnt, std::string *pckts)
{
NetIF::IPAddr destip(daddr);
int socklen = daddr->sa_family == AF_INET ? sizeof(struct sockaddr_in) :
sizeof(struct sockaddr_in6);
for (int i = 0; i < cnt; i++) {
ssize_t rc;
UpnpPrintf(UPNP_DEBUG, SSDP, __FILE__, __LINE__,
">>> SSDP SEND to %s >>>\n%s\n",
destip.straddr().c_str(), pckts[i].c_str());
rc = sendto(sock, pckts[i].c_str(), pckts[i].size(), 0, daddr, socklen);
if (rc == -1) {
char errorBuffer[ERROR_BUFFER_LEN];
posix_strerror_r(errno, errorBuffer, ERROR_BUFFER_LEN);
UpnpPrintf(UPNP_INFO, SSDP, __FILE__, __LINE__,
"sendPackets: sendto: %s\n", errorBuffer);
return UPNP_E_SOCKET_WRITE;
}
}
return UPNP_E_SUCCESS;
}
/* Creates a device notify or search reply packet. */
static void CreateServicePacket(
SSDPDevMessageType msg_type, const char *nt, const char *usn,
const std::string& location, int duration, std::string &packet,
int AddressFamily, SSDPPwrState& pwr, const std::string& prodvers)
{
std::ostringstream str;
switch (msg_type) {
case MSGTYPE_REPLY:
str <<
"HTTP/1.1 " << HTTP_OK << " OK\r\n" <<
"CACHE-CONTROL: max-age=" << duration << "\r\n" <<
"DATE: " << make_date_string(0) << "\r\n" <<
"EXT:\r\n" <<
"LOCATION: " << location << "\r\n" <<
"SERVER: " << get_sdk_device_info(prodvers) << "\r\n" <<
#ifdef UPNP_HAVE_OPTSSDP
"OPT: " << R"("http://schemas.upnp.org/upnp/1/0/"; ns=01)" << "\r\n" <<
"01-NLS: " << gUpnpSdkNLSuuid << "\r\n" <<
"X-User-Agent: " << X_USER_AGENT << "\r\n" <<
#endif
"ST: " << nt << "\r\n" <<
"USN: " << usn << "\r\n";
break;
case MSGTYPE_ADVERTISEMENT:
case MSGTYPE_SHUTDOWN:
{
const char *nts = (msg_type == MSGTYPE_ADVERTISEMENT) ?
"ssdp:alive" : "ssdp:byebye";
/* NOTE: The CACHE-CONTROL and LOCATION headers are not present in
* a shutdown msg, but are present here for MS WinMe interop. */
const char *host;
switch (AddressFamily) {
case AF_INET: host = SSDP_IP; break;
default: host = "[" SSDP_IPV6_LINKLOCAL "]";
}
str <<
"NOTIFY * HTTP/1.1\r\n" <<
"HOST: " << host << ":" << SSDP_PORT << "\r\n" <<
"CACHE-CONTROL: max-age=" << duration << "\r\n" <<
"LOCATION: " << location << "\r\n" <<
"SERVER: " << get_sdk_device_info(prodvers) << "\r\n" <<
#ifdef UPNP_HAVE_OPTSSDP
"OPT: " << R"("http://schemas.upnp.org/upnp/1/0/"; ns=01)" << "\r\n" <<
"01-NLS: " << gUpnpSdkNLSuuid << "\r\n" <<
"X-User-Agent: " << X_USER_AGENT << "\r\n" <<
#endif
"NT: " << nt << "\r\n" <<
"NTS: " << nts << "\r\n" <<
"USN: " << usn << "\r\n";
}
break;
default:
std::cerr << "Unknown message type in CreateServicePacket\n";
abort();
}
if (pwr.PowerState > 0) {
str <<
"Powerstate: " << pwr.PowerState << "\r\n" <<
"SleepPeriod: " << pwr.SleepPeriod << "\r\n" <<
"RegistrationState: " << pwr.RegistrationState << "\r\n";
}
str << "\r\n";
packet = str.str();
}
static int DeviceAdvertisementOrShutdown(
SSDPCommonData& sscd, SSDPDevMessageType msgtype, const char *DevType,
int RootDev, const char *Udn, const std::string& Location, int Duration)
{
char Mil_Usn[LINE_SIZE];
std::string msgs[3];
int ret_code = UPNP_E_OUTOF_MEMORY;
int rc = 0;
/* If device is a root device, we need to send 3 messages */
if (RootDev) {
rc = snprintf(Mil_Usn, sizeof(Mil_Usn), "%s::upnp:rootdevice", Udn);
if (rc < 0 || static_cast<unsigned int>(rc) >= sizeof(Mil_Usn))
goto error_handler;
CreateServicePacket(msgtype, "upnp:rootdevice",
Mil_Usn, Location, Duration, msgs[0],
sscd.DestAddr->sa_family, sscd.pwr, sscd.prodvers);
}
/* both root and sub-devices need to send these two messages */
CreateServicePacket(msgtype, Udn, Udn,
Location, Duration, msgs[1], sscd.DestAddr->sa_family,
sscd.pwr, sscd.prodvers);
rc = snprintf(Mil_Usn, sizeof(Mil_Usn), "%s::%s", Udn, DevType);
if (rc < 0 || static_cast<unsigned int>(rc) >= sizeof(Mil_Usn))
goto error_handler;
CreateServicePacket(msgtype, DevType, Mil_Usn, Location, Duration, msgs[2],
sscd.DestAddr->sa_family, sscd.pwr, sscd.prodvers);
/* check error */
if ((RootDev && msgs[0].empty()) || msgs[1].empty() || msgs[2].empty()) {
goto error_handler;
}
/* send packets */
if (RootDev) {
/* send 3 msg types */
ret_code = sendPackets(sscd.sock, sscd.DestAddr, 3, &msgs[0]);
} else { /* sub-device */
/* send 2 msg types */
ret_code = sendPackets(sscd.sock, sscd.DestAddr, 2, &msgs[1]);
}
error_handler:
return ret_code;
}
static int SendReply(
SSDPCommonData& sscd, const char *DevType, int RootDev,
const char *Udn, const std::string& Location, int Duration, int ByType)
{
int ret_code = UPNP_E_OUTOF_MEMORY;
std::string msgs[2];
int num_msgs;
char Mil_Usn[LINE_SIZE];
int i;
int rc = 0;
int family = static_cast<int>(sscd.DestAddr->sa_family);
if (RootDev) {
/* one msg for root device */
num_msgs = 1;
rc = snprintf(Mil_Usn, sizeof(Mil_Usn), "%s::upnp:rootdevice", Udn);
if (rc < 0 || static_cast<unsigned int>(rc) >= sizeof(Mil_Usn))
goto error_handler;
CreateServicePacket(MSGTYPE_REPLY, "upnp:rootdevice", Mil_Usn, Location,
Duration, msgs[0], family, sscd.pwr, sscd.prodvers);
} else {
/* two msgs for embedded devices */
num_msgs = 1;
/*NK: FIX for extra response when someone searches by udn */
if (!ByType) {
CreateServicePacket(MSGTYPE_REPLY, Udn, Udn, Location, Duration,
msgs[0], family, sscd.pwr, sscd.prodvers);
} else {
rc = snprintf(Mil_Usn, sizeof(Mil_Usn), "%s::%s", Udn, DevType);
if (rc < 0 || static_cast<unsigned int>(rc) >= sizeof(Mil_Usn))
goto error_handler;
CreateServicePacket(MSGTYPE_REPLY, DevType, Mil_Usn, Location,
Duration, msgs[0],family,sscd.pwr,sscd.prodvers);
}
}
/* check error */
for (i = 0; i < num_msgs; i++) {
if (msgs[i].empty()) {
goto error_handler;
}
}
ret_code = sendPackets(sscd.sock, sscd.DestAddr, num_msgs, msgs);
error_handler:
return ret_code;
}
static int DeviceReply(
SSDPCommonData& sscd, const char *DevType, int RootDev,
const char *Udn, const std::string& Location, int Duration)
{
std::string szReq[3];
char Mil_Nt[LINE_SIZE], Mil_Usn[LINE_SIZE];
int rc = 0;
int family = static_cast<int>(sscd.DestAddr->sa_family);
/* create 2 or 3 msgs */
if (RootDev) {
/* 3 replies for root device */
upnp_strlcpy(Mil_Nt, "upnp:rootdevice", sizeof(Mil_Nt));
rc = snprintf(Mil_Usn, sizeof(Mil_Usn), "%s::upnp:rootdevice", Udn);
if (rc < 0 || static_cast<unsigned int>(rc) >= sizeof(Mil_Usn))
return UPNP_E_OUTOF_MEMORY;
CreateServicePacket(MSGTYPE_REPLY, Mil_Nt, Mil_Usn, Location,
Duration, szReq[0], family, sscd.pwr, sscd.prodvers);
}
rc = snprintf(Mil_Nt, sizeof(Mil_Nt), "%s", Udn);
if (rc < 0 || static_cast<unsigned int>(rc) >= sizeof(Mil_Nt))
return UPNP_E_OUTOF_MEMORY;
rc = snprintf(Mil_Usn, sizeof(Mil_Usn), "%s", Udn);
if (rc < 0 || static_cast<unsigned int>(rc) >= sizeof(Mil_Usn))
return UPNP_E_OUTOF_MEMORY;
CreateServicePacket(MSGTYPE_REPLY, Mil_Nt, Mil_Usn, Location, Duration,
szReq[1], family, sscd.pwr, sscd.prodvers);
rc = snprintf(Mil_Nt, sizeof(Mil_Nt), "%s", DevType);
if (rc < 0 || static_cast<unsigned int>(rc) >= sizeof(Mil_Nt))
return UPNP_E_OUTOF_MEMORY;
rc = snprintf(Mil_Usn, sizeof(Mil_Usn), "%s::%s", Udn, DevType);
if (rc < 0 || static_cast<unsigned int>(rc) >= sizeof(Mil_Usn))
return UPNP_E_OUTOF_MEMORY;
CreateServicePacket(MSGTYPE_REPLY, Mil_Nt, Mil_Usn, Location, Duration,
szReq[2], family, sscd.pwr, sscd.prodvers);
/* check error */
if ((RootDev && szReq[0].empty()) || szReq[1].empty() || szReq[2].empty()) {
return UPNP_E_OUTOF_MEMORY;
}
/* send replies */
if (RootDev) {
return sendPackets(sscd.sock, sscd.DestAddr, 3, szReq);
}
return sendPackets(sscd.sock, sscd.DestAddr, 2, &szReq[1]);
}
static int ServiceSend(
SSDPCommonData& sscd, SSDPDevMessageType tp, const char *ServType,
const char *Udn, const std::string& Location, int Duration)
{
char Mil_Usn[LINE_SIZE];
std::string szReq[1];
int rc = 0;
rc = snprintf(Mil_Usn, sizeof(Mil_Usn), "%s::%s", Udn, ServType);
if (rc < 0 || static_cast<unsigned int>(rc) >= sizeof(Mil_Usn))
return UPNP_E_OUTOF_MEMORY;
CreateServicePacket(tp, ServType, Mil_Usn, Location, Duration, szReq[0],
sscd.DestAddr->sa_family, sscd.pwr, sscd.prodvers);
if (szReq[0].empty()) {
return UPNP_E_OUTOF_MEMORY;
}
return sendPackets(sscd.sock, sscd.DestAddr, 1, szReq);
}
static void replaceLochost(std::string& location, const std::string& lochost)
{
std::string::size_type pos = location.find(g_HostForTemplate);
if (pos != std::string::npos) {
location.replace(pos, g_HostForTemplate.size(), lochost);
}
}
static int servOrDevVers(const char *in)
{
const char *cp = std::strrchr(in, ':');
if (nullptr == cp)
return 0;
cp++;
if (*cp != 0) {
return std::atoi(cp);
}
return 0;
}
static bool sameServOrDevNoVers(const char *his, const char *mine)
{
const char *cp = std::strrchr(mine, ':');
if (nullptr == cp) {
// ??
return !strcasecmp(his, mine);
}
return !strncasecmp(his, mine, cp - mine);
}
// Send SSDP messages for one root device, one destination address,
// which is the reply host or one of our source addresses. There may
// be subdevices
static int AdvertiseAndReplyOneDest(
UpnpDevice_Handle Hnd, SSDPDevMessageType tp, int Exp,
struct sockaddr *DestAddr, const SsdpEntity& sdata, SOCKET sock,
const std::string& lochost)
{
int retVal = UPNP_E_SUCCESS;
int defaultExp = DEFAULT_MAXAGE;
int NumCopy = 0;
std::vector<const UPnPDeviceDesc*> alldevices;
bool isNotify = (tp == MSGTYPE_ADVERTISEMENT || tp == MSGTYPE_SHUTDOWN);
/* Use a read lock */
HandleReadLock();
struct Handle_Info *SInfo = nullptr;
if (GetHandleInfo(Hnd, &SInfo) != HND_DEVICE) {
HandleUnlock();
return UPNP_E_INVALID_HANDLE;
}
defaultExp = SInfo->MaxAge;
struct SSDPCommonData sscd;
sscd.sock = sock;
sscd.DestAddr = DestAddr;
sscd.pwr = SSDPPwrState{
SInfo->PowerState, SInfo->SleepPeriod, SInfo->RegistrationState};
sscd.prodvers = SInfo->productversion;
std::string location{SInfo->DescURL};
replaceLochost(location, lochost);
std::string lowerloc{SInfo->LowerDescURL};
replaceLochost(lowerloc, lochost);
// Store pointers to the root and embedded devices in a single vector
// for later convenience of mostly identical processing.
alldevices.push_back(&SInfo->devdesc);
for (const auto& dev : SInfo->devdesc.embedded) {
alldevices.push_back(&dev);
}
/* send advertisements/replies */
while (NumCopy == 0 || (isNotify && NumCopy < NUM_SSDP_COPY)) {
if (NumCopy != 0)
std::this_thread::sleep_for(std::chrono::milliseconds(SSDP_PAUSE));
NumCopy++;
for (auto& devp : alldevices) {
bool isroot = &devp == &(*alldevices.begin());
const char *devType = devp->deviceType.c_str();
const char *UDNstr = devp->UDN.c_str();
if (isNotify) {
DeviceAdvertisementOrShutdown(
sscd, tp, devType, isroot, UDNstr, location, Exp);
} else {
switch (sdata.RequestType) {
case SSDP_ALL:
DeviceReply(sscd, devType, isroot, UDNstr,
location, defaultExp);
break;
case SSDP_ROOTDEVICE:
if (isroot) {
SendReply(sscd, devType, 1, UDNstr,
location, defaultExp, 0);
}
break;
case SSDP_DEVICEUDN:
if (!strcasecmp(sdata.UDN.c_str(), UDNstr)) {
UpnpPrintf(UPNP_DEBUG, SSDP, __FILE__, __LINE__,
"DeviceUDN=%s/search UDN=%s MATCH\n",
UDNstr, sdata.UDN.c_str());
SendReply(sscd, devType, 0, UDNstr, location,
defaultExp, 0);
} else {
UpnpPrintf(UPNP_DEBUG, SSDP, __FILE__, __LINE__,
"DeviceUDN=%s/search UDN=%s NOMATCH\n",
UDNstr, sdata.UDN.c_str());
}
break;
case SSDP_DEVICETYPE: {
const char *dt = sdata.DeviceType.c_str();
if (sameServOrDevNoVers(dt, devType)) {
int myvers = servOrDevVers(devType);
int hisvers = servOrDevVers(dt);
if (hisvers < myvers) {
/* the requested version is lower than the
device version must reply with the
lower version number and the lower
description URL */
UpnpPrintf(UPNP_DEBUG, SSDP, __FILE__, __LINE__,
"DeviceType=%s/srchdevType=%s MATCH\n",
devType, dt);
SendReply(sscd, dt, 0, UDNstr,
lowerloc, defaultExp, 1);
} else if (hisvers == myvers) {
UpnpPrintf(UPNP_DEBUG, SSDP, __FILE__, __LINE__,
"DeviceType=%s/srchDevType=%s MATCH\n",
devType, dt);
SendReply(sscd, dt, 0,
UDNstr, location, defaultExp, 1);
} else {
UpnpPrintf(UPNP_DEBUG, SSDP, __FILE__, __LINE__,
"DeviceType=%s/srchDevType=%s NOMATCH\n",
devType, dt);
}
} else {
UpnpPrintf(UPNP_DEBUG, SSDP, __FILE__, __LINE__,
"DeviceType=%s /srchdevType=%s NOMATCH\n",
devType, dt);
}
}
break;
default:
break;
}
}
/* send service advertisements for services corresponding
* to the same device */
UpnpPrintf(UPNP_DEBUG, SSDP, __FILE__, __LINE__,
"Sending service advertisements\n");
/* Correct service traversal such that each device's serviceList
* is directly traversed as a child of its parent device. This
* ensures that the service's alive message uses the UDN of
* the parent device. */
for (const auto& service : devp->services) {
const char *servType = service.serviceType.c_str();
UpnpPrintf(UPNP_DEBUG, SSDP, __FILE__, __LINE__,
"ServiceType = %s\n", servType);
if (isNotify) {
ServiceSend(sscd, tp, servType, UDNstr, location, Exp);
} else {
switch (sdata.RequestType) {
case SSDP_ALL:
ServiceSend(sscd, MSGTYPE_REPLY, servType,
UDNstr, location, defaultExp);
break;
case SSDP_SERVICE: {
const char *sst = sdata.ServiceType.c_str();
if (sameServOrDevNoVers(sst, servType)) {
int myvers = servOrDevVers(servType);
int hisvers = servOrDevVers(sst);
if (hisvers < myvers) {
/* the requested version is lower
than the service version must
reply with the lower version
number and the lower
description URL */
UpnpPrintf(
UPNP_DEBUG, SSDP, __FILE__, __LINE__,
"ServiceTp=%s/searchServTp=%s MATCH\n",
sst, servType);
SendReply(sscd, sst, 0, UDNstr, lowerloc,
defaultExp, 1);
} else if (hisvers == myvers) {
UpnpPrintf(
UPNP_DEBUG, SSDP, __FILE__, __LINE__,
"ServiceTp=%s/searchServTp=%s MATCH\n",
sst, servType);
SendReply(sscd, sst, 0, UDNstr,
location, defaultExp, 1);
} else {
UpnpPrintf(
UPNP_DEBUG, SSDP, __FILE__, __LINE__,
"ServiceTp=%s/srchServTp=%s NO MATCH\n",
sst, servType);
}
} else {
UpnpPrintf(
UPNP_DEBUG, SSDP, __FILE__, __LINE__,
"ServiceTp=%s/srchServTp=%s NO MATCH\n",
sst, servType);
}
}
break;
default:
break;
}
}
}
}
}
UpnpPrintf(UPNP_ALL, SSDP, __FILE__, __LINE__, "AdvertiseAndReply1 exit\n");
HandleUnlock();
return retVal;
}
// Process the advertisements or replies for one root device (which
// may have subdevices).
//
// This top routine calls AdvertiseAndReplyOneDest() to do the real
// work for each of the appropriate network addresses/interfaces.
int AdvertiseAndReply(UpnpDevice_Handle Hnd, SSDPDevMessageType tp, int Exp,
struct sockaddr *repDestAddr, const SsdpEntity& sdata)
{
bool isNotify = (tp == MSGTYPE_ADVERTISEMENT || tp == MSGTYPE_SHUTDOWN);
int ret = UPNP_E_SUCCESS;
std::string lochost;
SOCKET sock = INVALID_SOCKET;
if (isNotify) {
// Loop on our interfaces and addresses
for (const auto& netif : g_netifs) {
UpnpPrintf(UPNP_ALL, SSDP, __FILE__, __LINE__,
"ssdp_device: mcast for %s\n", netif.getname().c_str());
struct sockaddr_storage dss;
auto destaddr = reinterpret_cast<struct sockaddr*>(&dss);
#ifdef UPNP_ENABLE_IPV6
if (using_ipv6()) {
ssdpMcastAddr(dss, AF_INET6);
sock = createMulticastSocket6(netif.getindex(), lochost);
if (sock == INVALID_SOCKET) {
goto exitfunc;
}
ret = AdvertiseAndReplyOneDest(
Hnd, tp, Exp, destaddr, sdata, sock, lochost);
if (ret != UPNP_E_SUCCESS) {
UpnpPrintf(UPNP_INFO, SSDP, __FILE__, __LINE__,
"SSDP dev: IPV6 SEND failed for %s\n",
netif.getname().c_str());
goto exitfunc;
}
UpnpCloseSocket(sock);
sock = INVALID_SOCKET;
}
#endif /* UPNP_ENABLE_IPV6 */
ssdpMcastAddr(dss, AF_INET);
auto addresses = netif.getaddresses();
for (const auto& ipaddr : addresses.first) {
if (ipaddr.family() == NetIF::IPAddr::Family::IPV4) {
const struct sockaddr_storage& fss{ipaddr.getaddr()};
sock = createMulticastSocket4(
reinterpret_cast<const struct sockaddr_in*>(&fss),
lochost);
} else {
continue;
}
if (sock == INVALID_SOCKET) {
goto exitfunc;
}
ret = AdvertiseAndReplyOneDest(
Hnd, tp, Exp, destaddr, sdata, sock, lochost);
UpnpCloseSocket(sock);
sock = INVALID_SOCKET;
}
}
} else {
sock = repDestAddr->sa_family == AF_INET ?
createReplySocket4(
reinterpret_cast<struct sockaddr_in*>(repDestAddr), lochost) :
createReplySocket6(
reinterpret_cast<struct sockaddr_in6*>(repDestAddr), lochost);
if (sock == INVALID_SOCKET) {
goto exitfunc;
}
ret = AdvertiseAndReplyOneDest(
Hnd, tp, Exp, repDestAddr, sdata, sock, lochost);
}
exitfunc:
if (ret != UPNP_E_SUCCESS) {
char errorBuffer[ERROR_BUFFER_LEN];
posix_strerror_r(errno, errorBuffer, ERROR_BUFFER_LEN);
UpnpPrintf(UPNP_INFO, SSDP, __FILE__, __LINE__,
"sendPackets: %s\n", errorBuffer);
return UPNP_E_NETWORK_ERROR;
}
if (sock != INVALID_SOCKET)
UpnpCloseSocket(sock);
return ret;
}
#endif /* EXCLUDE_SSDP */
#endif /* INCLUDE_DEVICE_APIS */
| 36.741549 | 105 | 0.552802 | [
"vector"
] |
dd2c3cec9ed48395f68248b79447490f13ef31c9 | 376 | cpp | C++ | doric-Qt/example/doric/utils/DoricSwitchBridge.cpp | Xcoder1011/Doric | ad1a409ef5edb9de8f3e1544748a9fa8015760c8 | [
"Apache-2.0"
] | 116 | 2019-12-30T11:34:47.000Z | 2022-03-31T05:32:58.000Z | doric-Qt/example/doric/utils/DoricSwitchBridge.cpp | Xcoder1011/Doric | ad1a409ef5edb9de8f3e1544748a9fa8015760c8 | [
"Apache-2.0"
] | 9 | 2020-04-26T02:04:27.000Z | 2022-01-26T07:31:01.000Z | doric-Qt/example/doric/utils/DoricSwitchBridge.cpp | Xcoder1011/Doric | ad1a409ef5edb9de8f3e1544748a9fa8015760c8 | [
"Apache-2.0"
] | 18 | 2020-01-24T15:42:03.000Z | 2021-12-28T08:17:36.000Z | #include "DoricSwitchBridge.h"
#include "shader/DoricSwitchNode.h"
DoricSwitchBridge::DoricSwitchBridge(QObject *parent) : QObject(parent) {}
void DoricSwitchBridge::onSwitch(QString pointer, bool checked) {
QObject *object = (QObject *)(pointer.toULongLong());
DoricSwitchNode *switchNode = dynamic_cast<DoricSwitchNode *>(object);
switchNode->onSwitch(checked);
}
| 28.923077 | 74 | 0.768617 | [
"object"
] |
dd33e426242323826928410eaf856b8942a0d198 | 644 | cpp | C++ | libahabin/AhaNativeRefer.cpp | aha-lang/aha | d8d9d03d55ddfd844876a31c36d6bb83c046813c | [
"MIT"
] | null | null | null | libahabin/AhaNativeRefer.cpp | aha-lang/aha | d8d9d03d55ddfd844876a31c36d6bb83c046813c | [
"MIT"
] | 1 | 2016-07-03T09:32:01.000Z | 2016-07-03T09:32:01.000Z | libahabin/AhaNativeRefer.cpp | aha-lang/aha | d8d9d03d55ddfd844876a31c36d6bb83c046813c | [
"MIT"
] | null | null | null | #include "ahabin/AhaNativeRefer.h"
#include "ahabin/exceptions.h"
namespace aha
{
void AhaNativeRefer::Read(aha_u32 SizeOfNativeRefer, std::istream& strm)
{
try
{
m_impl.Read(SizeOfNativeRefer, strm);
}
catch (BadModuleReferError&)
{
throw BadModuleNativeReferError();
}
}
aha_u32 AhaNativeRefer::Write(std::ostream& strm)
{
return m_impl.Write(strm);
}
void AhaNativeRefer::Validate(const AhaStrings& strings) const
{
m_impl.Validate(strings);
}
std::vector<aha_u32>& AhaNativeRefer::Get()
{
return m_impl.Get();
}
const std::vector<aha_u32>& AhaNativeRefer::Get() const
{
return m_impl.Get();
}
}
| 17.405405 | 73 | 0.703416 | [
"vector"
] |
dd36824025fd44743b007285d5a1736c31d8e580 | 6,501 | hpp | C++ | lib/uti/my_network/BlockingMultiThread/Server/UDP/ServerUdpMultiThreadWrapper.hpp | NicolasKeita/Apache-like | e8e866ab164547dda4353dc6fbc8219e32846082 | [
"MIT"
] | 1 | 2020-01-13T22:50:40.000Z | 2020-01-13T22:50:40.000Z | lib/uti/my_network/BlockingMultiThread/Server/UDP/ServerUdpMultiThreadWrapper.hpp | NicolasKeita/My_Apache | e8e866ab164547dda4353dc6fbc8219e32846082 | [
"MIT"
] | null | null | null | lib/uti/my_network/BlockingMultiThread/Server/UDP/ServerUdpMultiThreadWrapper.hpp | NicolasKeita/My_Apache | e8e866ab164547dda4353dc6fbc8219e32846082 | [
"MIT"
] | null | null | null | /*
** EPITECH PROJECT, 2019
** ServerUdpMultiThreadWrapper.hpp
** File description:
**
*/
#pragma once
#include <memory>
#include <iostream>
#include <boost/asio.hpp>
#include <boost/serialization/vector.hpp>
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <boost/bind.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/tuple/tuple.hpp>
#include "IServerUdpMultiThreadWrapper.hpp"
namespace uti::network {
template<class ProtocolDataPacket>
class ServerUdpMultiThreadWrapper {
public:
ServerUdpMultiThreadWrapper()
: _online { false },
_inbound_header {},
_header_length { 8 },
_inbound_data {},
_handleMessageReceived { nullptr }
{}
void turnOn(unsigned short int port, ProtocolDataPacket (*handleMessageReceived)(const ProtocolDataPacket &))
{
_handleMessageReceived = handleMessageReceived;
using boost::asio::ip::udp;
_socket = std::make_unique<udp::socket>(_io_context, udp::endpoint(udp::v4(), port));
_online = true;
while (true) {
//std::array<int8_t, 1024> data = {0};
std::pair<ProtocolDataPacket, udp::endpoint> clientMessage = this->getIncomingClientMessage();
std::cerr << "GOT A MESSAGE ! : " << std::endl;
/*
T o;
udp::endpoint e;
std::pair<T, udp::endpoint> r(o, e);
*/
//size_t length = _socket->receive_from(boost::asio::buffer(data), sender_endpoint);
std::thread thread_obj(&uti::network::ServerUdpMultiThreadWrapper<ProtocolDataPacket>::_handleRequest,
this,
//sender_endpoint,
std::ref(clientMessage.second),
clientMessage.first);
//data,
//length);
thread_obj.detach();
if (!_online)
break;
}
}
std::pair<ProtocolDataPacket, boost::asio::ip::udp::endpoint> getIncomingClientMessage()
{
// Receive the header
boost::asio::ip::udp::endpoint clientEndpoint;
_socket->receive_from(boost::asio::buffer(_inbound_header), clientEndpoint);
std::istringstream is(std::string(_inbound_header, _header_length));
std::size_t inbound_data_size = 0;
if (!(is >> std::hex >> inbound_data_size)) {
std::cerr << "[CLientUdpMultiThread] Header is not valid : " << std::dec << inbound_data_size << std::endl;
exit(31);
}
// Conversion hex to dec
std::stringstream stream;
size_t inbound_data_size_in_decimal = 0;
stream << inbound_data_size;
stream >> std::hex >> inbound_data_size_in_decimal;
_inbound_data.resize(inbound_data_size_in_decimal);
_socket->receive(boost::asio::buffer(_inbound_data));
ProtocolDataPacket t;
try {
std::string archive_data(&_inbound_data[0], _inbound_data.size());
std::istringstream archive_stream(archive_data);
boost::archive::text_iarchive archive(archive_stream);
archive >> t;
}
catch (const std::exception & e)
{
std::cerr << "[CLientUdpMultiThread] Unable to decode data.\n" << e.what() << std::endl;
exit(34);
}
return std::pair(t, clientEndpoint);
}
// void sendMessageToTheLastestClient(const std::string &message) override;
private:
boost::asio::io_context _io_context;
std::unique_ptr<boost::asio::ip::udp::socket> _socket;
bool _online;
char _inbound_header[8];
size_t _header_length;
std::vector<char> _inbound_data;
ProtocolDataPacket (*_handleMessageReceived)(const ProtocolDataPacket &);
private:
void _handleRequest(const boost::asio::ip::udp::endpoint &sender_endpoint, ProtocolDataPacket data)
{
//(void)data;
ProtocolDataPacket serverReplyToClient = _handleMessageReceived(data);
sendMessage(serverReplyToClient, sender_endpoint);
/*
std::string serverReplyToClient2 = "TODO(nicolas) change";
_socket->send_to(boost::asio::buffer(
serverReplyToClient), TODO (nicolas) Need to serialize this before sending it
serverReplyToClient2,
serverReplyToClient2.size()),
sender_endpoint);
*/
}
void sendMessage(const ProtocolDataPacket & message, const boost::asio::ip::udp::endpoint &sender_endpoint)
{
// Serialization
std::ostringstream archive_stream;
boost::archive::text_oarchive archive(archive_stream);
archive << message;
std::string message_serialized = archive_stream.str();
// Header creation
std::ostringstream header_stream;
header_stream << std::setw(static_cast<int>(_header_length)) \
<< std::hex << message_serialized.size();
if (!header_stream || header_stream.str().size() != _header_length) {
std::cerr << "[CLientUdpMultiThread] Serialization Object went wrong" << std::endl;
exit(84);
}
std::string header = header_stream.str();
// Merge
std::vector<boost::asio::const_buffer> buffers;
buffers.emplace_back(boost::asio::buffer(header));
buffers.emplace_back(boost::asio::buffer(message_serialized));
// Sending a long serialized message
//_socket->send_to(boost::asio::buffer(header), *_endpoints.begin());
_socket->send_to(boost::asio::buffer(header), sender_endpoint);
//_socket->send_to(boost::asio::buffer(message_serialized), *_endpoints.begin());
_socket->send_to(boost::asio::buffer(message_serialized), sender_endpoint);
//_socket->send_to(buffers, *_endpoints.begin()); // TODO : send it only once (merge header + message)
}
};
} | 37.796512 | 123 | 0.570528 | [
"object",
"vector"
] |
dd49de4c17d87d7775b9ba6ceebb39966572d4a5 | 11,748 | cpp | C++ | ext/include/osgEarthUtil/PolyhedralLineOfSight.cpp | energonQuest/dtEarth | 47b04bb272ec8781702dea46f5ee9a03d4a22196 | [
"MIT"
] | 6 | 2015-09-26T15:33:41.000Z | 2021-06-13T13:21:50.000Z | ext/include/osgEarthUtil/PolyhedralLineOfSight.cpp | energonQuest/dtEarth | 47b04bb272ec8781702dea46f5ee9a03d4a22196 | [
"MIT"
] | null | null | null | ext/include/osgEarthUtil/PolyhedralLineOfSight.cpp | energonQuest/dtEarth | 47b04bb272ec8781702dea46f5ee9a03d4a22196 | [
"MIT"
] | 5 | 2015-05-04T09:02:23.000Z | 2019-06-17T11:34:12.000Z | /* -*-c++-*- */
/* osgEarth - Dynamic map generation toolkit for OpenSceneGraph
* Copyright 2008-2013 Pelican Mapping
* http://osgearth.org
*
* osgEarth is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*/
#include <osgEarthUtil/PolyhedralLineOfSight>
#include <osgUtil/LineSegmentIntersector>
#include <osgUtil/IntersectionVisitor>
#include <osg/CullFace>
#define LC "[PolyhedralLineOfSight] "
using namespace osgEarth;
using namespace osgEarth::Util;
//------------------------------------------------------------------------
namespace
{
struct TerrainChangedCallback : public osgEarth::TerrainCallback
{
TerrainChangedCallback( PolyhedralLineOfSightNode* los ) : _los(los) { }
void onTileAdded(const osgEarth::TileKey& tileKey, osg::Node* terrain, TerrainCallbackContext& ) {
_los->terrainChanged( tileKey, terrain );
}
PolyhedralLineOfSightNode* _los;
};
}
//------------------------------------------------------------------------
PolyhedralLineOfSightNode::PolyhedralLineOfSightNode( MapNode* mapNode ) :
LocalizedNode( mapNode ),
_startAzim ( Angle(-45.0, Units::DEGREES) ),
_endAzim ( Angle( 45.0, Units::DEGREES) ),
_startElev ( Angle( 0.0, Units::DEGREES) ),
_endElev ( Angle( 45.0, Units::DEGREES) ),
_spacing ( Angle( 5.0, Units::DEGREES) ),
_distance ( Distance(50000.0, Units::METERS) )
{
OE_WARN << LC << "This class is under development; use at your own risk" << std::endl;
_xform = new osg::MatrixTransform();
this->addChild( _xform.get() );
_geode = new osg::Geode();
rebuildGeometry();
recalculateExtent();
_xform->addChild( _geode );
_terrainCallback = new TerrainChangedCallback(this);
if ( mapNode )
mapNode->getTerrain()->addTerrainCallback( _terrainCallback );
osg::StateSet* stateSet = this->getOrCreateStateSet();
stateSet->setMode( GL_BLEND, 1 );
stateSet->setRenderingHint( osg::StateSet::TRANSPARENT_BIN );
stateSet->setAttributeAndModes( new osg::CullFace(osg::CullFace::BACK), 1 );
}
PolyhedralLineOfSightNode::~PolyhedralLineOfSightNode()
{
if (_terrainCallback && getMapNode() )
{
getMapNode()->getTerrain()->removeTerrainCallback( _terrainCallback.get() );
}
}
void
PolyhedralLineOfSightNode::setMapNode( MapNode* mapNode )
{
osg::ref_ptr<MapNode> oldMapNode = getMapNode();
if ( oldMapNode.valid() )
{
if ( _terrainCallback.valid() )
{
oldMapNode->getTerrain()->removeTerrainCallback( _terrainCallback.get() );
}
if ( mapNode )
{
mapNode->getTerrain()->addTerrainCallback( _terrainCallback.get() );
}
}
LocalizedNode::setMapNode( mapNode );
}
void
PolyhedralLineOfSightNode::setDistance( const Distance& value )
{
_distance = value;
recalculateExtent();
updateSamples();
}
void
PolyhedralLineOfSightNode::setAzimuthalRange(const Angle& start,
const Angle& end)
{
_startAzim = start;
_endAzim = end;
rebuildGeometry();
updateSamples();
}
void
PolyhedralLineOfSightNode::setElevationRange(const Angle& start,
const Angle& end)
{
_startElev = start;
_endElev = end;
rebuildGeometry();
updateSamples();
}
void
PolyhedralLineOfSightNode::setSampleSpacing(const Angle& value)
{
_spacing = value;
rebuildGeometry();
updateSamples();
}
void
PolyhedralLineOfSightNode::terrainChanged(const osgEarth::TileKey& tileKey,
osg::Node* patch)
{
if ( tileKey.getExtent().intersects(_extent) )
{
updateSamples();
}
}
void
PolyhedralLineOfSightNode::traverse(osg::NodeVisitor& nv)
{
osg::Group::traverse( nv );
}
bool
PolyhedralLineOfSightNode::setPosition( const GeoPoint& pos )
{
bool ok = LocalizedNode::setPosition( pos );
recalculateExtent();
updateSamples();
return ok;
}
void
PolyhedralLineOfSightNode::dirty()
{
//todo
}
void
PolyhedralLineOfSightNode::recalculateExtent()
{
// get a local2world matrix for the map position:
GeoPoint absMapPos = _mapPosition;
absMapPos.makeAbsolute( getMapNode()->getTerrain() );
osg::Matrix local2world;
absMapPos.createLocalToWorld( local2world );
// local offsets (east and north)
osg::Vec3d x( _distance.as(Units::METERS), 0.0, 0.0 );
osg::Vec3d y( 0.0, _distance.as(Units::METERS), 0.0 );
// convert these to map coords:
GeoPoint easting, northing;
easting.fromWorld( getMapNode()->getMapSRS(), x * local2world );
northing.fromWorld( getMapNode()->getMapSRS(), y * local2world );
// calculate the offsets:
double d_easting = easting.x() - absMapPos.x();
double d_northing = northing.y() - absMapPos.y();
// update the extent.
_extent = GeoExtent(
getMapNode()->getMapSRS(),
absMapPos.x() - d_easting, absMapPos.y() - d_northing,
absMapPos.x() + d_easting, absMapPos.y() + d_northing );
OE_INFO << LC << "Cached extent = " << _extent.toString() << std::endl;
}
// Builds the initial basic geometry set. This needs to happen (a) on startup, and
// (b) if something changes that would alter the vertex count or unit vector
void
PolyhedralLineOfSightNode::rebuildGeometry()
{
// clear out the node first.
_geode->removeDrawables( 0, _geode->getNumDrawables() );
osg::Geometry* geom = new osg::Geometry();
geom->setUseVertexBufferObjects( true );
osg::Vec3Array* verts = new osg::Vec3Array();
geom->setVertexArray( verts );
verts->getVertexBufferObject()->setUsage(GL_DYNAMIC_DRAW_ARB);
osg::Vec4Array* colors = new osg::Vec4Array();
geom->setColorArray( colors );
geom->setColorBinding( osg::Geometry::BIND_PER_VERTEX );
osg::Vec3Array* normals = new osg::Vec3Array();
geom->setNormalArray( normals );
geom->setNormalBinding( osg::Geometry::BIND_PER_VERTEX );
double azim0 = _startAzim.as(Units::RADIANS);
double azim1 = _endAzim.as(Units::RADIANS);
double elev0 = _startElev.as(Units::RADIANS);
double elev1 = _endElev.as(Units::RADIANS);
double spacing = _spacing.as(Units::RADIANS);
if ( spacing <= 0.0 )
spacing = 0.1;
// the origin point
verts->push_back ( osg::Vec3(0.0f, 0.0f, 0.0f) );
normals->push_back( osg::Vec3(0.0f, 0.0f, 1.0f) );
colors->push_back ( osg::Vec4(1.0f, 1.0f, 0.0f, 1.0f) );
// Build the unit-vector vertex list. Later this will be updated
// in updateGeometry.
_numRows = 0;
bool lastElev = false;
for( double elev = elev0; !lastElev; elev += spacing, _numRows++ )
{
if ( elev >= elev1 )
{
elev = elev1;
lastElev = true;
}
double cos_elev = cos(elev), sin_elev = sin(elev);
_numCols = 0;
bool lastAzim = false;
for( double azim = azim0; !lastAzim; azim += spacing, _numCols++ )
{
if ( azim >= azim1 )
{
azim = azim1;
lastAzim = true;
}
double cos_azim = cos(azim), sin_azim = sin(azim);
double x = cos_elev * sin_azim;
double y = cos_elev * cos_azim;
double z = sin_elev;
verts->push_back ( osg::Vec3(x, y, z) );
normals->push_back( osg::Vec3(x, y, z) );
colors->push_back ( osg::Vec4(0,1,0,0.5f) );
}
}
// Build the primitive sets to render the polyhedron.
// first the walls.
osg::DrawElements* de =
verts->size() > 0xFFFF ? (osg::DrawElements*)new osg::DrawElementsUShort ( GL_TRIANGLES ) :
verts->size() > 0xFF ? (osg::DrawElements*)new osg::DrawElementsUShort( GL_TRIANGLES ) :
(osg::DrawElements*)new osg::DrawElementsUByte ( GL_TRIANGLES );
unsigned rowOffset = 1; // to account for the origin point
OE_NOTICE << LC << "numRows = " << _numRows << ", numCols = " << _numCols << std::endl;
// outer surface
for( unsigned r=0; r<_numRows-1; ++r )
{
for( unsigned c=0; c<_numCols-1; ++c )
{
unsigned i = rowOffset + c;
unsigned i2 = rowOffset + c + _numCols;
de->addElement( i );
de->addElement( i+1 );
de->addElement( i2 );
de->addElement( i2 );
de->addElement( i+1 );
de->addElement( i2+1 );
}
rowOffset += _numCols;
}
#if 1
// top cap
for( unsigned c=0; c<_numCols-1; ++c )
{
de->addElement( 0 );
de->addElement( rowOffset + c + 1 );
de->addElement( rowOffset + c );
}
#endif
geom->addPrimitiveSet( de );
// finally, make the geode and attach it.
_geode->addDrawable( geom );
}
void
PolyhedralLineOfSightNode::updateSamples()
{
if ( _geode->getNumDrawables() == 0 )
rebuildGeometry();
osg::Geometry* geom = _geode->getDrawable(0)->asGeometry();
osg::Vec3Array* verts = dynamic_cast<osg::Vec3Array*>( geom->getVertexArray() );
double distance = _distance.as(Units::METERS);
// get the world coords and a l2w transform for the origin:
osg::Vec3d originWorld;
osg::Matrix local2world, world2local;
Terrain* t = getMapNode()->getTerrain();
GeoPoint origin = getPosition();
origin.makeAbsolute( t );
origin.toWorld( originWorld, t );
origin.createLocalToWorld( local2world );
world2local.invert( local2world );
// set up an intersector:
osgUtil::LineSegmentIntersector* lsi = new osgUtil::LineSegmentIntersector( originWorld, originWorld );
osgUtil::IntersectionVisitor iv( lsi );
// intersect the verts (skip the origin point) with the map node.
for( osg::Vec3Array::iterator v = verts->begin()+1; v != verts->end(); ++v )
{
osg::Vec3d unit = *v;
unit.normalize();
unit *= distance;
osg::Vec3d world = unit * local2world;
if ( osg::equivalent(unit.length(), 0.0) )
{
OE_WARN << "problem." << std::endl;
}
lsi->reset();
lsi->setStart( originWorld );
lsi->setEnd( world );
OE_DEBUG << LC << "Ray: " <<
originWorld.x() << "," << originWorld.y() << "," << originWorld.z() << " => "
<< world.x() << "," << world.y() << "," << world.z()
<< std::endl;
getMapNode()->getTerrain()->accept( iv );
osgUtil::LineSegmentIntersector::Intersections& hits = lsi->getIntersections();
if ( !hits.empty() )
{
const osgUtil::LineSegmentIntersector::Intersection& hit = *hits.begin();
osg::Vec3d newV = hit.getWorldIntersectPoint() * world2local;
if ( newV.length() > 1.0 )
*v = newV;
else
*v = unit;
}
else
{
*v = unit;
}
//OE_NOTICE << "Radial point = " << v->x() << ", " << v->y() << ", " << v->z() << std::endl;
}
verts->dirty();
geom->dirtyBound();
}
| 29.079208 | 107 | 0.602571 | [
"geometry",
"render",
"vector",
"transform"
] |
dd52b1230b2eb8843160ac3f6c9ad598adba345c | 683 | cpp | C++ | FightingGameProject/DevSettings.cpp | RoundBearChoi/CPP_FightingGame | 21d07caab82dd5ee0ad233886a36ef1fe93e25b6 | [
"Unlicense"
] | 8 | 2021-03-08T06:21:13.000Z | 2022-03-04T21:53:37.000Z | FightingGameProject/DevSettings.cpp | RoundBearChoi/CPP_FightingGame | 21d07caab82dd5ee0ad233886a36ef1fe93e25b6 | [
"Unlicense"
] | null | null | null | FightingGameProject/DevSettings.cpp | RoundBearChoi/CPP_FightingGame | 21d07caab82dd5ee0ad233886a36ef1fe93e25b6 | [
"Unlicense"
] | null | null | null | #include "DevSettings.h"
namespace RB
{
RenderMode DevSettings::renderMode = RenderMode::SPRITES_ONLY;
void DevSettings::UpdateDebugBoxSettings()
{
InputData& inputData = *InputData::ptr;
if (inputData.key_f8)
{
if (!inputData.key_f8->processed)
{
inputData.key_f8->processed = true;
ChangeRenderMode();
}
}
}
void DevSettings::ChangeRenderMode()
{
int32_t mode = (int32_t)renderMode;
mode++;
if (mode < 0)
{
mode = (int32_t)RenderMode::COUNT - 1;
}
if (mode >= (int32_t)RenderMode::COUNT)
{
mode = 0;
}
renderMode = (RenderMode)mode;
IF_COUT{ std::cout << "render mode: " << (int32_t)renderMode << std::endl; }
}
} | 16.261905 | 78 | 0.642753 | [
"render"
] |
dd5a5c977211443da238d27855c58704d47c1ed4 | 5,358 | cpp | C++ | MistThread/IO/XML/XMLElement.cpp | Neko81795/CBREngine | 3ea100f09110d55fcbcadb23c246d47ed46c5121 | [
"CC-BY-4.0",
"MIT"
] | 2 | 2015-08-30T00:26:45.000Z | 2015-11-13T05:58:30.000Z | MistThread/IO/XML/XMLElement.cpp | Neko81795/CBREngine | 3ea100f09110d55fcbcadb23c246d47ed46c5121 | [
"CC-BY-4.0",
"MIT"
] | 1 | 2015-11-25T06:28:13.000Z | 2015-11-25T06:30:32.000Z | MistThread/IO/XML/XMLElement.cpp | Neko81795/CBREngine | 3ea100f09110d55fcbcadb23c246d47ed46c5121 | [
"CC-BY-4.0",
"MIT"
] | null | null | null | #include "XMLElement.h"
#include "Core/Exception.h"
namespace MistThread
{
namespace IO
{
namespace XML
{
XMLElement * XMLElement::GetElementByName(const std::string &name)
{
for (unsigned int i = 0; i < Elements.size(); i++)
{
if (Elements[i].Name == name)
return &Elements[i];
}
return nullptr;
}
const XMLElement * XMLElement::GetElementByName(const std::string &name) const
{
for (unsigned int i = 0; i < Elements.size(); i++)
{
if (Elements[i].Name == name)
return &Elements[i];
}
return nullptr;
}
XMLAttributeHandle XMLElement::GetAttributeByName(const std::string &name)
{
for (unsigned int i = 0; i < Attributes.size(); i++)
{
if (Attributes[i].Name == name)
return XMLAttributeHandle(i, this);
}
return XMLAttributeHandle(-1, this);
}
ConstXMLAttributeHandle XMLElement::GetAttributeByName(const std::string & name) const
{
for (unsigned int i = 0; i < Attributes.size(); i++)
{
if (Attributes[i].Name == name)
return ConstXMLAttributeHandle(i, this);
}
return ConstXMLAttributeHandle(-1, this);
}
std::vector<XMLElement *> XMLElement::GetElementsByName(const std::string &name)
{
std::vector<XMLElement*> elements;
for (unsigned int i = 0; i < Elements.size(); i++)
{
if (Elements[i].Name == name)
elements.push_back(&Elements[i]);
}
return elements;
}
std::vector<const XMLElement*> XMLElement::GetElementsByName(const std::string & name) const
{
std::vector<const XMLElement*> elements;
for (unsigned int i = 0; i < Elements.size(); i++)
{
if (Elements[i].Name == name)
elements.push_back(&Elements[i]);
}
return elements;
}
std::vector<XMLAttributeHandle> XMLElement::GetAttributesByName(const std::string &name)
{
std::vector<XMLAttributeHandle> attributes;
for (unsigned int i = 0; i < Attributes.size(); i++)
{
if (Attributes[i].Name == name)
attributes.emplace_back(i, this);
}
return attributes;
}
std::vector<ConstXMLAttributeHandle> XMLElement::GetAttributesByName(const std::string & name) const
{
std::vector<ConstXMLAttributeHandle> attributes;
for (unsigned int i = 0; i < Attributes.size(); i++)
{
if (Attributes[i].Name == name)
attributes.emplace_back(i, this);
}
return attributes;
}
XMLElement* XMLElement::AddElement(const std::string &name)
{
Elements.push_back(XMLElement(name));
return &Elements.back();
}
XMLAttributeHandle XMLElement::AddAttribute(const std::string &name, const std::string& value)
{
Attributes.push_back(XMLAttribute(name, value));
return XMLAttributeHandle(static_cast<int>(Attributes.size()) - 1, this);
}
std::string InsertSpaces(int tabDepth)
{
std::string str;
for (int i = 0; i < tabDepth; i++)
{
str += " ";
}
return str;
}
std::ostream &operator<<(std::ostream &stream, const XMLElement& element)
{
static int tabDepth = 0;
stream << InsertSpaces(tabDepth) << "<" << element.Name;
++tabDepth;
for (unsigned int i = 0; i < element.Attributes.size(); i++)
{
stream << " " << element.Attributes[i].Name << "=\"" << element.Attributes[i].Value << "\"";
}
if (element.Elements.size() == 0)
{
stream << "/>" << std::endl;
--tabDepth;
}
else
{
stream << ">" << std::endl;
for (unsigned int i = 0; i < element.Elements.size(); i++)
{
stream << element.Elements[i];
}
--tabDepth;
stream << InsertSpaces(tabDepth) << "</" << element.Name << ">" << std::endl;
}
return stream;
}
XMLElement::XMLElement(const std::string &name)
{
Name = name;
}
XMLElement::~XMLElement()
{
}
XMLAttributeHandle::XMLAttributeHandle(int index, XMLElement* element) : Index(index), Element(element) { }
XMLAttribute & XMLAttributeHandle::operator*()
{
return Element->Attributes[Index];
}
XMLAttribute XMLAttributeHandle::operator*() const
{
return Element->Attributes[Index];
}
XMLAttribute * XMLAttributeHandle::operator->()
{
return &Element->Attributes[Index];
}
XMLAttribute const * XMLAttributeHandle::operator->() const
{
return &Element->Attributes[Index];;
}
ConstXMLAttributeHandle::ConstXMLAttributeHandle(int index, XMLElement const* element) : Index(index), Element(element) {}
XMLAttribute ConstXMLAttributeHandle::operator*() const
{
return Element->Attributes[Index];
}
XMLAttribute const * ConstXMLAttributeHandle::operator->() const
{
return &Element->Attributes[Index];;
}
}
}
}
| 27.19797 | 128 | 0.550765 | [
"vector"
] |
e5857bbec0f644f6dbcc1932992792b9eb523e2a | 8,669 | cc | C++ | test/min_acc_test.cc | RobertLWalton/min | 763bb5cf7cc72218831da2da685e8e5aa6e1408f | [
"Unlicense"
] | null | null | null | test/min_acc_test.cc | RobertLWalton/min | 763bb5cf7cc72218831da2da685e8e5aa6e1408f | [
"Unlicense"
] | null | null | null | test/min_acc_test.cc | RobertLWalton/min | 763bb5cf7cc72218831da2da685e8e5aa6e1408f | [
"Unlicense"
] | null | null | null | // MIN Language Allocator/Collector/Compactor Test
// Program
//
// File: min_acc_test.cc
// Author: Bob Walton (walton@acm.org)
// Date: Fri May 24 15:22:55 EDT 2019
//
// The authors have placed this program in the public
// domain; they make no warranty and accept no liability
// for this program.
// Table of Contents:
//
// Setup
// ACC Interface Test
// ACC Garbage Collector Test
// Setup
// -----
# include <iostream>
# include <iomanip>
# include <cstdlib>
# include <cstring>
using std::cout;
using std::endl;
using std::hex;
using std::dec;
using std::ostream;
# define MIN_ASSERT MIN_ASSERT_CALL_ALWAYS
# include <min.h>
# include <min_acc.h>
# define MUP min::unprotected
# define MINT min::internal
# define MACC min::acc
// ACC Interface Test
//
void test_acc_interface ( void )
{
cout << endl;
cout << "Start Allocator/Collector/Compactor"
" Interface Test!" << endl;
cout << endl;
cout << "Test stub allocator functions:"
<< endl;
min::unsptr sbase = MUP::acc_stubs_allocated;
cout << "initial stubs allocated = "
<< sbase << endl;
min::stub * stub1 = MUP::new_acc_stub();
MIN_CHECK ( stub1 == MINT::last_allocated_stub );
MIN_CHECK ( MUP::acc_stubs_allocated == sbase + 1 );
MIN_CHECK
( min::type_of ( stub1 ) == min::ACC_FREE );
min::stub * stub2 = MUP::new_acc_stub();
MIN_CHECK ( stub2 == MINT::last_allocated_stub );
MIN_CHECK ( MUP::acc_stubs_allocated == sbase + 2 );
MIN_CHECK
( min::type_of ( stub2 ) == min::ACC_FREE );
min::unsptr free_stubs = MINT::number_of_free_stubs;
MINT::acc_expand_stub_free_list ( free_stubs + 2 );
MIN_CHECK ( MINT::number_of_free_stubs
>= free_stubs + 2 );
MIN_CHECK ( MUP::acc_stubs_allocated == sbase + 2 );
MIN_CHECK ( stub2 == MINT::last_allocated_stub );
min::stub * stub3 = MUP::new_acc_stub();
MIN_CHECK ( MUP::acc_stubs_allocated == sbase + 3 );
MIN_CHECK ( stub3 == MINT::last_allocated_stub );
min::stub * stub4 = MUP::new_acc_stub();
MIN_CHECK ( MUP::acc_stubs_allocated == sbase + 4 );
MIN_CHECK
( stub4 == MINT::last_allocated_stub );
cout << endl;
cout << "Test body allocator functions:"
<< endl;
cout << "MINT::min_fixed_block_size = "
<< MINT::min_fixed_block_size
<< " MINT::max_fixed_block_size = "
<< MINT::max_fixed_block_size
<< endl;
MUP::new_body ( stub1, 128 );
char * p1 = (char *) MUP::ptr_of ( stub1 );
memset ( p1, 0xBB, 128 );
MUP::new_body ( stub2, 128 );
char * p2 = (char *) MUP::ptr_of ( stub2 );
memset ( p2, 0xBB, 128 );
MIN_CHECK ( memcmp ( p1, p2, 128 ) == 0 );
MIN_CHECK ( p1 != p2 );
MUP::new_body ( stub3, 128 );
char * p3 = (char *) MUP::ptr_of ( stub3 );
memset ( p3, 0xCC, 128 );
MUP::new_body ( stub4, 128 );
char * p4 = (char *) MUP::ptr_of ( stub4 );
memset ( p4, 0xCC, 128 );
MIN_CHECK ( memcmp ( p3, p4, 128 ) == 0 );
MIN_CHECK ( p3 != p4 );
min::stub * stub5 = MUP::new_acc_stub();
MUP::new_body ( stub5, 128 );
char * p5 = (char *) MUP::ptr_of ( stub5 );
memset ( p5, 0xCC, 128 );
MIN_CHECK ( memcmp ( p3, p5, 128 ) == 0 );
{
MUP::resize_body rb ( stub5, 128, 128 );
memcpy ( MUP::new_body_ptr_ref ( rb ),
MUP::ptr_of ( stub5 ), 128 );
}
char * p6 = (char *) MUP::ptr_of ( stub5 );
MIN_CHECK ( memcmp ( p3, p6, 128 ) == 0 );
MIN_CHECK ( p5 != p6 );
MUP::deallocate_body ( stub5, 128 );
MIN_CHECK ( min::type_of ( stub5 )
== min::DEALLOCATED );
char * p7 = (char *) MUP::ptr_of ( stub5 );
MIN_CHECK ( p6 != p7 );
min::deallocate ( stub1 );
min::deallocate ( stub2 );
min::deallocate ( stub3 );
min::deallocate ( stub4 );
cout << endl;
cout << "Finish Allocator/Collector/Compactor"
" Interface Test!" << endl;
}
// ACC Garbage Collector Test
// --- ------- --------- ----
static min::locatable_gen teststr;
// Set to "this is a test str" before GC and
// checked after GC.
// Helper functions for tests.
struct print_gen {
min::gen g;
print_gen ( min::gen g ) : g ( g ) {}
friend ostream & operator <<
( ostream & s, print_gen pg )
{
return s << hex
<< min::unprotected::value_of ( pg.g )
<< dec;
}
};
// Compute a random number.
// Multiply with carry algorithm of George Marsaglia.
//
static min::uns32 m_z = 789645;
static min::uns32 m_w = 6793764;
static min::uns32 random_uns32 ( void )
{
m_z = 36969 * ( m_z & 0xFFFF ) + ( m_z >> 16 );
m_w = 18000 * ( m_w & 0xFFFF ) + ( m_w >> 16 );
return ( m_z << 16 ) + m_w;
}
// Create an object of size
//
// 2 + ( random_uns32() % m ).
//
// Set element j equal to j, fo j = 0, 1, ...
//
static min::gen create_object ( min::unsptr m )
{
bool print_save = min::assert_print;
min::assert_print = false;
min::unsptr size = 2 + random_uns32() % m;
min::locatable_gen obj;
obj = min::new_obj_gen ( size );
min::obj_vec_insptr ep ( obj );
for ( min::unsptr j = 0; j < size; ++ j )
min::attr_push(ep) = min::new_num_gen ( j );
min::assert_print = print_save;
return obj;
}
// Create an object that is a vector of n new objects
// each created by calling create_object(m).
//
static min::gen create_vec_of_objects
( min::unsptr n, min::unsptr m )
{
bool print_save = min::assert_print;
min::assert_print = false;
min::locatable_gen obj;
obj = min::new_obj_gen ( n );
min::obj_vec_insptr vp ( obj );
for ( min::unsptr i = 0; i < n; ++ i )
min::attr_push(vp) = create_object ( m );
min::assert_print = print_save;
return obj;
}
// Given an object created by create_vec_of_objects,
// randomly deallocate an element and allocate a
// replacement using create_object(m). Do this n times.
//
static void random_deallocate
( min::gen obj, min::unsptr n, min::unsptr m )
{
bool print_save = min::assert_print;
min::assert_print = false;
min::obj_vec_updptr vp ( obj );
min::unsptr size = min::attr_size_of ( vp );
while ( n -- )
{
min::unsptr i = random_uns32() % size;
min::deallocate
( MUP::stub_of ( min::attr ( vp, i ) ) );
min::attr ( vp, i ) = create_object ( m );
}
min::assert_print = print_save;
}
// Check an object created by create_vec_of_objects.
// Return true if object checks and false if it does
// not.
//
static bool check_vec_of_objects ( min::gen obj )
{
bool print_save = min::assert_print;
min::assert_print = false;
bool checks = true;
min::obj_vec_ptr vp ( obj );
for ( min::unsptr i = 0;
checks && i < min::attr_size_of ( vp );
++ i )
{
min::gen element = min::attr ( vp, i );
min::obj_vec_ptr ep ( element );
for ( min::unsptr j = 0;
j < min::attr_size_of ( ep ); ++ j )
{
min::gen value = min::new_num_gen ( j );
if ( min::attr ( ep, j ) != value )
{
cout << "check_vec_of_objects FAILURE:"
<< endl
<< " object[" << i << "][0] = "
<< value
<< " != "
<< min::attr ( ep, j )
<< " = object[" << i << "][" << j
<< "]" << endl;
checks = false;
break;
}
}
}
min::assert_print = print_save;
return checks;
}
void test_acc_garbage_collector ( void )
{
cout << endl;
cout << "Start ACC Garbage Collector Test!" << endl;
try {
cout << "Before Allocation" << endl;
MACC::print_acc_statistics ( cout );
::teststr = min::new_str_gen
( "this is a test str" );
min::locatable_gen v;
v = create_vec_of_objects ( 1000, 300 );
MIN_CHECK ( check_vec_of_objects ( v ) );
cout << "After Allocation" << endl;
MACC::print_acc_statistics ( cout );
random_deallocate ( v, 100000, 300 );
MIN_CHECK ( check_vec_of_objects ( v ) );
cout << "After Random Deallocation" << endl;
MACC::print_acc_statistics ( cout );
MACC::collect ( MACC::ephemeral_levels );
MIN_CHECK ( check_vec_of_objects ( v ) );
cout << "After Highest Level GC" << endl;
MACC::print_acc_statistics ( cout );
MIN_CHECK
( ::teststr
== min::new_str_gen
( "this is a test str" ) );
} catch ( min::assert_exception * x ) {
cout << "EXITING BECAUSE OF FAILED MIN_CHECK"
<< endl;
exit ( 1 );
}
cout << endl;
cout << "Finish ACC Garbage Collector Test!"
<< endl;
}
// Main Program
// ---- -------
int main ()
{
min::assert_err = stdout;
min::assert_print = true;
cout << endl;
cout << "Initialize!" << endl;
min::interrupt();
test_acc_interface();
test_acc_garbage_collector();
}
| 25.497059 | 56 | 0.589572 | [
"object",
"vector"
] |
e58a84fec4117bd47f043245cd4ae467b465c86e | 4,473 | cpp | C++ | Street Fighter II/Street-Fighter-II/ModuleInput.cpp | PolGannau/RepeatersStudio | cfc5fec038dddd67c9b9b3bf98a1ac684f0f39db | [
"MIT"
] | null | null | null | Street Fighter II/Street-Fighter-II/ModuleInput.cpp | PolGannau/RepeatersStudio | cfc5fec038dddd67c9b9b3bf98a1ac684f0f39db | [
"MIT"
] | null | null | null | Street Fighter II/Street-Fighter-II/ModuleInput.cpp | PolGannau/RepeatersStudio | cfc5fec038dddd67c9b9b3bf98a1ac684f0f39db | [
"MIT"
] | 1 | 2019-06-10T20:48:03.000Z | 2019-06-10T20:48:03.000Z | #include "Globals.h"
#include "Application.h"
#include "ModuleInput.h"
#include "../SDL/include/SDL.h"
ModuleInput::ModuleInput() : Module()
{
for (uint i = 0; i < MAX_KEYS; ++i)
keyboard[i] = KEY_IDLE;
for (uint i = 0; i < SDL_CONTROLLER_BUTTON_MAX; ++i)
Controller1[i] = KEY_IDLE;
for (uint i = 0; i <SDL_CONTROLLER_BUTTON_MAX; ++i)
Controller2[i] = KEY_IDLE;
int i = 0;
stringbutton[0] = SDL_CONTROLLER_BUTTON_A; ++i;
stringbutton[0 + i] = SDL_CONTROLLER_BUTTON_B; ++i;
stringbutton[0 + i] = SDL_CONTROLLER_BUTTON_X; ++i;
stringbutton[0 + i] = SDL_CONTROLLER_BUTTON_Y; ++i;
stringbutton[0 + i] = SDL_CONTROLLER_BUTTON_BACK; ++i;
stringbutton[0 + i] = SDL_CONTROLLER_BUTTON_GUIDE; ++i;
stringbutton[0 + i] = SDL_CONTROLLER_BUTTON_START; ++i;
stringbutton[0 + i] = SDL_CONTROLLER_BUTTON_LEFTSTICK; ++i;
stringbutton[0 + i] = SDL_CONTROLLER_BUTTON_RIGHTSTICK; ++i;
stringbutton[0 + i] = SDL_CONTROLLER_BUTTON_LEFTSHOULDER; ++i;
stringbutton[0 + i] = SDL_CONTROLLER_BUTTON_RIGHTSHOULDER; ++i;
stringbutton[0 + i] = SDL_CONTROLLER_BUTTON_DPAD_UP; ++i;
stringbutton[0 + i] = SDL_CONTROLLER_BUTTON_DPAD_DOWN; ++i;
stringbutton[0 + i] = SDL_CONTROLLER_BUTTON_DPAD_LEFT; ++i;
stringbutton[0 + i] = SDL_CONTROLLER_BUTTON_DPAD_RIGHT; ++i;
}
// Destructor
ModuleInput::~ModuleInput()
{
}
// Called before render is available
bool ModuleInput::Init()
{
LOG("Init SDL input event system");
bool ret = true;
SDL_Init(0);
if (SDL_InitSubSystem(SDL_INIT_EVENTS) < 0)
{
LOG("SDL_EVENTS could not initialize! SDL_Error: %s\n", SDL_GetError());
ret = false;
}
// controller
LOG("Init controller");
if (SDL_InitSubSystem(SDL_INIT_GAMECONTROLLER) < 0)
{
LOG("GamePad controller could not initialize! SDL_Error: %s\n", SDL_GetError());
}
return ret;
}
// Called every draw update
update_status ModuleInput::PreUpdate()
{
SDL_PumpEvents();
const Uint8* keys = SDL_GetKeyboardState(NULL);
for (int i = 0; i < MAX_KEYS; ++i)
{
if (keys[i] == 1)
{
if (keyboard[i] == KEY_IDLE)
keyboard[i] = KEY_DOWN;
else
keyboard[i] = KEY_REPEAT;
}
else
{
if (keyboard[i] == KEY_REPEAT || keyboard[i] == KEY_DOWN)
keyboard[i] = KEY_UP;
else
keyboard[i] = KEY_IDLE;
}
}
//Controller 1 ---------------------------------------------------------------------------------
for (int i = 0; i < SDL_CONTROLLER_BUTTON_MAX; ++i)
{
if (SDL_GameControllerGetButton(controller[0].controller, stringbutton[i]))
{
if (Controller1[i] == KEY_IDLE)
Controller1[i] = KEY_DOWN;
else
Controller1[i] = KEY_REPEAT;
}
else
{
if (Controller1[i] == KEY_REPEAT || Controller1[i] == KEY_DOWN)
Controller1[i] = KEY_UP;
else
Controller1[i] = KEY_IDLE;
}
}
//Controller 2----------------------------------------------------------------------------
for (int i = 0; i < SDL_CONTROLLER_BUTTON_MAX; ++i)
{
if (SDL_GameControllerGetButton(controller[1].controller, stringbutton[i]))
{
if (Controller2[i] == KEY_IDLE)
Controller2[i] = KEY_DOWN;
else
Controller2[i] = KEY_REPEAT;
}
else
{
if (Controller2[i] == KEY_REPEAT || Controller2[i] == KEY_DOWN)
Controller2[i] = KEY_UP;
else
Controller2[i] = KEY_IDLE;
}
}
SDL_PollEvent(&event);
if (event.type == SDL_CONTROLLERDEVICEADDED)
{
for (int i = 0; i < MAX_CONTROLLERS; i++)
{
if (controller[i].controller == nullptr && controller[i].joyId == -1)
{
controller[i].controller = SDL_GameControllerOpen(i);
SDL_Joystick* j = SDL_GameControllerGetJoystick(controller[i].controller);
controller[i].joyId = SDL_JoystickInstanceID(j);
break;
}
}
}
if (event.type == SDL_CONTROLLERDEVICEREMOVED)
{
for (int i = 0; i < MAX_CONTROLLERS; ++i)
{
if (controller[i].joyId == event.cdevice.which)
{
SDL_GameControllerClose(controller[i].controller);
controller[i].controller = nullptr;
controller[i].joyId = -1;
LOG("Disconnected gamepad index: %d", i)
break;
}
}
}
if (event.type == SDL_QUIT)
return update_status::UPDATE_STOP;
if (keyboard[SDL_SCANCODE_ESCAPE])
return update_status::UPDATE_STOP;
return update_status::UPDATE_CONTINUE;
}
// Called before quitting
bool ModuleInput::CleanUp()
{
LOG("Quitting SDL input event subsystem");
SDL_QuitSubSystem(SDL_INIT_EVENTS);
for (int i = 0; i < SDL_NumJoysticks(); ++i) {
if (SDL_IsGameController(i)) {
SDL_GameControllerClose(controller[i].controller);
}
}
return true;
}
| 24.712707 | 97 | 0.653253 | [
"render"
] |
e58ac469326c15230679ca7127b441dceba51ec8 | 23,410 | cpp | C++ | ctsTraffic/ctsMediaStreamServer.cpp | microsoft/ctsTraffic | 00263ffac1d26917933472d75332c0733eb3fc65 | [
"Apache-2.0"
] | 75 | 2019-05-12T15:48:01.000Z | 2022-03-29T16:41:46.000Z | ctsTraffic/ctsMediaStreamServer.cpp | microsoft/ctsTraffic | 00263ffac1d26917933472d75332c0733eb3fc65 | [
"Apache-2.0"
] | 5 | 2020-06-16T00:48:21.000Z | 2022-02-17T18:26:17.000Z | ctsTraffic/ctsMediaStreamServer.cpp | microsoft/ctsTraffic | 00263ffac1d26917933472d75332c0733eb3fc65 | [
"Apache-2.0"
] | 25 | 2019-05-26T08:27:50.000Z | 2022-01-10T04:58:28.000Z | /*
Copyright (c) Microsoft Corporation
All rights reserved.
Licensed under the Apache License, Version 2.0 (the ""License""); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions and limitations under the License.
*/
// cpp headers
#include <memory>
#include <vector>
#include <algorithm>
// os headers
#include <Windows.h>
#include <WinSock2.h>
// wil headers
#include <wil/stl.h>
#include <wil/resource.h>
// ctl headers
#include <ctSockaddr.hpp>
// project headers
#include "ctsConfig.h"
#include "ctsSocket.h"
#include "ctsIOTask.hpp"
#include "ctsWinsockLayer.h"
#include "ctsMediaStreamServer.h"
#include "ctsMediaStreamServerConnectedSocket.h"
#include "ctsMediaStreamServerListeningSocket.h"
#include "ctsMediaStreamProtocol.hpp"
namespace ctsTraffic
{
// Called to 'accept' incoming connections
void ctsMediaStreamServerListener(const std::weak_ptr<ctsSocket>& weakSocket) noexcept
{
try
{
ctsMediaStreamServerImpl::InitOnce();
// ctsMediaStreamServerImpl will complete the ctsSocket object
// when a client request comes in to be 'accepted'
ctsMediaStreamServerImpl::AcceptSocket(weakSocket);
}
catch (...)
{
const auto error = ctsConfig::PrintThrownException();
auto sharedSocket(weakSocket.lock());
if (sharedSocket)
{
sharedSocket->CompleteState(error);
}
}
}
// Called initiate IO on a datagram socket
void ctsMediaStreamServerIo(const std::weak_ptr<ctsSocket>& weakSocket) noexcept
{
const auto sharedSocket(weakSocket.lock());
if (!sharedSocket)
{
return;
}
// hold a reference on the socket
const auto lockedSocket = sharedSocket->AcquireSocketLock();
const auto lockedPattern = lockedSocket.GetPattern();
if (!lockedPattern)
{
return;
}
ctsTask nextTask;
try
{
ctsMediaStreamServerImpl::InitOnce();
do
{
nextTask = lockedPattern->InitiateIo();
if (nextTask.m_ioAction != ctsTaskAction::None)
{
ctsMediaStreamServerImpl::ScheduleIo(weakSocket, nextTask);
}
}
while (nextTask.m_ioAction != ctsTaskAction::None);
}
catch (...)
{
const auto error = ctsConfig::PrintThrownException();
if (nextTask.m_ioAction != ctsTaskAction::None)
{
// must complete any IO that was requested but not scheduled
lockedPattern->CompleteIo(nextTask, 0, error);
if (0 == sharedSocket->GetPendedIoCount())
{
sharedSocket->CompleteState(error);
}
}
}
}
// Called to remove that socket from the tracked vector of connected sockets
void ctsMediaStreamServerClose(const std::weak_ptr<ctsSocket>& weakSocket) noexcept
try
{
ctsMediaStreamServerImpl::InitOnce();
const auto sharedSocket(weakSocket.lock());
if (sharedSocket)
{
ctsMediaStreamServerImpl::RemoveSocket(sharedSocket->GetRemoteSockaddr());
}
}
catch (...)
{
}
namespace ctsMediaStreamServerImpl
{
// function for doing the actual IO for a UDP media stream datagram connection
wsIOResult ConnectedSocketIo(_In_ ctsMediaStreamServerConnectedSocket* connectedSocket) noexcept;
std::vector<std::unique_ptr<ctsMediaStreamServerListeningSocket>> g_listeningSockets; // NOLINT(clang-diagnostic-exit-time-destructors)
wil::critical_section g_socketVectorGuard{ ctsConfig::ctsConfigSettings::c_CriticalSectionSpinlock }; // NOLINT(cppcoreguidelines-interfaces-global-init, clang-diagnostic-exit-time-destructors)
_Guarded_by_(g_socketVectorGuard) std::vector<std::shared_ptr<ctsMediaStreamServerConnectedSocket>> g_connectedSockets; // NOLINT(clang-diagnostic-exit-time-destructors)
// weak_ptr<> to ctsSocket objects ready to accept a connection
_Guarded_by_(g_socketVectorGuard) std::vector<std::weak_ptr<ctsSocket>> g_acceptingSockets; // NOLINT(clang-diagnostic-exit-time-destructors)
// endpoints that have been received from clients not yet matched to ctsSockets
_Guarded_by_(g_socketVectorGuard) std::vector<std::pair<SOCKET, ctl::ctSockaddr>> g_awaitingEndpoints; // NOLINT(clang-diagnostic-exit-time-destructors)
// Singleton values used as the actual implementation for every 'connection'
// ReSharper disable once CppZeroConstantCanBeReplacedWithNullptr
static INIT_ONCE g_initImpl = INIT_ONCE_STATIC_INIT;
static BOOL CALLBACK InitOnceImpl(PINIT_ONCE, PVOID, PVOID*)
{
try
{
// 'listen' to each address
for (const auto& addr : ctsConfig::g_configSettings->ListenAddresses)
{
wil::unique_socket listening(ctsConfig::CreateSocket(addr.family(), SOCK_DGRAM, IPPROTO_UDP, ctsConfig::g_configSettings->SocketFlags));
const auto error = ctsConfig::SetPreBindOptions(listening.get(), addr);
if (error != NO_ERROR)
{
THROW_WIN32_MSG(error, "SetPreBindOptions (ctsMediaStreamServer)");
}
if (SOCKET_ERROR == bind(listening.get(), addr.sockaddr(), addr.length()))
{
THROW_WIN32_MSG(WSAGetLastError(), "bind (ctsMediaStreamServer)");
}
// capture the socket value before moved into the vector
const SOCKET listeningSocketToPrint(listening.get());
g_listeningSockets.emplace_back(
std::make_unique<ctsMediaStreamServerListeningSocket>(std::move(listening), addr));
PRINT_DEBUG_INFO(
L"\t\tctsMediaStreamServer - Receiving datagrams on %ws (%Iu)\n",
addr.WriteCompleteAddress().c_str(),
listeningSocketToPrint);
}
if (g_listeningSockets.empty())
{
throw std::exception("ctsMediaStreamServer invoked with no listening addresses specified");
}
// initiate the recv's in the 'listening' sockets
for (auto& listener : g_listeningSockets)
{
listener->InitiateRecv();
}
}
catch (...)
{
ctsConfig::PrintThrownException();
return FALSE;
}
return TRUE;
}
void InitOnce()
{
if (!InitOnceExecuteOnce(&g_initImpl, InitOnceImpl, nullptr, nullptr))
{
throw std::runtime_error("ctsMediaStreamServerListener could not be instantiated");
}
}
// Schedule the first IO on the specified ctsSocket
void ScheduleIo(const std::weak_ptr<ctsSocket>& weakSocket, const ctsTask& task)
{
auto sharedSocket = weakSocket.lock();
if (!sharedSocket)
{
THROW_WIN32_MSG(WSAECONNABORTED, "ctsSocket already freed");
}
std::shared_ptr<ctsMediaStreamServerConnectedSocket> sharedConnectedSocket;
{
// must guard connected_sockets since we need to add it
const auto lockConnectedObject = g_socketVectorGuard.lock();
// find the matching connected_socket
const auto foundSocket = std::find_if(
std::begin(g_connectedSockets),
std::end(g_connectedSockets),
[&sharedSocket](const std::shared_ptr<ctsMediaStreamServerConnectedSocket>& connectedSocket) noexcept {
return sharedSocket->GetRemoteSockaddr() == connectedSocket->GetRemoteAddress();
}
);
if (foundSocket == std::end(g_connectedSockets))
{
ctsConfig::PrintErrorInfo(
L"ctsMediaStreamServer - failed to find the socket with remote address %ws in our connected socket list to continue sending datagrams",
sharedSocket->GetRemoteSockaddr().WriteCompleteAddress().c_str());
THROW_WIN32_MSG(ERROR_INVALID_DATA, "ctsSocket was not found in the connected sockets to continue sending datagrams");
}
sharedConnectedSocket = *foundSocket;
}
// must call into connected socket without holding a lock
// and without maintaining an iterator into the list
// since the call to schedule_io could end up asking to remove this object from the list
sharedConnectedSocket->ScheduleTask(task);
}
// Process a new ctsSocket from the ctsSocketBroker
// - accept_socket takes the ctsSocket to create a new entry
// which will create a corresponding ctsMediaStreamServerConnectedSocket in the process
void AcceptSocket(const std::weak_ptr<ctsSocket>& weakSocket)
{
auto sharedSocket(weakSocket.lock());
if (sharedSocket)
{
const auto lockAwaitingObject = g_socketVectorGuard.lock();
if (g_awaitingEndpoints.empty())
{
// just add it to our accepting sockets vector under the writer lock
g_acceptingSockets.push_back(weakSocket);
}
else
{
auto waitingEndpoint = g_awaitingEndpoints.rbegin();
const auto existingSocket = std::find_if(
std::begin(g_connectedSockets),
std::end(g_connectedSockets),
[&](const std::shared_ptr<ctsMediaStreamServerConnectedSocket>& connectedSocket) noexcept {
return waitingEndpoint->second == connectedSocket->GetRemoteAddress();
});
if (existingSocket != std::end(g_connectedSockets))
{
ctsConfig::g_configSettings->UdpStatusDetails.m_duplicateFrames.Increment();
PRINT_DEBUG_INFO(L"ctsMediaStreamServer::accept_socket - socket with remote address %ws asked to be Started but was already established",
waitingEndpoint->second.WriteCompleteAddress().c_str());
// return early if this was a duplicate request: this can happen if there is latency or drops
// between the client and server as they attempt to negotiating starting a new stream
return;
}
g_connectedSockets.emplace_back(
std::make_shared<ctsMediaStreamServerConnectedSocket>(
weakSocket,
waitingEndpoint->first,
waitingEndpoint->second,
ConnectedSocketIo));
PRINT_DEBUG_INFO(L"ctsMediaStreamServer::accept_socket - socket with remote address %ws added to connected_sockets",
waitingEndpoint->second.WriteCompleteAddress().c_str());
// now complete the ctsSocket 'Create' request
const auto foundSocket = std::find_if(
g_listeningSockets.begin(),
g_listeningSockets.end(),
[&waitingEndpoint](const std::unique_ptr<ctsMediaStreamServerListeningSocket>& listener) noexcept {
return listener->GetSocket() == waitingEndpoint->first;
});
FAIL_FAST_IF_MSG(
foundSocket == g_listeningSockets.end(),
"Could not find the socket (%Iu) in the waiting_endpoint from our listening sockets (%p)\n",
waitingEndpoint->first, &g_listeningSockets);
sharedSocket->SetLocalSockaddr((*foundSocket)->GetListeningAddress());
sharedSocket->SetRemoteSockaddr(waitingEndpoint->second);
sharedSocket->CompleteState(NO_ERROR);
ctsConfig::PrintNewConnection(sharedSocket->GetLocalSockaddr(), sharedSocket->GetRemoteSockaddr());
// if added to connected_sockets, can then safely remove it from the waiting endpoint
g_awaitingEndpoints.pop_back();
}
}
}
// Process the removal of a connected socket once it is completed
// - remove_socket takes the remote address to find the socket
void RemoveSocket(const ctl::ctSockaddr& targetAddr)
{
const auto lockConnectedObject = g_socketVectorGuard.lock();
const auto foundSocket = std::find_if(
std::begin(g_connectedSockets),
std::end(g_connectedSockets),
[&targetAddr](const std::shared_ptr<ctsMediaStreamServerConnectedSocket>& connectedSocket) noexcept {
return targetAddr == connectedSocket->GetRemoteAddress();
});
if (foundSocket != std::end(g_connectedSockets))
{
g_connectedSockets.erase(foundSocket);
}
}
// Processes the incoming START request from the client
// - if we have a waiting ctsSocket to accept it, will add it to connected_sockets
// - else we'll queue it to awaiting_endpoints
void Start(SOCKET socket, const ctl::ctSockaddr& localAddr, const ctl::ctSockaddr& targetAddr)
{
const auto lockAwaitingObject = g_socketVectorGuard.lock();
const auto existingSocket = std::find_if(
std::begin(g_connectedSockets),
std::end(g_connectedSockets),
[&targetAddr](const std::shared_ptr<ctsMediaStreamServerConnectedSocket>& connectedSocket) noexcept {
return targetAddr == connectedSocket->GetRemoteAddress();
});
if (existingSocket != std::end(g_connectedSockets))
{
ctsConfig::g_configSettings->UdpStatusDetails.m_duplicateFrames.Increment();
PRINT_DEBUG_INFO(L"ctsMediaStreamServer::start - socket with remote address %ws asked to be Started but was already in connected_sockets",
targetAddr.WriteCompleteAddress().c_str());
// return early if this was a duplicate request: this can happen if there is latency or drops
// between the client and server as they attempt to negotiating starting a new stream
return;
}
const auto awaitingEndpoint = std::find_if(
std::begin(g_awaitingEndpoints),
std::end(g_awaitingEndpoints),
[&targetAddr](const std::pair<SOCKET, ctl::ctSockaddr>& endpoint) noexcept {
return targetAddr == endpoint.second;
});
if (awaitingEndpoint != std::end(g_awaitingEndpoints))
{
ctsConfig::g_configSettings->UdpStatusDetails.m_duplicateFrames.Increment();
PRINT_DEBUG_INFO(L"ctsMediaStreamServer::start - socket with remote address %ws asked to be Started but was already in awaiting endpoints",
targetAddr.WriteCompleteAddress().c_str());
// return early if this was a duplicate request: this can happen if there is latency or drops
// between the client and server as they attempt to negotiating starting a new stream
return;
}
// find a ctsSocket waiting to 'accept' a connection and complete it
bool addToAwaiting = true;
while (!g_acceptingSockets.empty())
{
auto weakInstance = *g_acceptingSockets.rbegin();
auto sharedInstance = weakInstance.lock();
if (sharedInstance)
{
// 'move' the accepting socket to connected
g_connectedSockets.emplace_back(
std::make_shared<ctsMediaStreamServerConnectedSocket>(weakInstance, socket, targetAddr, ConnectedSocketIo));
PRINT_DEBUG_INFO(L"ctsMediaStreamServer::start - socket with remote address %ws added to connected_sockets",
targetAddr.WriteCompleteAddress().c_str());
// verify is successfully added to connected_sockets before popping off accepting_sockets
addToAwaiting = false;
g_acceptingSockets.pop_back();
// now complete the accepted ctsSocket back to the ctsSocketState
sharedInstance->SetLocalSockaddr(localAddr);
sharedInstance->SetRemoteSockaddr(targetAddr);
sharedInstance->CompleteState(NO_ERROR);
ctsConfig::PrintNewConnection(localAddr, targetAddr);
break;
}
}
// if we didn't find a waiting connection to accept it, queue it for when one arrives later
if (addToAwaiting)
{
PRINT_DEBUG_INFO(L"ctsMediaStreamServer::start - socket with remote address %ws added to awaiting_endpoints",
targetAddr.WriteCompleteAddress().c_str());
// only queue it if we aren't already waiting on this address
g_awaitingEndpoints.emplace_back(socket, targetAddr);
}
}
wsIOResult ConnectedSocketIo(_In_ ctsMediaStreamServerConnectedSocket* connectedSocket) noexcept
{
const SOCKET socket = connectedSocket->GetSendingSocket();
if (INVALID_SOCKET == socket)
{
return wsIOResult(WSA_OPERATION_ABORTED);
}
const ctl::ctSockaddr& remoteAddr(connectedSocket->GetRemoteAddress());
const ctsTask nextTask = connectedSocket->GetNextTask();
wsIOResult returnResults;
if (ctsTask::BufferType::UdpConnectionId == nextTask.m_bufferType)
{
// making a synchronous call
WSABUF wsabuffer{};
wsabuffer.buf = nextTask.m_buffer;
wsabuffer.len = nextTask.m_bufferLength;
const auto sendResult = WSASendTo(
socket,
&wsabuffer,
1,
&returnResults.m_bytesTransferred,
0,
remoteAddr.sockaddr(),
remoteAddr.length(),
nullptr,
nullptr);
if (SOCKET_ERROR == sendResult)
{
const auto error = WSAGetLastError();
ctsConfig::PrintErrorInfo(
L"WSASendTo(%Iu, %ws) for the Connection-ID failed [%d]",
socket,
remoteAddr.WriteCompleteAddress().c_str(),
error);
return wsIOResult(error);
}
}
else
{
const auto sequenceNumber = connectedSocket->IncrementSequence();
PRINT_DEBUG_INFO(
L"\t\tctsMediaStreamServer sending seq number %lld (%lu bytes)\n",
sequenceNumber,
nextTask.m_bufferLength);
ctsMediaStreamSendRequests sendingRequests(
nextTask.m_bufferLength, // total bytes to send
sequenceNumber,
nextTask.m_buffer);
for (auto& sendRequest : sendingRequests)
{
// making a synchronous call
DWORD bytesSent{};
const auto sendResult = WSASendTo(
socket,
sendRequest.data(),
static_cast<DWORD>(sendRequest.size()),
&bytesSent,
0,
remoteAddr.sockaddr(),
remoteAddr.length(),
nullptr,
nullptr);
if (SOCKET_ERROR == sendResult)
{
const auto error = WSAGetLastError();
if (WSAEMSGSIZE == error)
{
unsigned long bytesRequested = 0;
// iterate across each WSABUF* in the array
for (auto& wasbuffer : sendRequest)
{
bytesRequested += wasbuffer.len;
}
ctsConfig::PrintErrorInfo(
L"WSASendTo(%Iu, seq %lld, %ws) failed with WSAEMSGSIZE : attempted to send datagram of size %u bytes",
socket,
sequenceNumber,
remoteAddr.WriteCompleteAddress().c_str(),
bytesRequested);
}
else
{
ctsConfig::PrintErrorInfo(
L"WSASendTo(%Iu, seq %lld, %ws) failed [%d]",
socket,
sequenceNumber,
remoteAddr.WriteCompleteAddress().c_str(),
error);
}
return wsIOResult(error);
}
// successfully completed synchronously
returnResults.m_bytesTransferred += bytesSent;
}
}
return returnResults;
}
}
}
| 45.812133 | 263 | 0.550363 | [
"object",
"vector"
] |
e58bca88fb8018ddae716cd16ea51f7d51f86047 | 6,807 | cpp | C++ | tests/test_composite_graphs.cpp | kingang1986/purine2 | e53447da173e83fb62bae8cf50bde17f75723203 | [
"BSD-2-Clause"
] | 312 | 2015-03-16T15:29:38.000Z | 2021-09-16T22:48:41.000Z | tests/test_composite_graphs.cpp | zuiwufenghua/purine2 | e53447da173e83fb62bae8cf50bde17f75723203 | [
"BSD-2-Clause"
] | 19 | 2015-03-17T16:20:19.000Z | 2015-10-03T03:34:09.000Z | tests/test_composite_graphs.cpp | zuiwufenghua/purine2 | e53447da173e83fb62bae8cf50bde17f75723203 | [
"BSD-2-Clause"
] | 108 | 2015-03-16T07:07:30.000Z | 2021-08-22T07:32:13.000Z | // Copyright Lin Min 2015
#include <iostream>
#include "catch/catch.hpp"
#include "operations/operation.hpp"
#include "operations/include/random.hpp"
#include "dispatch/op.hpp"
#include "common/common.hpp"
#include "caffeine/math_functions.hpp"
#include "composite/connectable.hpp"
#include "dispatch/runnable.hpp"
#include "dispatch/graph_template.hpp"
#include "composite/graph/copy.hpp"
using namespace std;
using namespace purine;
typedef vector<Blob*> B;
/**
* rank: 0 1
* device: -1, 0, 1 -1, 0, 1
*/
TEST_CASE("TestCopy", "[Copy]") {
Runnable g;
SECTION("Single Copy") {
SECTION("Within rank") {
int rank = current_rank();
/**
* cpu <-> gpu
* (0, -1) -> (0, 0)
* (0, 0) -> (0, -1)
*/
SECTION("cpu <-> gpu") {
Op<Constant>* c = g.create<Constant>("constant", rank, -1, "main",
Constant::param_tuple(2.));
Blob* twos_cpu = g.create("twos_cpu", rank, -1, {1, 10, 10, 10});
Blob* twos_gpu = g.create("twos_gpu", rank, 0, {1, 10, 10, 10});
Blob* dest_cpu = g.create("dest_cpu", rank, -1, {1, 10, 10, 10});
Copy* cp = g.createAny<Copy>("cp", Copy::param_tuple());
Copy* cp2 = g.createAny<Copy>("cp2", Copy::param_tuple());
*c >> B{ twos_cpu } >> *cp >> B{ twos_gpu } >> *cp2 >> B{ dest_cpu };
REQUIRE(cp->nodes().size() == 1);
REQUIRE(cp2->nodes().size() == 1);
REQUIRE(g.nodes().size() == 6);
g.run();
REQUIRE(caffe::purine_cpu_compare(twos_cpu->tensor()->cpu_data(),
dest_cpu->tensor()->cpu_data(),
twos_cpu->tensor()->size().count()));
}
/*
* gpu <-> gpu
* (0, 1) -> (0, 0)
* (0, 0) -> (0, 1)
*/
SECTION("gpu <-> gpu") {
Blob* twos_gpu1 = g.create("twos_gpu1", rank, 0, {1, 10, 10, 10});
Blob* twos_gpu2 = g.create("twos_gpu2", rank, 1, {1, 10, 10, 10});
Copy* cp = g.createAny<Copy>("cp", Copy::param_tuple());
B{ twos_gpu1 } >> *cp >> B{ twos_gpu2 };
// filler
Runnable fill;
Op<Constant>* c1 = fill.create<Constant>("constant1", rank, 0, "main",
Constant::param_tuple(2.));
Op<Constant>* c2 = fill.create<Constant>("constant2", rank, 1, "main",
Constant::param_tuple(2.));
Blob* gpu1 = fill.create("gpu1", twos_gpu1->shared_tensor());
Blob* gpu2 = fill.create("gpu2", twos_gpu2->shared_tensor());
*c1 >> B{ gpu1 };
*c2 >> B{ gpu2 };
REQUIRE(cp->nodes().size() == 1);
REQUIRE(g.nodes().size() == 3);
REQUIRE(fill.nodes().size() == 4);
fill.run();
REQUIRE(!caffe::purine_gpu_compare(gpu1->tensor()->gpu_data(),
gpu2->tensor()->gpu_data(),
gpu1->tensor()->size().count()));
g.run();
REQUIRE(caffe::purine_gpu_compare(twos_gpu1->tensor()->gpu_data(),
twos_gpu2->tensor()->gpu_data(),
twos_gpu1->tensor()->size().count()));
}
/*
* same device
* (0, 0) -> (0, 0)
* (0, -1) -> (0, -1)
*/
SECTION("gpu <-> gpu") {
Blob* gpu = g.create("gpu", rank, 0, {1, 10, 10, 10});
Copy* cp = g.createAny<Copy>("cp", Copy::param_tuple(rank, 0));
B{ gpu } >> *cp;
cp->top();
REQUIRE(cp->top() == B{ gpu });
REQUIRE(g.nodes().size() == 1);
}
}
SECTION("Cross rank") {
/**
* cpu <-> cpu
* (0, -1) <-> (1, -1)
*/
SECTION("cpu <-> cpu") {
Blob* rank1 = g.create("rank1", 0, -1, {1, 10, 10, 10});
Blob* rank2 = g.create("rank2", 1, -1, {1, 10, 10, 10});
Copy* cp = g.createAny<Copy>("cp", Copy::param_tuple());
B{ rank1 } >> *cp >> B{ rank2 };
// filler
Runnable fill;
Op<Constant>* c1 = fill.create<Constant>("constant1", 0, -1, "main",
Constant::param_tuple(2.));
Op<Constant>* c2 = fill.create<Constant>("constant2", 1, -1, "main",
Constant::param_tuple(1.));
Op<Constant>* c3 = fill.create<Constant>("constant3", 1, -1, "main",
Constant::param_tuple(2.));
Blob* r1 = fill.create("r1", rank1->shared_tensor());
Blob* r2 = fill.create("r2", rank2->shared_tensor());
Blob* r3 = fill.create("r3", 1, -1, {1, 10, 10, 10});
*c1 >> B{ r1 };
*c2 >> B{ r2 };
*c3 >> B{ r3 };
print_graph(g.print());
print_graph(fill.print());
// run
fill.run();
if (current_rank() == 1) {
REQUIRE(!caffe::purine_cpu_compare(r2->tensor()->cpu_data(),
r3->tensor()->cpu_data(),
r2->tensor()->size().count()));
}
g.run();
if (current_rank() == 1) {
REQUIRE(caffe::purine_cpu_compare(r2->tensor()->cpu_data(),
r3->tensor()->cpu_data(),
r2->tensor()->size().count()));
}
}
/*
* gpu -> cpu
* (0, 0) -> (1, -1)
*/
/*
* gpu -> gpu
* (0, 0) -> (1, 0)
*/
/*
* cpu -> gpu
* (0, -1) -> (0, 0)
*/
}
}
SECTION("MultiCopy") {
Runnable g;
Runnable fill;
vector<Blob*> r2s;
vector<Blob*> r3s;
for (int i = 0; i < 10; ++i) {
Blob* rank1 = g.create("rank1", 0, -1, {1, 10, 10, 10});
Blob* rank2 = g.create("rank2", 1, -1, {1, 10, 10, 10});
Copy* cp = g.createAny<Copy>("cp", Copy::param_tuple());
B{ rank1 } >> *cp >> B{ rank2 };
// filler
Op<Constant>* c1 = fill.create<Constant>("constant1", 0, -1, "main",
Constant::param_tuple(DTYPE(i)));
Op<Constant>* c2 = fill.create<Constant>("constant2", 1, -1, "main",
Constant::param_tuple(1.414));
Op<Constant>* c3 = fill.create<Constant>("constant3", 1, -1, "main",
Constant::param_tuple(DTYPE(i)));
Blob* r1 = fill.create("r1", rank1->shared_tensor());
Blob* r2 = fill.create("r2", rank2->shared_tensor());
Blob* r3 = fill.create("r3", 1, -1, {1, 10, 10, 10});
*c1 >> B{ r1 };
*c2 >> B{ r2 };
*c3 >> B{ r3 };
r2s.push_back(r2);
r3s.push_back(r3);
}
// run
fill.run();
if (current_rank() == 1) {
for (int i = 0; i < 10; ++i) {
REQUIRE(!caffe::purine_cpu_compare(r2s[i]->tensor()->cpu_data(),
r3s[i]->tensor()->cpu_data(),
r2s[i]->tensor()->size().count()));
}
}
g.run();
if (current_rank() == 1) {
for (int i = 0; i < 10; ++i) {
REQUIRE(caffe::purine_cpu_compare(r2s[i]->tensor()->cpu_data(),
r3s[i]->tensor()->cpu_data(),
r2s[i]->tensor()->size().count()));
}
}
}
}
| 33.204878 | 78 | 0.482885 | [
"vector"
] |
e58e8a74f104b69eda8bb4bfa8093b07850d4ac1 | 822 | cpp | C++ | goost/magma/BlkBackwarded.cpp | DronMDF/goost | 87a21ba383efc12209377ab686df7b93f4297f50 | [
"MIT"
] | 8 | 2017-04-06T20:38:44.000Z | 2022-01-08T09:01:52.000Z | goost/magma/BlkBackwarded.cpp | DronMDF/goost | 87a21ba383efc12209377ab686df7b93f4297f50 | [
"MIT"
] | 364 | 2017-02-16T19:07:32.000Z | 2021-12-23T16:36:43.000Z | goost/magma/BlkBackwarded.cpp | DronMDF/goost | 87a21ba383efc12209377ab686df7b93f4297f50 | [
"MIT"
] | 1 | 2017-10-08T20:46:48.000Z | 2017-10-08T20:46:48.000Z | // Copyright (c) 2017-2021 Andrey Valyaev <dron.valyaev@gmail.com>
//
// This software may be modified and distributed under the terms
// of the MIT license. See the LICENSE file for details.
#include "BlkBackwarded.h"
#include "LazyKey.h"
using namespace std;
using namespace goost::magma;
BlkBackwarded::BlkBackwarded(const shared_ptr<const Block> &block, const shared_ptr<const LazyKey> &key)
: block(block), key(key)
{
}
pair<uint32_t, uint32_t> BlkBackwarded::value() const
{
const auto value = block->value();
uint32_t a = value.first;
uint32_t b = value.second;
b ^= key->transform(a, 7);
a ^= key->transform(b, 6);
b ^= key->transform(a, 5);
a ^= key->transform(b, 4);
b ^= key->transform(a, 3);
a ^= key->transform(b, 2);
b ^= key->transform(a, 1);
a ^= key->transform(b, 0);
return {a, b};
}
| 24.176471 | 104 | 0.677616 | [
"transform"
] |
e59fdec841a11326040d9c9db409aae745506f13 | 438 | cpp | C++ | leetcode.com/0160 Intersection of Two Linked Lists/best.cpp | sky-bro/AC | 29bfa3f13994612887e18065fa6e854b9a29633d | [
"MIT"
] | 1 | 2020-08-20T11:02:49.000Z | 2020-08-20T11:02:49.000Z | leetcode.com/0160 Intersection of Two Linked Lists/best.cpp | sky-bro/AC | 29bfa3f13994612887e18065fa6e854b9a29633d | [
"MIT"
] | null | null | null | leetcode.com/0160 Intersection of Two Linked Lists/best.cpp | sky-bro/AC | 29bfa3f13994612887e18065fa6e854b9a29633d | [
"MIT"
] | 1 | 2022-01-01T23:23:13.000Z | 2022-01-01T23:23:13.000Z | #include <iostream>
#include <vector>
using namespace std;
// Definition for singly-linked list.
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
ListNode *pA = headA, *pB = headB;
while (pA != pB) {
pA = pA ? pA->next : pB;
pB = pB ? pB->next : pA;
}
return pA;
}
};
| 18.25 | 67 | 0.605023 | [
"vector"
] |
e5a9d4e84310102239b60aa7c30758ab7fafb9b3 | 683 | cpp | C++ | Olympiad Programs/Codeforces Training/3A.cpp | mirtaba/ACMICPC-INOI_Archive | ea06e4e40e984f0807410e4f9b5f7042580da2e3 | [
"MIT"
] | 1 | 2020-12-08T11:21:34.000Z | 2020-12-08T11:21:34.000Z | Olympiad Programs/Codeforces Training/3A.cpp | mirtaba/ACMICPC-INOI_Archive | ea06e4e40e984f0807410e4f9b5f7042580da2e3 | [
"MIT"
] | null | null | null | Olympiad Programs/Codeforces Training/3A.cpp | mirtaba/ACMICPC-INOI_Archive | ea06e4e40e984f0807410e4f9b5f7042580da2e3 | [
"MIT"
] | null | null | null | #include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <string>
#include <cctype>
#include <stack>
#include <queue>
#include <list>
#include <vector>
#include <map>
#include <sstream>
#include <cmath>
#include <bitset>
#include <utility>
#include <set>
#include <numeric>
using namespace std;
int main()
{
string s1,s2;
cin >> s1 >> s2;
cout << max(abs(s1[0]-s2[0]) , abs(s1[1]-s2[1])) << endl;
while(s1!=s2)
{
if(s1[0]<s2[0]){cout<<"R";s1[0]++;}
if(s1[0]>s2[0]){cout<<"L";s1[0]--;}
if(s1[1]<s2[1]){cout<<"U";s1[1]++;}
if(s1[1]>s2[1]){cout<<"D";s1[1]--;}
cout<<endl;
}
return 0;
}
| 18.972222 | 61 | 0.551977 | [
"vector"
] |
e5ad205acbef7715a463d0483ad00dc5b3553241 | 3,584 | cpp | C++ | src/strings.cpp | hoathienvu8x/chatmachine | a05e9afd2dabe49e4a61ba97fbd07d2fcd041b89 | [
"Apache-2.0"
] | 4 | 2019-05-01T02:34:17.000Z | 2020-12-27T23:29:45.000Z | src/strings.cpp | hoathienvu8x/chatmachine | a05e9afd2dabe49e4a61ba97fbd07d2fcd041b89 | [
"Apache-2.0"
] | 1 | 2020-03-25T09:14:18.000Z | 2020-03-25T09:14:18.000Z | src/strings.cpp | hoathienvu8x/chatmachine | a05e9afd2dabe49e4a61ba97fbd07d2fcd041b89 | [
"Apache-2.0"
] | 11 | 2019-03-15T07:53:58.000Z | 2022-01-08T03:51:21.000Z | #include "strings.h"
#include "locale"
#include <iostream>
#include <vector>
#include <sstream>
#include <string>
#include <regex>
using namespace std;
void subsitute(string &input, vector<subsitution_t> subs) {
for(int i=0, s=subs.size(); i<s; ++i) {
replace(input, subs[i].input, subs[i].sub);
}
}
void replace(std::string &s, const std::string toReplace, const std::string replaceWith) {
regex re(toReplace);
s = regex_replace(s, re, replaceWith);
}
void insert_spaces(std::string &str) {
str.insert(str.begin(), ' ');
str.insert(str.end(), ' ');
}
void toUpper(std::string &str)
{
std::locale settings;
std::string toUpper;
for(unsigned int i = 0; i < str.size(); ++i)
toUpper += (std::toupper(str[i], settings));
str = toUpper;
}
// removes multi spaces and punctuations
void shrink(std::string &str) {
std::string srk = "";
char prevChar = ' ';
for(int i=0, l=str.length(); i < l; ++i) {
if (str[i] == ' ' && prevChar == ' ')
continue;
else if (isPunc(str[i]) && !isPunc(prevChar))
srk += ' ';
else if (isPunc(str[i]) && isPunc(prevChar)) {
prevChar = str[i];
continue;
} else
srk += str[i];
prevChar = str[i];
}
str = srk;
srk = "";
for(int i=0, l=str.length(); i < l; ++i) {
if (str[i] == ' ' && prevChar == ' ')
continue;
else if (i < l-1 || str[i] != ' ') {
srk += str[i];
}
prevChar = str[i];
}
str = srk;
}
string trim(const string& str)
{
size_t first = str.find_first_not_of(' ');
if (string::npos == first)
{
return str;
}
size_t last = str.find_last_not_of(' ');
return str.substr(first, (last - first + 1));
}
// split str with ' '
vector<string> split(std::string str) {
vector<string> vs;
Split(vs, str, ' ');
return vs;
}
int Split(vector<string>& v, string str, char sep) {
v.clear();
string::size_type stTemp = str.find(sep);
//cout << "Split() : str=" << str << endl;
while(stTemp != string::npos)
{
v.push_back(str.substr(0, stTemp));
str = str.substr(stTemp + 1);
stTemp = str.find(sep);
}
v.push_back(str);
return v.size();
}
bool isPunc(char c) {
std::string puncs = "?!,;.";
return puncs.find(c) != std::string::npos;
}
void transfer(char const *array[], vecstr &vs, int size) {
for (int i=0; i<size; ++i) {
if (array[i] == NULL) {
break;
} else
vs.push_back(array[i]);
}
}
// wikibooks.org
// Levenshtein distance
unsigned int edit_distance(const std::string& s1, const std::string& s2)
{
const std::size_t len1 = s1.size(), len2 = s2.size();
std::vector<std::vector<unsigned int> > d(len1 + 1, std::vector<unsigned int>(len2 + 1));
d[0][0] = 0;
for(unsigned int i = 1; i <= len1; ++i) d[i][0] = i;
for(unsigned int i = 1; i <= len2; ++i) d[0][i] = i;
for(unsigned int i = 1; i <= len1; ++i)
for(unsigned int j = 1; j <= len2; ++j)
// note that std::min({arg1, arg2, arg3}) works only in C++11,
// for C++98 use std::min(std::min(arg1, arg2), arg3)
d[i][j] = std::min(std::min(d[i - 1][j] + 1, d[i][j - 1] + 1), d[i - 1][j - 1] + (s1[i - 1] == s2[j - 1] ? 0 : 1));
return d[len1][len2];
}
void arraycopy(vector<string> src, int srcPos, vector<string> &dest, int destPos, int length) {
for(int i=destPos, j=srcPos; i<destPos+length; ++i, ++j) {
dest[i] = src[j];
}
}
// In MinGW std::to_string() does not exist
//string to_string(int i) {
// stringstream ss;
// ss << i;
// return ss.str();
//}
| 22.540881 | 137 | 0.554967 | [
"vector"
] |
e5adf6fc6ab766039a06909009cea79a491d7e54 | 44,378 | cpp | C++ | libs/sge_engine/src/sge_engine/GameDrawer/DefaultGameDrawer.cpp | ongamex/SGEEngine | de17c10bd880e8175ea01588eeefeb70abfbc3d0 | [
"MIT"
] | 34 | 2021-06-15T10:24:49.000Z | 2022-03-22T19:20:23.000Z | libs/sge_engine/src/sge_engine/GameDrawer/DefaultGameDrawer.cpp | ongamex/SGEEngine | de17c10bd880e8175ea01588eeefeb70abfbc3d0 | [
"MIT"
] | 9 | 2021-03-04T21:34:03.000Z | 2021-05-04T18:33:47.000Z | libs/sge_engine/src/sge_engine/GameDrawer/DefaultGameDrawer.cpp | ongamex/SGEEngine | de17c10bd880e8175ea01588eeefeb70abfbc3d0 | [
"MIT"
] | 2 | 2021-12-29T01:15:22.000Z | 2022-02-01T10:53:15.000Z | #include "sge_engine/GameDrawer/DefaultGameDrawer.h"
#include "sge_core/Camera.h"
#include "sge_core/DebugDraw.h"
#include "sge_core/ICore.h"
#include "sge_core/QuickDraw.h"
#include "sge_core/materials/DefaultPBRMtl/DefaultPBRMtl.h"
#include "sge_core/materials/IMaterial.h"
#include "sge_core/shaders/LightDesc.h"
#include "sge_engine/GameInspector.h"
#include "sge_engine/GameWorld.h"
#include "sge_engine/IWorldScript.h"
#include "sge_engine/Physics.h"
#include "sge_engine/actors/ABlockingObstacle.h"
#include "sge_engine/actors/ACRSpline.h"
#include "sge_engine/actors/ACamera.h"
#include "sge_engine/actors/AInfinitePlaneObstacle.h"
#include "sge_engine/actors/AInvisibleRigidObstacle.h"
#include "sge_engine/actors/ALight.h"
#include "sge_engine/actors/ALine.h"
#include "sge_engine/actors/ALocator.h"
#include "sge_engine/actors/ANavMesh.h"
#include "sge_engine/actors/ASky.h"
#include "sge_engine/traits/TraitModel.h"
#include "sge_engine/traits/TraitParticles.h"
#include "sge_engine/traits/TraitSprite.h"
#include "sge_engine/traits/TraitViewportIcon.h"
#include "sge_utils/math/Frustum.h"
#include "sge_utils/math/color.h"
#include "sge_utils/utils/FileStream.h"
// Caution:
// this include is an exception do not include anything else like it.
#include "../core_shaders/ShadeCommon.h"
//#include "../shaders/FWDDefault_buildShadowMaps.h"
namespace sge {
struct LegacyRenderItem : IRenderItem {
LegacyRenderItem(std::function<void()> drawFn)
: drawFn(drawFn) {
}
std::function<void()> drawFn;
};
vec4f getPrimarySelectionColor() {
const vec4f kPrimarySelectionColor1 = vec4f(0.17f, 0.75f, 0.53f, 1.f);
const vec4f kPrimarySelectionColor2 = vec4f(0.25f, 1.f, 0.63f, 1.f);
float k = 1.f - fabsf(sinf(0.5f * Timer::now_seconds() * pi()));
return lerp(kPrimarySelectionColor1, kPrimarySelectionColor2, k);
}
static inline const vec4f kSecondarySelectionColor = colorFromIntRgba(245, 158, 66, 255);
// Actors forward declaration
struct AInvisibleRigidObstacle;
void DefaultGameDrawer::prepareForNewFrame() {
m_shadingLights.clear();
}
void DefaultGameDrawer::updateShadowMaps(const GameDrawSets& drawSets) {
const std::vector<GameObject*>* const allLights = getWorld()->getObjects(sgeTypeId(ALight));
if (allLights == nullptr) {
return;
}
ICamera* const gameCamera = drawSets.gameCamera;
const Frustum* const gameCameraFrustumWs = drawSets.gameCamera->getFrustumWS();
// Compute All shadow maps.
for (const GameObject* const actorLight : *allLights) {
const ALight* const light = static_cast<const ALight*>(actorLight);
const LightDesc& lightDesc = light->getLightDesc();
const bool isPointLight = lightDesc.type == light_point;
LightShadowInfo& lsi = this->m_perLightShadowFrameTarget[light->getId()];
lsi.isCorrectlyUpdated = false;
if (lightDesc.isOn == false) {
continue;
}
// if the light is not inside the view frsutum do no update its shadow map.
// If the camera frustum is present, try to clip the object.
if (gameCameraFrustumWs != nullptr) {
const AABox3f bboxOS = light->getBBoxOS();
if (!bboxOS.IsEmpty()) {
if (gameCameraFrustumWs->isObjectOrientedBoxOutside(bboxOS, light->getTransform().toMatrix())) {
continue;
}
}
}
// Retrieve the ShadowMapBuildInfo which tells us the cameras to be used for rendering the shadow map.
Optional<ShadowMapBuildInfo> shadowMapBuildInfoOpt = lightDesc.buildShadowMapInfo(light->getTransform(), *gameCameraFrustumWs);
if (shadowMapBuildInfoOpt.isValid() == false) {
continue;
}
// Sanity check.
if (shadowMapBuildInfoOpt->isPointLight != isPointLight) {
sgeAssert(false);
continue;
}
lsi.buildInfo = shadowMapBuildInfoOpt.get();
int shadowMapWidth = lightDesc.shadowMapRes;
int shadowMapHegiht = lightDesc.shadowMapRes;
if (isPointLight) {
// Point light shadow will render a cube map to a single 2D texture.
// The specified shadow map resolution should be the resolution of each side of the cubemap faces.
shadowMapWidth = lightDesc.shadowMapRes * 4;
shadowMapHegiht = lightDesc.shadowMapRes * 3;
}
// Create the appropriatley sized frame target for the shadow map.
GpuHandle<FrameTarget>& shadowFrameTarget = lsi.frameTarget;
const bool shouldCreateNewShadowMapTexture = shadowFrameTarget.IsResourceValid() == false ||
shadowFrameTarget->getWidth() != shadowMapWidth ||
shadowFrameTarget->getHeight() != shadowMapHegiht;
if (shouldCreateNewShadowMapTexture) {
// Caution, TODO: On Safari (the web browser) I've read that it needs a color render target.
// Keep that in mind when testing and developing.
shadowFrameTarget = getCore()->getDevice()->requestResource<FrameTarget>();
shadowFrameTarget->create2D(shadowMapWidth, shadowMapHegiht, TextureFormat::Unknown, TextureFormat::D24_UNORM_S8_UINT);
}
// Draws the shadow map to the created frame target.
const auto drawShadowMapFromCamera = [this, &lsi](const RenderDestination& rendDest, ICamera* gameCamera,
ICamera* drawCamera) -> void {
GameDrawSets drawShadowSets;
drawShadowSets.gameCamera = gameCamera; // The gameplay camera, form where the player is going to look at the scene.
drawShadowSets.drawCamera = drawCamera; // This is the camera that is going to be used for rendering the shadow map.
drawShadowSets.rdest = rendDest;
drawShadowSets.quickDraw = &getCore()->getQuickDraw();
drawShadowSets.shadowMapBuildInfo = &lsi.buildInfo;
drawWorld(drawShadowSets, drawReason_gameplayShadow);
};
// Clear the pre-existing image in the shadow map.
getCore()->getDevice()->getContext()->clearColor(shadowFrameTarget, 0, vec4f(0.f).data);
getCore()->getDevice()->getContext()->clearDepth(shadowFrameTarget, 1.f);
if (shadowMapBuildInfoOpt->isPointLight) {
// Compute the shadow map sub regions to be used a viewport for rendering each face.
const short mapSideRes = short(lightDesc.shadowMapRes);
Rect2s viewports[signedAxis_numElements];
viewports[axis_x_pos] = Rect2s(mapSideRes, mapSideRes, 0, mapSideRes);
viewports[axis_x_neg] = Rect2s(mapSideRes, mapSideRes, 2 * mapSideRes, mapSideRes);
viewports[axis_y_pos] = Rect2s(mapSideRes, mapSideRes, mapSideRes, 0);
viewports[axis_y_neg] = Rect2s(mapSideRes, mapSideRes, mapSideRes, 2 * mapSideRes);
viewports[axis_z_pos] = Rect2s(mapSideRes, mapSideRes, mapSideRes, mapSideRes);
viewports[axis_z_neg] = Rect2s(mapSideRes, mapSideRes, 3 * mapSideRes, mapSideRes);
// Render the scene for each face of the cube map.
// TODO: avoid rendering individual faces that would not cast shadow in the visiable area of the game camera.
for (int iSignedAxis = 0; iSignedAxis < signedAxis_numElements; ++iSignedAxis) {
RenderDestination rdest(getCore()->getDevice()->getContext(), shadowFrameTarget, viewports[iSignedAxis]);
drawShadowMapFromCamera(rdest, gameCamera, &shadowMapBuildInfoOpt->pointLightShadowMapCameras[iSignedAxis]);
}
} else {
// Non-point lights have only one camera that uses the whole texture for storing the shadow map.
RenderDestination rdest(getCore()->getDevice()->getContext(), shadowFrameTarget);
drawShadowMapFromCamera(rdest, gameCamera, &shadowMapBuildInfoOpt->shadowMapCamera);
}
lsi.isCorrectlyUpdated = true;
}
for (const GameObject* actorLight : *allLights) {
const ALight* const light = static_cast<const ALight*>(actorLight);
const LightDesc& lightDesc = light->getLightDesc();
ShadingLightData shadingLight;
if (lightDesc.isOn == false) {
continue;
}
vec3f color = lightDesc.color * lightDesc.intensity;
vec3f position(0.f);
float spotLightCosAngle = 1.f; // Defaults to cos(0)
if (lightDesc.type == light_point) {
position = light->getTransform().p;
} else if (lightDesc.type == light_directional) {
position = -light->getTransformMtx().c0.xyz().normalized0();
} else if (lightDesc.type == light_spot) {
position = light->getTransform().p;
spotLightCosAngle = cosf(lightDesc.spotLightAngle);
} else {
sgeAssert(false);
}
LightShadowInfo& lsi = m_perLightShadowFrameTarget[light->getId()];
if (lightDesc.hasShadows && lsi.isCorrectlyUpdated) {
if (lsi.buildInfo.isPointLight) {
if (lsi.frameTarget.IsResourceValid()) {
shadingLight.shadowMap = lsi.frameTarget->getDepthStencil();
shadingLight.shadowMapProjView =
mat4f::getIdentity(); // Not used for points light. They use the near/far projection settings and linear depth maps
}
} else {
if (lsi.frameTarget.IsResourceValid()) {
shadingLight.shadowMap = lsi.frameTarget->getDepthStencil();
shadingLight.shadowMapProjView = lsi.buildInfo.shadowMapCamera.getProjView();
}
}
}
shadingLight.pLightDesc = &lightDesc;
shadingLight.lightPositionWs = position;
shadingLight.lightDirectionWs = light->getTransformMtx().c0.xyz().normalized0();
shadingLight.lightBoxWs = light->getBBoxOS().getTransformed(light->getTransformMtx());
m_shadingLights.push_back(shadingLight);
}
m_shadingLightPerObject.reserve(m_shadingLights.size());
}
bool DefaultGameDrawer::isInFrustum(const GameDrawSets& drawSets, Actor* actor) const {
// If the camera frustum is present, try to clip the object.
const Frustum* const pFrustum = drawSets.drawCamera->getFrustumWS();
const AABox3f bboxOS = actor->getBBoxOS();
if (pFrustum != nullptr) {
if (!bboxOS.IsEmpty()) {
const transf3d& tr = actor->getTransform();
// We can technically transform the box in world space and then take the bounding sphere, however
// transforming 8 verts is a perrty costly operation (and we do not need all the data).
// So instead of that we "manually compute the sphere here.
// Note: is that really faster?!
vec3f const bboxCenterOS = bboxOS.center();
quatf const bbSpherePosQ = tr.r * quatf(bboxCenterOS * tr.s, 0.f) * conjugate(tr.r);
vec3f const bbSpherePos = bbSpherePosQ.xyz() + tr.p;
float const bbSphereRadius = bboxOS.halfDiagonal().length() * tr.s.componentMaxAbs();
if (pFrustum->isSphereOutside(bbSpherePos, bbSphereRadius)) {
return false;
}
}
}
return true;
}
void DefaultGameDrawer::getLightingForLocation(const AABox3f& bboxWs, ObjectLighting& lighting) {
m_shadingLightPerObject.clear();
// Find all the lights that can affect the area covered by the bounding box.
// Usually this bbox comes from some actor.
for (const ShadingLightData& shadingLight : m_shadingLights) {
if (shadingLight.lightBoxWs.IsEmpty() || shadingLight.lightBoxWs.overlaps(bboxWs)) {
m_shadingLightPerObject.emplace_back(&shadingLight);
}
}
lighting.ppLightData = m_shadingLightPerObject.data();
lighting.lightsCount = int(m_shadingLightPerObject.size());
}
void DefaultGameDrawer::getActorObjectLighting(Actor* actor, ObjectLighting& lighting) {
// Find all the lights that can affect this object.
const AABox3f bboxOS = actor->getBBoxOS();
const AABox3f actorBBoxWs = bboxOS.getTransformed(actor->getTransformMtx());
getLightingForLocation(actorBBoxWs, lighting);
}
void DefaultGameDrawer::getRenderItemsForActor(const GameDrawSets& drawSets, const SelectedItemDirect& item, DrawReason drawReason) {
Actor* actor = item.gameObject ? item.gameObject->getActor() : nullptr;
if (actor == nullptr) {
return;
}
// Check if the actor is in the camera frustum.
// If it isn't don't bother getting any render items.
if (!isInFrustum(drawSets, actor)) {
return;
}
if (TraitModel* const trait = getTrait<TraitModel>(actor); item.editMode == editMode_actors && trait != nullptr) {
trait->getRenderItems(drawReason, m_RIs_geometry);
}
if (TraitSprite* const trait = getTrait<TraitSprite>(actor); item.editMode == editMode_actors && trait != nullptr) {
trait->getRenderItems(drawReason, drawSets, m_RIs_traitSprite);
}
if (TraitParticlesSimple* const trait = getTrait<TraitParticlesSimple>(actor); item.editMode == editMode_actors && trait != nullptr) {
trait->getRenderItems(m_RIs_traitParticles);
}
if (TraitParticlesProgrammable* const trait = getTrait<TraitParticlesProgrammable>(actor);
item.editMode == editMode_actors && trait != nullptr) {
trait->getRenderItems(m_RIs_traitParticlesProgrammable);
}
if (drawReason_IsEditOrSelectionTool(drawReason)) {
if (TraitViewportIcon* const trait = getTrait<TraitViewportIcon>(actor)) {
trait->getRenderItems(m_RIs_traitViewportIcon);
}
}
const TypeId actorType = actor->getType();
if (actorType == sgeTypeId(ACamera) || actorType == sgeTypeId(ALight) || actorType == sgeTypeId(ALine) ||
actorType == sgeTypeId(ACRSpline) || actorType == sgeTypeId(ALocator) || actorType == sgeTypeId(AInvisibleRigidObstacle) ||
actorType == sgeTypeId(AInfinitePlaneObstacle) || actorType == sgeTypeId(ANavMesh)) {
m_RIs_helpers.push_back(HelperDrawRenderItem(item, drawReason));
}
}
vec4f getSelectionTintColor(DrawReason drawReason) {
const bool useWireframe = drawReason_IsVisualizeSelection(drawReason);
const vec4f wireframeColor =
(drawReason == drawReason_visualizeSelectionPrimary) ? getPrimarySelectionColor() : kSecondarySelectionColor;
vec4f selectionTint = useWireframe ? wireframeColor : vec4f(0.f);
selectionTint.w = useWireframe ? 1.f : 0.f;
return selectionTint;
}
void DefaultGameDrawer::drawCurrentRenderItems(const GameDrawSets& drawSets, DrawReason drawReason, bool shouldDrawSky) {
// ObjectLighting is overused for multiple things.
ObjectLighting lighting;
// const bool useWireframe = drawReason_IsVisualizeSelection(drawReason);
// const vec4f wireframeColor =
// (drawReason == drawReason_visualizeSelectionPrimary) ? getPrimarySelectionColor() : kSecondarySelectionColor;
// const int wireframeColorInt = colorToIntRgba(wireframeColor);
// vec4f selectionTint = useWireframe ? wireframeColor : vec4f(0.f);
// selectionTint.w = useWireframe ? 1.f : 0.f;
lighting.ambientLightColor = getWorld()->m_ambientLight * getWorld()->m_ambientLightIntensity;
lighting.ambientFakeDetailBias = getWorld()->m_ambientLightFakeDetailAmount;
// Extract the alpha sorting plane.
const vec3f zSortingPlanePosWs = drawSets.drawCamera->getCameraPosition();
const vec3f zSortingPlaneNormal = drawSets.drawCamera->getCameraLookDir();
const Plane zSortPlane = Plane::FromPosAndDir(zSortingPlanePosWs, zSortingPlaneNormal);
// Gather and sort the render items.
m_RIs_opaque.clear();
m_RIs_alphaSorted.clear();
for (auto& ri : m_RIs_geometry) {
ri.zSortingValue = zSortPlane.Distance(ri.zSortingPositionWs);
if (ri.needsAlphaSorting) {
m_RIs_alphaSorted.push_back(&ri);
} else {
m_RIs_opaque.push_back(&ri);
}
}
for (auto& ri : m_RIs_traitSprite) {
ri.zSortingValue = zSortPlane.Distance(ri.zSortingPositionWs);
if (ri.needsAlphaSorting) {
m_RIs_alphaSorted.push_back(&ri);
} else {
m_RIs_opaque.push_back(&ri);
}
}
for (auto& ri : m_RIs_traitParticles) {
ri.zSortingValue = zSortPlane.Distance(ri.zSortingPositionWs);
if (ri.needsAlphaSorting) {
m_RIs_alphaSorted.push_back(&ri);
} else {
m_RIs_opaque.push_back(&ri);
}
}
for (auto& ri : m_RIs_traitParticlesProgrammable) {
ri.zSortingValue = zSortPlane.Distance(ri.zSortingPositionWs);
if (ri.needsAlphaSorting) {
m_RIs_alphaSorted.push_back(&ri);
} else {
m_RIs_opaque.push_back(&ri);
}
}
for (auto& ri : m_RIs_traitViewportIcon) {
ri.zSortingValue = zSortPlane.Distance(ri.zSortingPositionWs);
if (ri.needsAlphaSorting) {
m_RIs_alphaSorted.push_back(&ri);
} else {
m_RIs_opaque.push_back(&ri);
}
}
for (auto& ri : m_RIs_helpers) {
ri.zSortingValue = zSortPlane.Distance(ri.zSortingPositionWs);
if (ri.needsAlphaSorting) {
m_RIs_alphaSorted.push_back(&ri);
} else {
m_RIs_opaque.push_back(&ri);
}
}
// The opaque items don't need to be sorted in any way for the rendering to appear correct.
// However, if we sort them fron-to-back we would reduce the pixel shader overdraw.
std::sort(m_RIs_opaque.begin(), m_RIs_opaque.end(),
[](IRenderItem* a, IRenderItem* b) -> bool { return a->zSortingValue < b->zSortingValue; });
// Sort the semi-transparent render items as they need to be draw in back-to-front order
// so that the alpha blending and z-depth could be done correctly.
std::sort(m_RIs_alphaSorted.rbegin(), m_RIs_alphaSorted.rend(),
[](IRenderItem* a, IRenderItem* b) -> bool { return a->zSortingValue < b->zSortingValue; });
// Draw the render items.
auto drawRenderItems = [&](std::vector<IRenderItem*>& renderItems) -> void {
for (auto& riRaw : renderItems) {
if (auto geomRi = dynamic_cast<GeometryRenderItem*>(riRaw)) {
// Find all the lights that can affect this object.
ObjectLighting reasonInfo = lighting;
getLightingForLocation(geomRi->bboxWs, reasonInfo);
drawRenderItem_Geometry(*geomRi, drawSets, reasonInfo, drawReason);
} else if (auto riSprite = dynamic_cast<TraitSpriteRenderItem*>(riRaw)) {
// Find all the lights that can affect this object.
ObjectLighting reasonInfo = lighting;
getActorObjectLighting(riSprite->actor, reasonInfo);
drawRenderItem_TraitSprite(*riSprite, drawSets, reasonInfo, drawReason);
} else if (auto riTraitViewportIcon = dynamic_cast<TraitViewportIconRenderItem*>(riRaw)) {
drawRenderItem_TraitViewportIcon(*riTraitViewportIcon, drawSets, drawReason);
} else if (auto riTraitParticles = dynamic_cast<TraitParticlesSimpleRenderItem*>(riRaw)) {
drawRenderItem_TraitParticlesSimple(*riTraitParticles, drawSets, lighting);
} else if (auto riTraitParticlesProgrammable = dynamic_cast<TraitParticlesProgrammableRenderItem*>(riRaw)) {
drawRenderItem_TraitParticlesProgrammable(*riTraitParticlesProgrammable, drawSets, lighting);
} else if (auto riHelper = dynamic_cast<HelperDrawRenderItem*>(riRaw)) {
drawHelperActor(riHelper->item.gameObject->getActor(), drawSets, riHelper->item.editMode, 0, lighting, drawReason);
} else {
sgeAssert(false && "Render Item does not have a drawing implementation");
}
}
};
drawRenderItems(m_RIs_opaque);
// Draw the sky after the opaque objects to reduce the overdraw done by its pixel shader.
// However draw it before the transparent objects, as it might be visible trough them.
if (shouldDrawSky) {
drawSky(drawSets, drawReason);
}
drawRenderItems(m_RIs_alphaSorted);
}
void DefaultGameDrawer::drawItem(const GameDrawSets& drawSets, const SelectedItemDirect& item, DrawReason drawReason) {
clearRenderItems();
getRenderItemsForActor(drawSets, item, drawReason);
drawCurrentRenderItems(drawSets, drawReason, false);
}
void DefaultGameDrawer::drawWorld(const GameDrawSets& drawSets, const DrawReason drawReason) {
clearRenderItems();
// Get the render items for all actors in the scene.
getWorld()->iterateOverPlayingObjects(
[&](GameObject* object) -> bool {
// TODO: Skip this check for whole types. We know they are not actors...
if (Actor* actor = object->getActor()) {
AABox3f actorBboxOS = actor->getBBoxOS();
SelectedItemDirect item;
item.editMode = editMode_actors;
item.gameObject = actor;
getRenderItemsForActor(drawSets, item, drawReason);
}
return true;
},
false);
// Draw the render items.
drawCurrentRenderItems(drawSets, drawReason, true);
// Draw the physics debug draw if enabled.
if (getWorld()->inspector && getWorld()->inspector->m_physicsDebugDrawEnabled) {
drawSets.rdest.sgecon->clearDepth(drawSets.rdest.frameTarget, 1.f);
getWorld()->m_physicsDebugDraw.preDebugDraw(drawSets.drawCamera->getProjView(), drawSets.quickDraw, drawSets.rdest);
getWorld()->physicsWorld.dynamicsWorld->debugDrawWorld();
getWorld()->m_physicsDebugDraw.postDebugDraw();
}
// Call scripts onPostDraw. They might draw stuff themselves (like UI).
if (drawReason == drawReason_gameplay || drawReason == drawReason_editing) {
for (ObjectId scriptObj : getWorld()->m_scriptObjects) {
if (IWorldScript* script = dynamic_cast<IWorldScript*>(getWorld()->getObjectById(scriptObj))) {
script->onPostDraw(drawSets);
}
}
}
// Draw the debug draw commands.
getCore()->getDebugDraw().draw(drawSets.rdest, drawSets.drawCamera->getProjView());
#if 0
// This code here is something needed only for debugging shadow maps.
// I ended up writing this from stach more than 10 times that is why I decided to keep it.
// It basically draws the shadow map of thr 1st light in the top left corner of the game screen.
if (drawReason == drawReason_editing) {
if (m_shadingLights.size() > 0 && m_shadingLights[0].shadowMap) {
drawSets.quickDraw->drawTexture(drawSets.rdest, 0.f, 0.f, 256.f, m_shadingLights[0].shadowMap);
}
}
#endif
}
void DefaultGameDrawer::drawSky(const GameDrawSets& drawSets, const DrawReason drawReason) {
if (drawReason_IsGameOrEditNoShadowPass(drawReason)) {
const std::vector<GameObject*>* allSkies = getWorld()->getObjects(sgeTypeId(ASky));
ASky* const sky = (allSkies && !allSkies->empty()) ? static_cast<ASky*>(allSkies->at(0)) : nullptr;
if (sky) {
SkyShaderSettings skyShaderSettings = sky->getSkyShaderSetting();
mat4f view = drawSets.drawCamera->getView();
mat4f proj = drawSets.drawCamera->getProj();
vec3f camPosWs = drawSets.drawCamera->getCameraPosition();
m_skyShader.draw(drawSets.rdest, camPosWs, view, proj, skyShaderSettings);
} else {
mat4f view = drawSets.drawCamera->getView();
mat4f proj = drawSets.drawCamera->getProj();
vec3f camPosWs = drawSets.drawCamera->getCameraPosition();
SkyShaderSettings skyShaderSettings;
skyShaderSettings.mode = SkyShaderSettings::mode_colorGradinet;
skyShaderSettings.topColor = vec3f(0.75f);
skyShaderSettings.bottomColor = vec3f(0.25f);
m_skyShader.draw(drawSets.rdest, camPosWs, view, proj, skyShaderSettings);
}
}
}
void DefaultGameDrawer::drawRenderItem_Geometry(GeometryRenderItem& ri,
const GameDrawSets& drawSets,
const ObjectLighting& lighting,
DrawReason const drawReason) {
if (ri.geometry == nullptr || ri.pMtlData == nullptr) {
return;
}
const vec3f camPos = drawSets.drawCamera->getCameraPosition();
if (drawReason_IsVisualizeSelection(drawReason)) {
m_constantColorShader.drawGeometry(drawSets.rdest, drawSets.drawCamera->getProjView(), ri.worldTransform, *ri.geometry,
getSelectionTintColor(drawReason), false);
} else if (drawReason == drawReason_gameplayShadow) {
m_shadowMapBuilder.drawGeometry(drawSets.rdest, camPos, drawSets.drawCamera->getProjView(), ri.worldTransform,
*drawSets.shadowMapBuildInfo, *ri.geometry, /* ri.mtl.diffuseTexture*/ nullptr, false);
} else {
drawGeometry(drawSets.rdest, *drawSets.drawCamera, ri.worldTransform, lighting, *ri.geometry, ri.pMtlData, InstanceDrawMods());
}
}
void DefaultGameDrawer::drawRenderItem_TraitSprite(const TraitSpriteRenderItem& ri,
const GameDrawSets& drawSets,
const ObjectLighting& lighting,
DrawReason const drawReason) {
if (ri.spriteTexture == nullptr) {
return;
}
const vec3f camPos = drawSets.drawCamera->getCameraPosition();
Geometry texPlaneGeom = m_texturedPlaneDraw.getGeometry(drawSets.rdest.getDevice());
if (drawReason_IsVisualizeSelection(drawReason)) {
m_constantColorShader.drawGeometry(drawSets.rdest, drawSets.drawCamera->getProjView(), ri.obj2world, texPlaneGeom,
getSelectionTintColor(drawReason), true);
} else if (drawReason == drawReason_gameplayShadow) {
// Shadow maps.
m_shadowMapBuilder.drawGeometry(drawSets.rdest, camPos, drawSets.drawCamera->getProjView(), ri.obj2world,
*drawSets.shadowMapBuildInfo, texPlaneGeom, ri.spriteTexture, ri.forceNoCulling);
} else {
// Gameplay shaded.
DefaultPBRMtlData texPlaneMtl;
texPlaneMtl.diffuseColorSrc = DefaultPBRMtlData::diffuseColorSource_diffuseMap;
texPlaneMtl.diffuseTexture = ri.spriteTexture;
texPlaneMtl.metalness = 0.f;
texPlaneMtl.roughness = 1.f;
texPlaneMtl.forceNoLighting = ri.forceNoLighting;
texPlaneMtl.forceNoLighting = ri.forceNoCulling;
drawGeometry(drawSets.rdest, *drawSets.drawCamera, ri.obj2world, lighting, texPlaneGeom, &texPlaneMtl, InstanceDrawMods());
}
}
void DefaultGameDrawer::drawRenderItem_TraitViewportIcon(TraitViewportIconRenderItem& ri,
const GameDrawSets& drawSets,
const DrawReason& drawReason) {
if (Texture* iconTex = ri.traitIcon->getIconTexture()) {
vec4f tintColor = vec4f(1.f);
if (drawReason == drawReason_visualizeSelectionPrimary)
tintColor = getPrimarySelectionColor();
else if (drawReason == drawReason_visualizeSelection)
tintColor = kSecondarySelectionColor;
const mat4f node2world = ri.traitIcon->computeNodeToWorldMtx(*drawSets.drawCamera);
m_texturedPlaneDraw.draw(drawSets.rdest, drawSets.drawCamera->getProjView() * node2world, iconTex, tintColor);
}
};
void DefaultGameDrawer::drawRenderItem_TraitParticlesSimple(TraitParticlesSimpleRenderItem& ri,
const GameDrawSets& drawSets,
const ObjectLighting& lighting) {
TraitParticlesSimple* traitParticles = ri.traitParticles;
const vec3f camPos = drawSets.drawCamera->getCameraPosition();
for (ParticleGroupDesc& pdesc : traitParticles->m_pgroups) {
if (pdesc.m_visMethod == ParticleGroupDesc::vis_model3D) {
AssetIface_Model3D* modelIface = pdesc.m_particleModel.getAssetInterface<AssetIface_Model3D>();
if (modelIface != nullptr) {
const auto& itr = traitParticles->m_pgroupState.find(pdesc.m_name);
const mat4f n2w = itr->second.getParticlesToWorldMtx();
if (itr != traitParticles->m_pgroupState.end()) {
const ParticleGroupState& pstate = itr->second;
for (const ParticleGroupState::ParticleState& particle : pstate.getParticles()) {
mat4f particleTForm = n2w * mat4f::getTranslation(particle.pos) * mat4f::getScaling(particle.scale);
drawEvalModel(drawSets.rdest, *drawSets.drawCamera, particleTForm, lighting, modelIface->getStaticEval(),
InstanceDrawMods());
}
}
}
} else if (pdesc.m_visMethod == ParticleGroupDesc::vis_sprite) {
const auto& itr = traitParticles->m_pgroupState.find(pdesc.m_name);
if (itr != traitParticles->m_pgroupState.end()) {
const mat4f n2w = mat4f::getIdentity();
ParticleGroupState& pstate = itr->second;
ParticleGroupState::SpriteRendData* srd =
pstate.computeSpriteRenderData(*drawSets.rdest.sgecon, pdesc, *drawSets.drawCamera);
if (srd != nullptr) {
drawGeometry(drawSets.rdest, *drawSets.drawCamera, n2w, lighting, srd->geometry, &srd->material, InstanceDrawMods());
}
}
}
}
}
void DefaultGameDrawer::drawRenderItem_TraitParticlesProgrammable(TraitParticlesProgrammableRenderItem& ri,
const GameDrawSets& drawSets,
const ObjectLighting& lighting) {
TraitParticlesProgrammable* particlesTrait = ri.traitParticles;
const mat4f n2w = particlesTrait->getActor()->getTransformMtx();
const vec3f camPos = drawSets.drawCamera->getCameraPosition();
const vec3f camLookDir = drawSets.drawCamera->getCameraLookDir();
const int numPGroups = particlesTrait->getNumPGroups();
for (int iGroup = 0; iGroup < numPGroups; ++iGroup) {
TraitParticlesProgrammable::ParticleGroup* pgrp = particlesTrait->getPGroup(iGroup);
if (isAssetLoaded(pgrp->spriteTexture, assetIface_model3d)) {
for (const TraitParticlesProgrammable::ParticleGroup::ParticleData& particle : pgrp->allParticles) {
mat4f particleTForm =
mat4f::getTranslation(particle.position) * mat4f::getRotationQuat(particle.spin) * mat4f::getScaling(particle.scale);
drawEvalModel(drawSets.rdest, *drawSets.drawCamera, particleTForm, lighting,
getLoadedAssetIface<AssetIface_Model3D>(pgrp->spriteTexture)->getStaticEval(), InstanceDrawMods());
}
} else {
if (m_partRendDataGen.generate(*pgrp, *drawSets.rdest.sgecon, *drawSets.drawCamera, n2w)) {
const mat4f identity = mat4f::getIdentity();
drawGeometry(drawSets.rdest, *drawSets.drawCamera, identity, lighting, m_partRendDataGen.geometry,
&m_partRendDataGen.material, InstanceDrawMods());
}
}
}
}
void DefaultGameDrawer::drawHelperActor_drawANavMesh(ANavMesh& navMesh,
const GameDrawSets& drawSets,
const ObjectLighting& UNUSED(lighting),
const DrawReason drawReason,
const vec4f wireframeColor) {
// Draw the bounding box of the nav-mesh. This box basically shows where is the area where the nav-mesh is going to be built.
if (drawReason_IsEditOrSelectionTool(drawReason)) {
drawSets.quickDraw->drawWiredAdd_Box(navMesh.getTransformMtx(), colorToIntRgba(wireframeColor));
drawSets.quickDraw->drawWired_Execute(drawSets.rdest, drawSets.drawCamera->getProjView());
}
if (drawReason_IsVisualizeSelection(drawReason)) {
vec4f wireframeColorAlphaFloat = wireframeColor;
wireframeColorAlphaFloat.w = 0.5f;
uint32 wireframeColorAlpha = colorToIntRgba(wireframeColorAlphaFloat);
drawSets.quickDraw->drawWired_Clear();
// A small value that we add to each vertex (in world space) so that the contruction and nav-mesh
// geometry does not end-up z-fighting in the viewport.
// The proper solution would be an actual depth bias, but since this is an editor only (and used usuually only for debug)
// this is a good enough solution.
const vec3f fightingPositionBias = -drawSets.drawCamera->getCameraLookDir() * 0.001f;
for (size_t iTri = 0; iTri < navMesh.m_debugDrawNavMeshTriListWs.size() / 3; ++iTri) {
vec3f a = navMesh.m_debugDrawNavMeshTriListWs[iTri * 3 + 0] + fightingPositionBias;
vec3f b = navMesh.m_debugDrawNavMeshTriListWs[iTri * 3 + 1] + fightingPositionBias;
vec3f c = navMesh.m_debugDrawNavMeshTriListWs[iTri * 3 + 2] + fightingPositionBias;
drawSets.quickDraw->drawSolidAdd_Triangle(a, b, c, wireframeColorAlpha);
drawSets.quickDraw->drawWiredAdd_triangle(a, b, c, colorToIntRgba(wireframeColor));
}
const uint32 buildMeshColorInt = colorIntFromRGBA255(246, 189, 85);
const uint32 buildMeshColorAlphaInt = colorIntFromRGBA255(246, 189, 85, 127);
for (size_t iTri = 0; iTri < navMesh.m_debugDrawNavMeshBuildTriListWs.size() / 3; ++iTri) {
vec3f a = navMesh.m_debugDrawNavMeshBuildTriListWs[iTri * 3 + 0] + fightingPositionBias;
vec3f b = navMesh.m_debugDrawNavMeshBuildTriListWs[iTri * 3 + 1] + fightingPositionBias;
vec3f c = navMesh.m_debugDrawNavMeshBuildTriListWs[iTri * 3 + 2] + fightingPositionBias;
drawSets.quickDraw->drawSolidAdd_Triangle(a, b, c, buildMeshColorAlphaInt);
drawSets.quickDraw->drawWiredAdd_triangle(a, b, c, buildMeshColorInt);
}
drawSets.quickDraw->drawSolid_Execute(drawSets.rdest, drawSets.drawCamera->getProjView(), false,
getCore()->getGraphicsResources().BS_backToFrontAlpha);
drawSets.quickDraw->drawWired_Execute(drawSets.rdest, drawSets.drawCamera->getProjView());
}
}
void DefaultGameDrawer::drawHelperActor(Actor* actor,
const GameDrawSets& drawSets,
EditMode const editMode,
int const itemIndex,
const ObjectLighting& lighting,
DrawReason const drawReason) {
TypeId actorType = actor->getType();
const vec3f camPos = drawSets.drawCamera->getCameraPosition();
const vec3f camLookDir = drawSets.drawCamera->getCameraLookDir();
const bool isVisualizingSelection = drawReason_IsVisualizeSelection(drawReason);
vec4f selectionTint = getSelectionTintColor(drawReason);
const uint32 wireframeColorInt = colorToIntRgba(selectionTint);
// If we are rendering the actor to visualize a selection, show a wireframe representation specifying how the light is oriented, or its
// area of effect.
if (actorType == sgeTypeId(ALight) && drawReason_IsVisualizeSelection(drawReason)) {
if (editMode == editMode_actors) {
drawSets.quickDraw->drawWired_Clear();
const ALight* const light = static_cast<const ALight*>(actor);
const vec3f color = light->getLightDesc().color;
const LightDesc lightDesc = light->getLightDesc();
if (lightDesc.type == light_point) {
const float sphereRadius = maxOf(lightDesc.range, 0.1f);
drawSets.quickDraw->drawWiredAdd_Sphere(actor->getTransformMtx(), wireframeColorInt, sphereRadius, 6);
} else if (lightDesc.type == light_directional) {
const float arrowLength = maxOf(lightDesc.intensity * 10.f, 1.f);
drawSets.quickDraw->drawWiredAdd_Arrow(
actor->getTransform().p, actor->getTransform().p + actor->getTransformMtx().c0.xyz().normalized() * arrowLength,
wireframeColorInt);
} else if (lightDesc.type == light_spot) {
const float coneHeight = maxOf(lightDesc.range, 2.f);
const float coneRadius = tanf(lightDesc.spotLightAngle) * coneHeight;
drawSets.quickDraw->drawWiredAdd_ConeBottomAligned(actor->getTransformMtx() * mat4f::getRotationZ(deg2rad(-90.f)),
wireframeColorInt, coneHeight, coneRadius, 6);
}
drawSets.quickDraw->drawWired_Execute(drawSets.rdest, drawSets.drawCamera->getProjView());
}
} else if (actorType == sgeTypeId(ABlockingObstacle) && editMode == editMode_actors) {
ABlockingObstacle* const simpleObstacle = static_cast<ABlockingObstacle*>(const_cast<Actor*>(actor));
if (simpleObstacle->geometry.hasData()) {
if (drawReason_IsVisualizeSelection(drawReason)) {
m_constantColorShader.drawGeometry(drawSets.rdest, drawSets.drawCamera->getProjView(), simpleObstacle->getTransformMtx(),
simpleObstacle->geometry, selectionTint, false);
} else {
drawGeometry(drawSets.rdest, *drawSets.drawCamera, simpleObstacle->getTransformMtx(), lighting, simpleObstacle->geometry,
&simpleObstacle->material, InstanceDrawMods());
}
}
} else if (actorType == sgeTypeId(ACamera) && drawReason_IsVisualizeSelection(drawReason)) {
if (editMode == editMode_actors) {
if (const TraitCamera* const traitCamera = getTrait<TraitCamera>(actor)) {
const auto intersectPlanes = [](const Plane& p0, const Plane& p1, const Plane& p2) -> vec3f {
// http://www.ambrsoft.com/TrigoCalc/Plan3D/3PlanesIntersection_.htm
float const det = -triple(p0.norm(), p1.norm(), p2.norm()); // Caution: I'm not sure about that minus...
float const x = triple(p0.v4.wyz(), p1.v4.wyz(), p2.v4.wyz()) / det;
float const y = triple(p0.v4.xwz(), p1.v4.xwz(), p2.v4.xwz()) / det;
float const z = triple(p0.v4.xyw(), p1.v4.xyw(), p2.v4.xyw()) / det;
return vec3f(x, y, z);
};
const ICamera* const ifaceCamera = traitCamera->getCamera();
const Frustum* const f = ifaceCamera->getFrustumWS();
if (f) {
const vec3f frustumVerts[8] = {
intersectPlanes(f->t, f->r, f->n), intersectPlanes(f->t, f->l, f->n),
intersectPlanes(f->b, f->l, f->n), intersectPlanes(f->b, f->r, f->n),
intersectPlanes(f->t, f->r, f->f), intersectPlanes(f->t, f->l, f->f),
intersectPlanes(f->b, f->l, f->f), intersectPlanes(f->b, f->r, f->f),
};
const vec3f lines[] = {
// Near plane.
frustumVerts[0],
frustumVerts[1],
frustumVerts[1],
frustumVerts[2],
frustumVerts[2],
frustumVerts[3],
frustumVerts[3],
frustumVerts[0],
// Lines that connect near and far planes.
frustumVerts[4 + 0],
frustumVerts[4 + 1],
frustumVerts[4 + 1],
frustumVerts[4 + 2],
frustumVerts[4 + 2],
frustumVerts[4 + 3],
frustumVerts[4 + 3],
frustumVerts[4 + 0],
// Far plane.
frustumVerts[0],
frustumVerts[4],
frustumVerts[1],
frustumVerts[5],
frustumVerts[2],
frustumVerts[6],
frustumVerts[3],
frustumVerts[7],
};
drawSets.quickDraw->drawWired_Clear();
for (int t = 0; t < SGE_ARRSZ(lines); t += 2) {
drawSets.quickDraw->drawWiredAdd_Line(lines[t], lines[t + 1], wireframeColorInt);
}
drawSets.quickDraw->drawWired_Execute(drawSets.rdest, drawSets.drawCamera->getProjView());
}
}
}
} else if (actorType == sgeTypeId(ALine) && drawReason_IsEditOrSelectionTool(drawReason)) {
const ALine* const spline = static_cast<const ALine*>(actor);
if (editMode == editMode_actors) {
mat4f const obj2world = spline->getTransformMtx();
const int color = drawReason_IsVisualizeSelection(drawReason) ? 0xFF0055FF : 0xFFFFFFFF;
const int numSegments = spline->getNumSegments();
for (int iSegment = 0; iSegment < numSegments; ++iSegment) {
int i0, i1;
if (spline->getSegmentVerts(iSegment, i0, i1) == false) {
sgeAssert(false);
break;
}
// TODO: cache one of the matrix multiplications.
vec3f p0 = mat_mul_pos(obj2world, spline->points[i0]);
vec3f p1 = mat_mul_pos(obj2world, spline->points[i1]);
getCore()->getQuickDraw().drawWiredAdd_Line(p0, p1, color);
getCore()->getQuickDraw().drawWiredAdd_Sphere(mat4f::getTranslation(p0), color, 0.2f, 3);
if (iSegment == numSegments - 1) {
getCore()->getQuickDraw().drawWiredAdd_Sphere(mat4f::getTranslation(p1), color, 0.2f, 3);
}
}
getCore()->getQuickDraw().drawWired_Execute(drawSets.rdest, drawSets.drawCamera->getProjView(), nullptr);
} else if (editMode == editMode_points) {
mat4f const tr = spline->getTransformMtx();
getCore()->getQuickDraw().drawWired_Clear();
getCore()->getQuickDraw().drawWiredAdd_Sphere(tr * mat4f::getTranslation(spline->points[itemIndex]),
isVisualizingSelection ? wireframeColorInt : 0xFFFFFFFF, 0.2f, 3);
getCore()->getQuickDraw().drawWired_Execute(drawSets.rdest, drawSets.drawCamera->getProjView(), nullptr);
}
} else if (actorType == sgeTypeId(ACRSpline) && drawReason_IsEditOrSelectionTool(drawReason)) {
ACRSpline* const spline = static_cast<ACRSpline*>(actor);
mat4f const tr = spline->getTransformMtx();
const float pointScale = spline->getBBoxOS().getTransformed(tr).size().length() * 0.01f;
if (editMode == editMode_actors) {
int color = isVisualizingSelection ? wireframeColorInt : 0xFFFFFFFF;
const float lenPerLine = 1.f;
getCore()->getQuickDraw().drawWired_Clear();
vec3f p0;
spline->evaluateAtDistance(&p0, nullptr, 0.f);
p0 = mat_mul_pos(tr, p0);
for (float t = lenPerLine; t <= spline->totalLength; t += lenPerLine) {
vec3f p1;
spline->evaluateAtDistance(&p1, nullptr, t);
p1 = mat_mul_pos(tr, p1);
getCore()->getQuickDraw().drawWiredAdd_Line(p0, p1, color);
p0 = p1;
}
for (int t = 0; t < spline->getNumPoints(); t++) {
vec3f worldPos = mat_mul_pos(tr, spline->points[t]);
if (t == 0)
getCore()->getQuickDraw().drawWiredAdd_Box(mat4f::getTRS(worldPos, quatf::getIdentity(), vec3f(pointScale)), color);
else
getCore()->getQuickDraw().drawWiredAdd_Sphere(mat4f::getTranslation(worldPos), color, pointScale, 3);
}
getCore()->getQuickDraw().drawWired_Execute(drawSets.rdest, drawSets.drawCamera->getProjView(), nullptr);
} else if (editMode == editMode_points) {
getCore()->getQuickDraw().drawWired_Clear();
getCore()->getQuickDraw().drawWiredAdd_Sphere(tr * mat4f::getTranslation(spline->points[itemIndex]),
isVisualizingSelection ? wireframeColorInt : 0xFFFFFFFF, pointScale, 3);
getCore()->getQuickDraw().drawWired_Execute(drawSets.rdest, drawSets.drawCamera->getProjView(), nullptr);
}
} else if (actorType == sgeTypeId(ALocator) && drawReason_IsEditOrSelectionTool(drawReason)) {
if (editMode == editMode_actors) {
drawSets.quickDraw->drawWired_Clear();
drawSets.quickDraw->drawWiredAdd_Basis(actor->getTransformMtx());
drawSets.quickDraw->drawWiredAdd_Box(actor->getTransformMtx(), wireframeColorInt);
drawSets.quickDraw->drawWired_Execute(drawSets.rdest, drawSets.drawCamera->getProjView());
}
} else if (actorType == sgeTypeId(ABone) && drawReason_IsEditOrSelectionTool(drawReason)) {
if (editMode == editMode_actors) {
drawSets.quickDraw->drawWired_Clear();
ABone* const bone = static_cast<ABone*>(actor);
GameWorld* world = bone->getWorld();
float boneLength = 1.f;
const vector_set<ObjectId>* pChildren = world->getChildensOf(bone->getId());
if (pChildren != nullptr) {
vec3f boneFromWs = bone->getPosition();
const vector_set<ObjectId>& children = *pChildren;
if (children.size() == 1) {
Actor* child = world->getActorById(children.getNth(0));
if (child != nullptr) {
vec3f boneToWs = child->getPosition();
vec3f boneDirVectorWs = (boneToWs - boneFromWs);
if (boneDirVectorWs.lengthSqr() > 1e-6f) {
boneLength = boneDirVectorWs.length();
quatf rotationWs =
quatf::fromNormalizedVectors(vec3f(1.f, 0.f, 0.f), boneDirVectorWs.normalized0(), vec3f(0.f, 0.f, 1.f));
vec3f translWs = boneFromWs;
mat4f visualBoneTransformWs = mat4f::getTRS(translWs, rotationWs, vec3f(1.f));
drawSets.quickDraw->drawWiredAdd_Bone(visualBoneTransformWs, boneDirVectorWs.length(), bone->boneLength,
selectionTint);
}
}
} else {
for (ObjectId childId : children) {
Actor* child = world->getActorById(childId);
if (child != nullptr) {
vec3f boneToWs = child->getPosition();
drawSets.quickDraw->drawWiredAdd_Line(boneFromWs, boneToWs, wireframeColorInt);
}
}
}
}
// Dreaw the location of the bone.
drawSets.quickDraw->drawWiredAdd_Sphere(bone->getTransformMtx(), wireframeColorInt, boneLength / 12.f, 6);
drawSets.quickDraw->drawWired_Execute(drawSets.rdest, drawSets.drawCamera->getProjView(), nullptr,
getCore()->getGraphicsResources().DSS_always_noTest);
}
} else if ((actorType == sgeTypeId(AInvisibleRigidObstacle)) && drawReason_IsEditOrSelectionTool(drawReason)) {
if (editMode == editMode_actors) {
drawSets.quickDraw->drawWired_Clear();
drawSets.quickDraw->drawWiredAdd_Box(actor->getTransformMtx(), actor->getBBoxOS(), wireframeColorInt);
drawSets.quickDraw->drawWired_Execute(drawSets.rdest, drawSets.drawCamera->getProjView());
}
} else if (actorType == sgeTypeId(AInfinitePlaneObstacle) && drawReason_IsEditOrSelectionTool(drawReason)) {
if (editMode == editMode_actors) {
AInfinitePlaneObstacle* plane = static_cast<AInfinitePlaneObstacle*>(actor);
const float scale = plane->displayScale * plane->getTransform().s.componentMaxAbs();
drawSets.quickDraw->drawWired_Clear();
drawSets.quickDraw->drawWiredAdd_Arrow(actor->getPosition(), actor->getPosition() + actor->getDirY() * scale,
wireframeColorInt);
drawSets.quickDraw->drawWiredAdd_Grid(actor->getPosition(), actor->getDirX() * scale, actor->getDirZ() * scale, 1, 1,
wireframeColorInt);
drawSets.quickDraw->drawWired_Execute(drawSets.rdest, drawSets.drawCamera->getProjView());
}
} else if (actorType == sgeTypeId(ANavMesh)) {
if (ANavMesh* navMesh = static_cast<ANavMesh*>(actor)) {
drawHelperActor_drawANavMesh(*navMesh, drawSets, lighting, drawReason, selectionTint);
}
} else {
// Not implemented.
}
}
} // namespace sge
| 43.851779 | 136 | 0.707828 | [
"mesh",
"geometry",
"render",
"object",
"vector",
"transform"
] |
e5b00372b43573c135e5e8808dcaba8c768fd636 | 934 | cpp | C++ | baekjoon/2336/source.cpp | qilip/ACMStudy | c4d6f31b01358ead4959c92f1fac59a3826f3f77 | [
"CC-BY-3.0"
] | 4 | 2020-02-02T08:34:46.000Z | 2021-10-01T11:21:17.000Z | baekjoon/2336/source.cpp | qilip/ACMStudy | c4d6f31b01358ead4959c92f1fac59a3826f3f77 | [
"CC-BY-3.0"
] | 1 | 2021-09-04T14:03:50.000Z | 2021-09-04T14:03:50.000Z | baekjoon/2336/source.cpp | qilip/ACMStudy | c4d6f31b01358ead4959c92f1fac59a3826f3f77 | [
"CC-BY-3.0"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
int n;
int nn[50'0010][3];
vector<pair<int, pair<int, int>>> v;
int tree[100'0010];
void update(int pos, int val){
int idx = pos + n;
tree[idx] = val;
idx >>= 1;
while(idx){
tree[idx] = min(tree[idx<<1], tree[idx<<1|1]);
idx>>=1;
}
}
int query(int c){
int l = 0, r = c;
int cur = 9999'9999;
for(l+=n, r+=n;l<=r; l>>=1, r>>=1){
if(l&1) cur = min(cur, tree[l]);
if(~r&1) cur = min(cur, tree[r]);
l++; r--;
}
return cur;
}
int main(void){
scanf("%d", &n);
fill(tree, tree+100'0008, 9999'9999);
for(int i=0;i<3;i++){
for(int j=0;j<n;j++){
int a;
scanf("%d", &a);
nn[a-1][i] = j;
}
}
for(int i=0;i<n;i++){
v.push_back({nn[i][0], {nn[i][1], nn[i][2]}});
}
sort(v.begin(), v.end());
int ans = 0;
for(auto cur : v){
auto [b, c] = cur.second;
if(query(b) > c) ans++;
update(b, c);
}
printf("%d", ans);
return 0;
} | 16.981818 | 48 | 0.517131 | [
"vector"
] |
e5b0d85d72800df34b8ea6552994bb3408e7052b | 4,587 | cpp | C++ | src/topo/base_topo/BaseTopology.cpp | thillux/topoGen | 219901bda2df2594393dd5f52a6b6e961c59225e | [
"BSD-3-Clause"
] | 3 | 2016-12-27T05:05:56.000Z | 2017-04-28T16:46:01.000Z | src/topo/base_topo/BaseTopology.cpp | thillux/topoGen | 219901bda2df2594393dd5f52a6b6e961c59225e | [
"BSD-3-Clause"
] | null | null | null | src/topo/base_topo/BaseTopology.cpp | thillux/topoGen | 219901bda2df2594393dd5f52a6b6e961c59225e | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright (c) 2013-2015, Michael Grey and Markus Theil
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "BaseTopology.hpp"
#include "geo/CityNode.hpp"
#include "lemon/maps.h"
#include "lemon/connectivity.h"
#include <boost/log/trivial.hpp>
BaseTopology::BaseTopology()
: _graph(new Graph),
_nodeGeoNodeMap(new NodeMap(*_graph)),
_edgeGeoMap(new EdgeMap(*_graph)),
_geoNodeMap(new GeoNodeMap) {
}
Graph::Node BaseTopology::addNode(GeographicNode_Ptr& gNode) {
Graph::Node nd = _graph->addNode();
(*_nodeGeoNodeMap)[nd] = gNode;
(*_geoNodeMap)[gNode->id()] = nd;
return nd;
}
NodeMap_Ptr BaseTopology::getNodeMap() {
return _nodeGeoNodeMap;
}
Graph_Ptr BaseTopology::getGraph() {
return _graph;
}
GeoNodeMap_Ptr BaseTopology::getGeoNodeMap() {
return _geoNodeMap;
}
Graph::Edge BaseTopology::addEdge(Graph::Node& u, Graph::Node& v, GeographicEdge_Ptr& e) {
Graph::Edge edge = _graph->addEdge(u, v);
(*_edgeGeoMap)[edge] = e;
return edge;
}
EdgeMap_Ptr BaseTopology::getEdgeMap() {
return _edgeGeoMap;
}
void BaseTopology::prune() {
// extract the biggest connected component and prune the rest
Graph_Ptr graph = getGraph();
Graph::NodeMap<int> nodeMap(*graph);
int numConnectedComponents = lemon::connectedComponents(*graph, nodeMap);
BOOST_LOG_TRIVIAL(info) << "Graph has " << numConnectedComponents << " components!";
// count members of first component
std::map<int, int> componentCounter;
for (Graph::NodeIt it(*graph); it != lemon::INVALID; ++it) {
componentCounter[nodeMap[it]]++;
}
int maxComponent = 0;
int maxNum = 0;
for (auto p : componentCounter) {
if (p.second > maxNum) {
maxNum = p.second;
maxComponent = p.first;
}
}
std::list<int> nodesToDelete;
for (Graph::NodeIt it(*graph); it != lemon::INVALID; ++it) {
if (nodeMap[it] != maxComponent)
nodesToDelete.push_back(graph->id(it));
}
for (auto id : nodesToDelete) {
graph->erase(graph->nodeFromId(id));
_geoNodeMap->erase(id);
}
}
std::vector<GeographicPositionTuple> BaseTopology::getHighestDegreeNodes(unsigned int amount, bool USonly) {
std::multimap<int, GeographicPositionTuple> degreeMap;
std::vector<GeographicPositionTuple> toReturn;
Graph_Ptr graph = getGraph();
Graph::NodeMap<int> nodeMap(*graph);
for (Graph::NodeIt it(*graph); it != lemon::INVALID; ++it) {
Graph::Node nd(it);
int arcs = lemon::countOutArcs(*graph, nd);
GeographicNode_Ptr& gNode = (*_nodeGeoNodeMap)[nd];
if (dynamic_cast<CityNode*>(gNode.get()) != NULL) {
if (USonly == false || static_cast<CityNode*>(gNode.get())->country() == "United States") {
degreeMap.insert(std::make_pair(arcs, gNode->coord()));
}
}
}
for (unsigned int i = 0; i < amount; ++i) {
toReturn.push_back(degreeMap.rbegin()->second);
degreeMap.erase(std::prev(degreeMap.end()));
}
return toReturn;
}
| 35.835938 | 108 | 0.683453 | [
"vector"
] |
e5b2aa8a0c58f030dc7c5b02a5d76f70ce994c10 | 893 | cpp | C++ | gym/103107/f/f.cpp | GoatGirl98/cf | 4077ca8e0fe29dc2bbb7b60166989857cc062e17 | [
"MIT"
] | null | null | null | gym/103107/f/f.cpp | GoatGirl98/cf | 4077ca8e0fe29dc2bbb7b60166989857cc062e17 | [
"MIT"
] | null | null | null | gym/103107/f/f.cpp | GoatGirl98/cf | 4077ca8e0fe29dc2bbb7b60166989857cc062e17 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
#define watch(x) std::cout << (#x) << " is " << (x) << std::endl
using LL = long long;
std::vector<int> spf(int N) {
std::vector<int> sp(N), p{0, 2};
for (int i = 2; i < N; i += 2) sp[i] = 2;
for (int i = 1; i < N; i += 2) sp[i] = i;
for (int i = 3; i < N; i += 2) {
if (sp[i] == i) p.emplace_back(i);
for (int j = 2, np = p.size(); j < np && p[j] <= sp[i] && i * p[j] < N; ++j) {
sp[i * p[j]] = p[j]; // 注意到sp只被赋值一次
}
}
return sp;
}
int main() {
//freopen("in", "r", stdin);
std::cin.tie(nullptr)->sync_with_stdio(false);
int n;
std::cin >> n;
auto sp = spf(n + 1);
auto f = [&](int x) {
if (x == 1) return 1;
int ans = 1, px = sp[x], cnt = 0;
while (x % px == 0) {
x /= px;
if (cnt) ans *= px;
cnt = !cnt;
}
return ans * x;
};
LL ans = 0;
for (int i = 1; i <= n; ++i) ans += f(i);
std::cout << ans << '\n';
return 0;
} | 23.5 | 80 | 0.459127 | [
"vector"
] |
e5bbe7023df14ec84d2b74058ff52f3bc43755f0 | 12,197 | cpp | C++ | Project.cpp | moinak878/ideal-octo-enigma | 3fcb0ead9eb383262495951c868b8f51b4fbf929 | [
"MIT"
] | 2 | 2019-12-26T08:48:16.000Z | 2020-01-08T10:12:39.000Z | Project.cpp | moinak878/ideal-octo-enigma | 3fcb0ead9eb383262495951c868b8f51b4fbf929 | [
"MIT"
] | null | null | null | Project.cpp | moinak878/ideal-octo-enigma | 3fcb0ead9eb383262495951c868b8f51b4fbf929 | [
"MIT"
] | null | null | null | #include<fstream.h>
#include<conio.h>
#include<stdio.h>
#include<dos.h>
#include<process.h>
#include<string.h>
void enterrecord();
void searchrecord();
void delrecord();
void modifyrecord();
int display();
void display1();
class student //to record temporarily
{
public:
int rollno;
char name[20];
int marks[5], total;
float percentage;
float tot_marks;
float pass_marks;
student()
{
tot_marks=100;
pass_marks=40;
}
void input();
void input1();
void output();
};
void student::input() // first time input
{
total=0;
display();
gotoxy(5,12);
cout<<" ENTER NEW RECORD";
gotoxy(30,7);
cout<<"Enter Roll No : ";
cin>>rollno;
gotoxy(30,9);
cout<<"Enter Name of Student : ";
gets(name);
gotoxy(30,13);
cout<<"Enter marks in 5 subjects out of 100";
gotoxy(30,14);
cout<<"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~";
gotoxy(54,20);
cout<<"Press ENTER to cont......";
gotoxy(30,15);
cout<<"Enter marks in English : ";
cin>>marks[0];
gotoxy(30,15);
cout<<" ";
gotoxy(30,15);
cout<<"Enter marks in Physics : ";
cin>>marks[1];
gotoxy(30,15);
cout<<" ";
gotoxy(30,15);
cout<<"Enter marks in Chemistry : ";
cin>>marks[2];
gotoxy(30,15);
cout<<" ";
gotoxy(30,15);
cout<<"Enter marks in Maths : ";
cin>>marks[3];
gotoxy(30,15);
cout<<" ";
gotoxy(30,15);
cout<<"Enter marks in Computer : ";
cin>>marks[4];
for(int i=0;i<5;i++)
total=total+marks[i];
percentage = total/5.0;
}
void student::input1() // while modifying contents
{
int marks1,marks2,marks3,marks4,marks5,roll;
char nam[30];
total=0;
display();
gotoxy(5,12);
cout<<" ENTER NEW RECORD";
gotoxy(30,7);
cout<<"Enter Roll No(Press -1 ,if Unchanged) : ";
cin>>roll;
if(roll!=-1)
rollno=roll;
gotoxy(30,9);
cout<<"Enter Name of Student :";
gotoxy(30,10);
cout<<"(Press .,if Unchanged) ";
gotoxy(55,9);
gets(nam);
if(strcmp(nam,".")!=0)
strcpy(name,nam);
gotoxy(30,13);
cout<<"Enter marks in 5 subjects(Press -1 ,if Unchanged)";
gotoxy(30,14);
cout<<"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~";
gotoxy(54,20);
cout<<"Press ENTER to cont......";
gotoxy(30,15);
cout<<"Enter marks in English : ";
cin>>marks1;
if(marks1!=-1)
marks[0]=marks1;
gotoxy(30,15);
cout<<" ";
gotoxy(30,15);
cout<<"Enter marks in Physics : ";
cin>>marks2;
if(marks2!=-1)
marks[1]=marks2;
gotoxy(30,15);
cout<<" ";
gotoxy(30,15);
cout<<"Enter marks in Chemistry : ";
cin>>marks3;
if(marks3!=-1)
marks[2]=marks3;
gotoxy(30,15);
cout<<" ";
gotoxy(30,15);
cout<<"Enter marks in Maths : ";
cin>>marks4;
if(marks4!=-1)
marks[3]=marks4;
gotoxy(30,15);
cout<<" ";
gotoxy(30,15);
cout<<"Enter marks in Computer : ";
cin>>marks5;
if(marks5!=-1)
marks[4]=marks5;
for(int i=0;i<5;i++)
total=total+marks[i];
percentage = total/5.0;
}
void student::output() //to display the records
{
clrscr();
display();
gotoxy(5,12);
cout<<"DETAILS OF STUDENT ";
gotoxy(40,6);
cout<<"THE DETAILS OF THE STUDENT ";
for(int i=0;i<53;i++)
{
gotoxy(26+i,8);
cprintf("%c",196);
gotoxy(26+i,10);
cprintf("%c",196);
gotoxy(26+i,18);
cprintf("%c",196);
}
gotoxy(27,9);
cout<<"Student's Name : "<<name;
gotoxy(65,9);
cout<<"Roll No : "<<rollno;
gotoxy(27,11);
cout<<"SUBJECT | "<<"ob. marks" <<"full marks"<<"pass marks";
gotoxy(27,12);
cout<<"ENGLISH | "<<marks[0];
gotoxy(27,13);
cout<<"PHYSICS | "<<marks[1];
gotoxy(27,14);
cout<<"CHEMISTRY | "<<marks[2];
gotoxy(27,15);
cout<<"MATHEMATICS | "<<marks[3];
gotoxy(27,16);
cout<<"COMPUTER | "<<marks[4];
gotoxy(27,20);
cout<<"TOTAL MARKS º";
gotoxy(32,20);
cout<<total;
gotoxy(45,19);
cout<<"PERCENTAGE º";
gotoxy(49,20);
cout<<percentage<<" %";
gotoxy(60,19);
cout<<" STATUS";
gotoxy(52,17);
cout<<"Press Enter to continue.... ";
if(percentage<40)
{
gotoxy(66,20);
cout<<"FAILED";
}
if(percentage>=40 && percentage<60)
{
gotoxy(63,20);
cout<<"PASSED, GRADE C";
}
if(percentage>=60 && percentage<80)
{
gotoxy(63,20);
cout<<"PASSED, GRADE B";
}
if(percentage>=80 && percentage<=100)
{
gotoxy(63,20);
cout<<"PASSED, GRADE A";
}
getch();
}
int display() // prints the main frame
{
clrscr();
int i;
gotoxy(31,2);
cprintf("D.A.V MODEL SCHOOL");
gotoxy(36,3);
cprintf("DURGAPUR");
gotoxy(3,23);
cprintf("Created By: Tamali Kundu,Nunna Lakshmi Saranya,Titas Sarkar,Srijoni Choudhury");
gotoxy(60,24);
cprintf("Computer Science,XII");
textcolor(7);
for(i=1;i<18;i++)
{
gotoxy(25,5+i);
cprintf("%c",179);
}
for(i=1;i<24;i++)
{
if(i==1)
{
gotoxy(2,3+i);
cprintf("%c",201);
}
else
if(i==22)
{
gotoxy(2,3+i);
cprintf("%c",200);
}
else
{
gotoxy(2,3+i);
cprintf("º");
}
}
for(i=1;i<23;i++)
{
if(i==1)
{
gotoxy(80,3+i);
cprintf("%c",187);
}
else
if(i==22)
{
gotoxy(79,3+i);
cprintf("e%c",188);
}
else
{
gotoxy(80,3+i);
cprintf("º");
}
}
for(i=0;i<77;i++)
{
gotoxy(3+i,21);
cprintf("%c",196);
}
_setcursortype(_NOCURSOR);
textcolor(4);
gotoxy(22,4);
cprintf("COMPUTERIZED REPORT CARD GENERATION");
textcolor(10);
gotoxy(5,6);
cprintf("Enter Your choice ");
gotoxy(4,23);
cprintf("%s",__DATE__);
gotoxy(6,23);
textcolor(7);
for(i=3;i<80;i++)
{
gotoxy(i,3);
cprintf("%c",205);
}
for(i=3;i<80;i++)
{
gotoxy(i,5);
cprintf("%c",205);
}
for(i=3;i<80;i++)
{
gotoxy(i,24);
cprintf("%c",205);
}
for(i=5;i<27;i++)
{
gotoxy(i-2,7);
cprintf("%c",196);
}
}
void display2() //first screen
{
int i;
gotoxy(31,2);
cprintf("D.A.V MODEL SCHOOL");
gotoxy(36,3);
cprintf(" DURGAPUR");
gotoxy(3,23);
cprintf("Created By:Tamali Kundu,Nunna Lakshmi Saranya,Titas Sarkar,Srijoni Choudhury ");
gotoxy(60,24);
cprintf("Computer Science,XII");
textcolor(7);
for(i=1;i<24;i++)
{
if(i==1)
{
gotoxy(2,3+i);
cprintf("%c",201);
}
else
if(i==22)
{
gotoxy(2,3+i);
cprintf("%c",200);
}
else
{
gotoxy(2,3+i);
cprintf("º");
}
}
for(i=1;i<23;i++)
{
if(i==1)
{
gotoxy(80,3+i);
cprintf("%c",187);
}
else
if(i==22)
{
gotoxy(79,3+i);
cprintf(" %c",188);
}
else
{
gotoxy(80,3+i);
cprintf("º");
}
}
for(i=0;i<77;i++)
{
gotoxy(3+i,21);
cprintf("%c",196);
}
_setcursortype(_NOCURSOR);
textcolor(4);
gotoxy(22,4);
cprintf("COMPUTERIZED REPORT CARD GENERATION");
textcolor(10);
textcolor(7);
for(i=3;i<80;i++)
{
gotoxy(i,3);
cprintf("%c",205);
}
for(i=3;i<80;i++)
{
gotoxy(i,5);
cprintf("%c",205);
}
for(i=3;i<80;i++)
{
gotoxy(i,24);
cprintf("%c",205);
}
}
void menu()
{
x:
int i,choice=0;
clrscr();
display();
gotoxy(6,9);
cout<<"NEW RECORD";
gotoxy(6,11);
cout<<"SEARCH RECORD";
gotoxy(6,13);
cout<<"DELETE RECORD";
gotoxy(6,15);
cout<<"MODIFY RECORD";
gotoxy(6,17);
cout<<"DISPLAY ALL";
gotoxy(6,19);
cout<<"EXIT";
textcolor(6);
gotoxy(4,9);
cprintf("1");
gotoxy(4,11);
cprintf("2");
gotoxy(4,13);
cprintf("3");
gotoxy(4,15);
cprintf("4");
gotoxy(4,17);
cprintf("5");
gotoxy(4,19);
cprintf("6");
textcolor(7);
gotoxy(35,13);
cout<<" ENTER YOUR CHOICE ";
cin>>choice;
if(choice==1)
enterrecord();
else if(choice==2)
searchrecord();
else if(choice==3)
delrecord();
else if(choice==4)
modifyrecord();
else if(choice==5)
display1();
else if(choice==6)
exit(0);
else
{
clrscr();
display();
gotoxy(5,12);
cout<<" WRONG CHOICE ";
gotoxy(32,12);
cout<<"SORRY,WRONG CHOICE !! ENTER BETWEEN 1 AND 6 ";
gotoxy(54,20);
cout<<"Press ENTER to cont......";
getch();
goto x;
}
}
void display1()
{
clrscr();
student s;
fstream file1("mainfile.dat",ios::binary|ios::in);
while(file1.read((char*)&s,sizeof(s)))
{
s.output();
}
file1.close();
menu();
}
void enterrecord()
{
clrscr();
student s;
fstream file1("mainfile.dat",ios::app|ios::binary|ios::out);
s.input();
file1.write((char*)&s,sizeof(s));
file1.close();
s.output();
menu();
}
void modifyrecord()
{
fstream file1;
clrscr();
display();
gotoxy(5,12);
cout<<" MODIFY RECORD ";
gotoxy(33,12);
cout<<" ENTER RECORD (Roll No) TO MODIFY ";
int r,pos=0;
char found='f';
cin>>r;
file1.open("mainfile.dat",ios::binary|ios::in|ios::out);
clrscr();
student s,ss;
while(!file1.eof())
{
pos=file1.tellg();
file1.read((char*)&s,sizeof(s));
if(s.rollno==r)
{
s.output();
s.input1();
file1.seekg(pos);
file1.write((char*)&s,sizeof(s));
found='t';
break;
}
}
if(found=='f')
{
display();
gotoxy(5,12);
cout<<" MODIFY RECORD ";
gotoxy(33,12);
cout<<" RECORD NOT FOUND !! ";
gotoxy(54,20);
cout<<"Press ENTER to cont......";
getch();
}
file1.seekg(0);
file1.close();
menu();
}
void delrecord()
{
int r;
char found='f',confirm='n';
ifstream file1("mainfile.dat",ios::binary|ios::in);
ofstream file2("temp.dat",ios::binary|ios::out);
student s1,ss;
clrscr();
display();
gotoxy(5,12);
cout<<" DELETE RECORDS ";
gotoxy(33,12);
cout<<"ENTER ROLL NUMBER TO BE DELETED ";
cin>>r;
while(file1.read((char*)&s1,sizeof(s1)))
{
if(s1.rollno==r)
{
//s1.output();
found='t';
display();
gotoxy(5,12);
cout<<" DELETE RECORDS ";
gotoxy(33,12);
cout<<"The Record is Successfully Deleted ....";
gotoxy(54,20);
cout<<"Press ENTER to cont......";
getch();
}
else
file2.write((char *)&s1,sizeof(s1));
}
if(found=='f')
{
display();
gotoxy(5,12);
cout<<" DELETE RECORDS ";
gotoxy(33,12);
cout<<"SORRY,THE RECORD WAS NOT FOUND! ";
gotoxy(54,20);
cout<<"Press ENTER to cont......";
getch();
}
file1.close();
file2.close();
remove("mainfile.dat");
rename("temp.dat","mainfile.dat");
file1.open("mainfile.dat",ios::in);
file1.close();
menu();
}
void searchrecord()
{
clrscr();
int b=0;
student s;
fstream file1("mainfile.dat",ios::binary|ios::in);
display();
gotoxy(5,12);
cout<<" SEARCHED RECORDS ";
gotoxy(30,12);
cout<<"ENTER ROLL NO.OF THE RECORD TO BE SEARCHED ";
int r;
cin>>r;
while( file1.read((char*)&s,sizeof(s)))
{
if(s.rollno==r)
{
clrscr();
s.output();
b++;
//break;
}
}
if(b==0)
{
clrscr();
display();
gotoxy(5,12);
cout<<" SEARCHED RECORDS ";
gotoxy(33,12);
cout<<"SORRY,THE RECORD WAS NOT FOUND!";
gotoxy(54,20);
cout<<"Press ENTER to cont......";
getch();
}
clrscr();
menu();
}
void passw() // checks whether the person is authorized or not
{
char un[30];
gotoxy(30,11);
printf("User Name : ");
gotoxy(30,13);
printf("Passward : ");
gotoxy(42,11);
gets(un);
gotoxy(42,13);
int i=0;
char c,ch[20];
do
{
c=getch();
ch[i++]=c;
if(c==13)
printf(" ");
else
printf("*");
}while(c!=13);
ch[i-1]=NULL;
if(strcmp(ch,"Class12e")==0 && strcmpi(un,"Project")==0)
{
gotoxy(30,15);
textcolor(3 + BLINK);
cprintf(" MATCH FOUND");getch();
textcolor(7);
clrscr();
display2();
gotoxy(25,10);
printf(" Please Wait.....");
gotoxy(8,12);
textcolor(6);
cprintf("Û");
gotoxy(10,12);
gotoxy(67,12);
textcolor(6);
cprintf("Û");
gotoxy(74,12);
textcolor(6);
cprintf("Û");
gotoxy(10,12);
for(int j=0;j<=55;j=j+1)
{
gotoxy(69,12);
if(j>=50)
cout<<j*2-10<<"%";
else
cout<<j*2<<"%";
delay(50);
gotoxy(10+j,12);
textcolor(6);
cprintf("Û");
}
delay(3500);
textcolor(7);
}
else
{
gotoxy(30,15);
textcolor(RED + BLINK);
cprintf(" MATCH NOT FOUND");getch();
exit(0);
textcolor(7);
}
}
void main()
{
clrscr();
display2();
passw();
menu();
}
| 16.823448 | 92 | 0.542428 | [
"model"
] |
e5bfb1b7e281410a58fb430f9f985300fb18b5b0 | 5,557 | hpp | C++ | include/codegen/include/GlobalNamespace/GameplayModifiersModelSO.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | 1 | 2021-11-12T09:29:31.000Z | 2021-11-12T09:29:31.000Z | include/codegen/include/GlobalNamespace/GameplayModifiersModelSO.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | null | null | null | include/codegen/include/GlobalNamespace/GameplayModifiersModelSO.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | 2 | 2021-10-03T02:14:20.000Z | 2021-11-12T09:29:36.000Z | // Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
#pragma pack(push, 8)
// Begin includes
#include "extern/beatsaber-hook/shared/utils/typedefs.h"
// Including type: PersistentScriptableObject
#include "GlobalNamespace/PersistentScriptableObject.hpp"
// Completed includes
// Begin forward declares
// Forward declaring namespace: GlobalNamespace
namespace GlobalNamespace {
// Forward declaring type: GameplayModifierParamsSO
class GameplayModifierParamsSO;
// Forward declaring type: GameplayModifiers
class GameplayModifiers;
}
// Forward declaring namespace: System::Collections::Generic
namespace System::Collections::Generic {
// Forward declaring type: List`1<T>
template<typename T>
class List_1;
}
// Completed forward declares
// Type namespace:
namespace GlobalNamespace {
// Autogenerated type: GameplayModifiersModelSO
class GameplayModifiersModelSO : public GlobalNamespace::PersistentScriptableObject {
public:
// private GameplayModifierParamsSO _batteryEnergy
// Offset: 0x18
GlobalNamespace::GameplayModifierParamsSO* batteryEnergy;
// private GameplayModifierParamsSO _noFail
// Offset: 0x20
GlobalNamespace::GameplayModifierParamsSO* noFail;
// private GameplayModifierParamsSO _instaFail
// Offset: 0x28
GlobalNamespace::GameplayModifierParamsSO* instaFail;
// private GameplayModifierParamsSO _noObstacles
// Offset: 0x30
GlobalNamespace::GameplayModifierParamsSO* noObstacles;
// private GameplayModifierParamsSO _noBombs
// Offset: 0x38
GlobalNamespace::GameplayModifierParamsSO* noBombs;
// private GameplayModifierParamsSO _fastNotes
// Offset: 0x40
GlobalNamespace::GameplayModifierParamsSO* fastNotes;
// private GameplayModifierParamsSO _strictAngles
// Offset: 0x48
GlobalNamespace::GameplayModifierParamsSO* strictAngles;
// private GameplayModifierParamsSO _disappearingArrows
// Offset: 0x50
GlobalNamespace::GameplayModifierParamsSO* disappearingArrows;
// private GameplayModifierParamsSO _fasterSong
// Offset: 0x58
GlobalNamespace::GameplayModifierParamsSO* fasterSong;
// private GameplayModifierParamsSO _slowerSong
// Offset: 0x60
GlobalNamespace::GameplayModifierParamsSO* slowerSong;
// private GameplayModifierParamsSO _noArrows
// Offset: 0x68
GlobalNamespace::GameplayModifierParamsSO* noArrows;
// private GameplayModifierParamsSO _ghostNotes
// Offset: 0x70
GlobalNamespace::GameplayModifierParamsSO* ghostNotes;
// private GameplayModifierParamsSO _demoNoObstacles
// Offset: 0x78
GlobalNamespace::GameplayModifierParamsSO* demoNoObstacles;
// private GameplayModifierParamsSO _demoNoFail
// Offset: 0x80
GlobalNamespace::GameplayModifierParamsSO* demoNoFail;
// public System.Boolean GetModifierBoolValue(GameplayModifiers gameplayModifiers, GameplayModifierParamsSO gameplayModifierParams)
// Offset: 0xB3FAD4
bool GetModifierBoolValue(GlobalNamespace::GameplayModifiers* gameplayModifiers, GlobalNamespace::GameplayModifierParamsSO* gameplayModifierParams);
// public System.Void SetModifierBoolValue(GameplayModifiers gameplayModifiers, GameplayModifierParamsSO gameplayModifierParams, System.Boolean value)
// Offset: 0xB3FE98
void SetModifierBoolValue(GlobalNamespace::GameplayModifiers* gameplayModifiers, GlobalNamespace::GameplayModifierParamsSO* gameplayModifierParams, bool value);
// public System.Collections.Generic.List`1<GameplayModifierParamsSO> GetModifierParams(GameplayModifiers gameplayModifiers)
// Offset: 0xB40340
System::Collections::Generic::List_1<GlobalNamespace::GameplayModifierParamsSO*>* GetModifierParams(GlobalNamespace::GameplayModifiers* gameplayModifiers);
// public System.Single GetTotalMultiplier(GameplayModifiers gameplayModifiers)
// Offset: 0xB405C4
float GetTotalMultiplier(GlobalNamespace::GameplayModifiers* gameplayModifiers);
// public System.Int32 MaxModifiedScoreForMaxRawScore(System.Int32 maxRawScore, GameplayModifiers gameplayModifiers)
// Offset: 0xB406E0
int MaxModifiedScoreForMaxRawScore(int maxRawScore, GlobalNamespace::GameplayModifiers* gameplayModifiers);
// public System.Int32 MaxModifiedScoreForMaxRawScore(System.Int32 maxRawScore, GameplayModifiers gameplayModifiers, GameplayModifiersModelSO gameplayModifiersModel)
// Offset: 0xB40738
int MaxModifiedScoreForMaxRawScore(int maxRawScore, GlobalNamespace::GameplayModifiers* gameplayModifiers, GlobalNamespace::GameplayModifiersModelSO* gameplayModifiersModel);
// private System.Int32 GetModifiedScoreForGameplayModifiers(System.Int32 rawScore, GameplayModifiers gameplayModifiers)
// Offset: 0xB4070C
int GetModifiedScoreForGameplayModifiers(int rawScore, GlobalNamespace::GameplayModifiers* gameplayModifiers);
// public System.Void .ctor()
// Offset: 0xB40764
// Implemented from: PersistentScriptableObject
// Base method: System.Void PersistentScriptableObject::.ctor()
// Base method: System.Void ScriptableObject::.ctor()
// Base method: System.Void Object::.ctor()
// Base method: System.Void Object::.ctor()
static GameplayModifiersModelSO* New_ctor();
}; // GameplayModifiersModelSO
}
#include "extern/beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
DEFINE_IL2CPP_ARG_TYPE(GlobalNamespace::GameplayModifiersModelSO*, "", "GameplayModifiersModelSO");
#pragma pack(pop)
| 51.934579 | 178 | 0.786396 | [
"object"
] |
e5d676aa82bfda667fe1514e0718f8728d991831 | 8,047 | cpp | C++ | Sources/Elastos/Packages/Apps/Launcher2/src/elastos/droid/launcher2/InstallWidgetReceiver.cpp | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | 7 | 2017-07-13T10:34:54.000Z | 2021-04-16T05:40:35.000Z | Sources/Elastos/Packages/Apps/Launcher2/src/elastos/droid/launcher2/InstallWidgetReceiver.cpp | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | null | null | null | Sources/Elastos/Packages/Apps/Launcher2/src/elastos/droid/launcher2/InstallWidgetReceiver.cpp | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | 9 | 2017-07-13T12:33:20.000Z | 2021-06-19T02:46:48.000Z | //=========================================================================
// Copyright (C) 2012 The Elastos Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//=========================================================================
#include "elastos/droid/launcher2/InstallWidgetReceiver.h"
#include "elastos/droid/launcher2/PendingAddItemInfo.h"
#include "elastos/droid/launcher2/LauncherSettings.h"
#include "elastos/droid/view/LayoutInflater.h"
#include "Elastos.Droid.Graphics.h"
#include "Elastos.Droid.Service.h"
#include "Elastos.CoreLibrary.Core.h"
#include <elastos/core/CoreUtils.h>
#include "R.h"
using Elastos::Droid::Content::IContext;
using Elastos::Droid::Content::Pm::IPackageManager;
using Elastos::Droid::Content::EIID_IDialogInterfaceOnClickListener;
using Elastos::Droid::Graphics::Drawable::IDrawable;
using Elastos::Droid::View::LayoutInflater;
using Elastos::Droid::Widget::ITextView;
using Elastos::Droid::Widget::IImageView;
using Elastos::Droid::Widget::EIID_IListAdapter;
using Elastos::Droid::Widget::EIID_IAdapter;
using Elastos::Core::IInteger32;
using Elastos::Core::CoreUtils;
namespace Elastos {
namespace Droid {
namespace Launcher2 {
InstallWidgetReceiver::WidgetMimeTypeHandlerData::WidgetMimeTypeHandlerData(
/* [in] */ IResolveInfo* rInfo,
/* [in] */ IAppWidgetProviderInfo* wInfo)
: mResolveInfo(rInfo)
, mWidgetInfo(wInfo)
{
}
CAR_INTERFACE_IMPL_3(InstallWidgetReceiver::WidgetListAdapter, Object, IListAdapter
, IAdapter, IDialogInterfaceOnClickListener);
InstallWidgetReceiver::WidgetListAdapter::WidgetListAdapter(
/* [in] */ ILauncher* l,
/* [in] */ const String& mimeType,
/* [in] */ IClipData* data,
/* [in] */ IList* list,
/* [in] */ ICellLayout* target,
/* [in] */ Int32 targetScreen,
/* [in] */ ArrayOf<Int32>* targetPos)
: mLauncher(l)
, mMimeType(mimeType)
, mClipData(data)
, mActivities(list)
, mTargetLayout(target)
, mTargetLayoutScreen(targetScreen)
, mTargetLayoutPos(targetPos)
{
}
ECode InstallWidgetReceiver::WidgetListAdapter::RegisterDataSetObserver(
/* [in] */ IDataSetObserver* observer)
{
return NOERROR;
}
ECode InstallWidgetReceiver::WidgetListAdapter::UnregisterDataSetObserver(
/* [in] */ IDataSetObserver* observer)
{
return NOERROR;
}
ECode InstallWidgetReceiver::WidgetListAdapter::GetCount(
/* [out] */ Int32* count)
{
VALIDATE_NOT_NULL(count);
return mActivities->GetSize(count);
}
ECode InstallWidgetReceiver::WidgetListAdapter::GetItem(
/* [in] */ Int32 position,
/* [out] */ IInterface** item)
{
VALIDATE_NOT_NULL(item);
*item = NULL;
return NOERROR;
}
ECode InstallWidgetReceiver::WidgetListAdapter::GetItemId(
/* [in] */ Int32 position,
/* [out] */ Int64* itemId)
{
VALIDATE_NOT_NULL(itemId);
*itemId = position;
return NOERROR;
}
ECode InstallWidgetReceiver::WidgetListAdapter::HasStableIds(
/* [out] */ Boolean* hasStableIds)
{
VALIDATE_NOT_NULL(hasStableIds);
*hasStableIds = TRUE;
return NOERROR;
}
ECode InstallWidgetReceiver::WidgetListAdapter::GetView(
/* [in] */ Int32 position,
/* [in] */ IView* inConvertView,
/* [in] */ IViewGroup* parent,
/* [out] */ IView** view)
{
VALIDATE_NOT_NULL(view);
*view = NULL;
AutoPtr<IContext> context;
IView::Probe(parent)->GetContext((IContext**)&context);
AutoPtr<IPackageManager> packageManager;
context->GetPackageManager((IPackageManager**)&packageManager);
// Lazy-create inflater
if (mInflater == NULL) {
LayoutInflater::From(context, (ILayoutInflater**)&mInflater);
}
// Use the convert-view where possible
AutoPtr<IView> convertView = inConvertView;
if (convertView == NULL) {
mInflater->Inflate(Elastos::Droid::Launcher2::R::layout::external_widget_drop_list_item, parent,
FALSE, (IView**)&convertView);
}
AutoPtr<IInterface> obj;
mActivities->Get(position, (IInterface**)&obj);
AutoPtr<WidgetMimeTypeHandlerData> data = (WidgetMimeTypeHandlerData*)IObject::Probe(obj);
AutoPtr<IResolveInfo> resolveInfo = data->mResolveInfo;
AutoPtr<IAppWidgetProviderInfo> widgetInfo = data->mWidgetInfo;
// Set the icon
AutoPtr<IDrawable> d;
resolveInfo->LoadIcon(packageManager, (IDrawable**)&d);
AutoPtr<IView> _view;
convertView->FindViewById(Elastos::Droid::Launcher2::R::id::provider_icon, (IView**)&_view);
AutoPtr<IImageView> i = IImageView::Probe(_view);
i->SetImageDrawable(d);
// Set the text
AutoPtr<ICharSequence> component;
resolveInfo->LoadLabel(packageManager, (ICharSequence**)&component);
AutoPtr<ArrayOf<Int32> > widgetSpan = ArrayOf<Int32>::Alloc(2);
Int32 width;
widgetInfo->GetMinWidth(&width);
Int32 height;
widgetInfo->GetMinHeight(&height);
AutoPtr<ArrayOf<Int32> > outArray;
mTargetLayout->RectToCell(width, height, widgetSpan, (ArrayOf<Int32>**)&outArray);
AutoPtr<IView> _view2;
convertView->FindViewById(Elastos::Droid::Launcher2::R::id::provider, (IView**)&_view2);
AutoPtr<ITextView> t = ITextView::Probe(_view2);
AutoPtr<ArrayOf<IInterface*> > array = ArrayOf<IInterface*>::Alloc(3);
array->Set(0, TO_IINTERFACE(component));
AutoPtr<IInteger32> intObj1 = CoreUtils::Convert((*widgetSpan)[0]);
array->Set(1, TO_IINTERFACE(intObj1));
AutoPtr<IInteger32> intObj2 = CoreUtils::Convert((*widgetSpan)[1]);
array->Set(2, TO_IINTERFACE(intObj2));
String format;
context->GetString(
Elastos::Droid::Launcher2::R::string::external_drop_widget_pick_format,
array, &format);
AutoPtr<ICharSequence> cchar = CoreUtils::Convert(format);
t->SetText(cchar);
*view = convertView;
REFCOUNT_ADD(*view);
return NOERROR;
}
ECode InstallWidgetReceiver::WidgetListAdapter::GetItemViewType(
/* [in] */ Int32 position,
/* [out] */ Int32* viewType)
{
VALIDATE_NOT_NULL(viewType);
*viewType = 0;
return NOERROR;
}
ECode InstallWidgetReceiver::WidgetListAdapter::GetViewTypeCount(
/* [out] */ Int32* count)
{
VALIDATE_NOT_NULL(count);
*count = 1;
return NOERROR;
}
ECode InstallWidgetReceiver::WidgetListAdapter::IsEmpty(
/* [out] */ Boolean* isEmpty)
{
VALIDATE_NOT_NULL(isEmpty);
return mActivities->IsEmpty(isEmpty);
}
ECode InstallWidgetReceiver::WidgetListAdapter::AreAllItemsEnabled(
/* [out] */ Boolean* enabled)
{
VALIDATE_NOT_NULL(enabled);
*enabled = FALSE;
return NOERROR;
}
ECode InstallWidgetReceiver::WidgetListAdapter::IsEnabled(
/* [in] */ Int32 position,
/* [out] */ Boolean* enabled)
{
VALIDATE_NOT_NULL(enabled);
*enabled = TRUE;
return NOERROR;
}
ECode InstallWidgetReceiver::WidgetListAdapter::OnClick(
/* [in] */ IDialogInterface* dialog,
/* [in] */ Int32 which)
{
AutoPtr<IInterface> obj;
mActivities->Get(which, (IInterface**)&obj);
AutoPtr<WidgetMimeTypeHandlerData> data = (WidgetMimeTypeHandlerData*)IObject::Probe(obj);
AutoPtr<IAppWidgetProviderInfo> widgetInfo = data->mWidgetInfo;
AutoPtr<PendingAddWidgetInfo> createInfo = new PendingAddWidgetInfo();
createInfo->constructor(widgetInfo, mMimeType, IParcelable::Probe(mClipData));
return mLauncher->AddAppWidgetFromDrop(createInfo, LauncherSettings::Favorites::CONTAINER_DESKTOP,
mTargetLayoutScreen, NULL, NULL, mTargetLayoutPos);
}
} // namespace Launcher2
} // namespace Droid
} // namespace Elastos | 31.311284 | 104 | 0.693426 | [
"object"
] |
e5d77a5511ec1a9ccbad23dda0d6c40a347e1ddc | 2,610 | cpp | C++ | src/playground/Main.cpp | jmnel/math4171 | 25f7b95b24bcac0cd707a16c0d387fce4e68be03 | [
"MIT"
] | null | null | null | src/playground/Main.cpp | jmnel/math4171 | 25f7b95b24bcac0cd707a16c0d387fce4e68be03 | [
"MIT"
] | null | null | null | src/playground/Main.cpp | jmnel/math4171 | 25f7b95b24bcac0cd707a16c0d387fce4e68be03 | [
"MIT"
] | null | null | null | // -- Calculations for assignment 1 --
// -- Chapter 3: Exercise 1 ----------
#include <cstdlib>
#include <iostream>
#include <memory>
#include <string>
#include <vector>
#include <Vec.hpp>
//#include <PythonCommon.hpp>
#include <PythonContext.hpp>
//#include <PythonFloat.hpp>
#include <PythonFunction.hpp>
#include <PythonModule.hpp>
//#include <ContourPlot.hpp>
//#include <ListPlot.hpp>
//#include <SurfacePlot.hpp>
//#include <Figure.hpp>
//#include "MinNelderMead.hpp"
//#ifdef _WIN32
//#elif __APPLE__
//#elif __linux__
//#include <unistd.h>
//#endif
using std::cout;
// using std::dynamic_pointer_cast;
using std::endl;
using std::shared_ptr;
using std::string;
using std::vector;
// using namespace arc;
using namespace arc;
using namespace arc::python;
int main(int argc, char* argv[]) {
//auto func1 = [](Vec2d x) {
//auto term1 = (1.0 - x[0]);
//term1 = term1 * term1;
//auto term2 = x[1] - x[0] * x[0];
//term2 = term2 * term2 * 100;
//return term1 + term2;
//// return sin(x[0] * x[0] + x[1] * x[1]);
//};
//Vec2d xMin(-1.5, -0.5);
//Vec2d xMax(1.5, 2.0);
python::appendToPath(
"/home/jacques/repos/math4171/src/arcpython");
PythonModule m( "foo");
PythonFunction f( m, "bar" );
//auto f = PythonFunction( m,
//arc::plot::Figure fig;
//auto axes = fig.getCurrentAxes();
////auto adr = pythonOmToApiCast( axes.pythonAxesObject );
////cout << "addr1=" << std::hex << adr << endl;
////auto mod = PythonModule("
//axes.setAxesLimitX(-0.3, 0.3);
//// axes.setAxesLimitY(-0.3, 0.3);
//vector<vector<double>> x;
//vector<vector<double>> y;
//vector<vector<double>> z;
//for( int i = 0; i < 100; i++ ) {
//x.push_back( vector<double>() );
//y.push_back( vector<double>() );
//z.push_back( vector<double>() );
//for( int j = 0; j < 100; j++ ) {
//double xVal = -0.5 + i * 0.01;
//double yVal = -0.5 + j * 0.01;
//double zVal = xVal * xVal + yVal * yVal;
//x.back().push_back( xVal );
//y.back().push_back( yVal );
//z.back().push_back( zVal );
//}
//}
////for (int i = 0; i < 100; i++) {
////double xI = 0.1 * i;
////double yI = sin(xI);
////x.emplace_back(xI);
////y.emplace_back(yI);
////}
//// auto plot1 = axes.surfacePlot(x, y, z);
//// auto plot2 = axes.contourPlot(x,y,z);
//auto plot2 = axes.contourPlot(x, y, z);
//fig.show();
//fig.save("/home/jacques/foo.pdf");
}
| 24.857143 | 62 | 0.544061 | [
"vector"
] |
e5d9b413dc51ff4e0b622caa1a472c9bf59a26ed | 7,388 | cpp | C++ | src/Customs/FirstBossScript.cpp | fgagamedev/voID | 37cd56fe2878d036c36dafcf595e48ed85408d02 | [
"MIT"
] | null | null | null | src/Customs/FirstBossScript.cpp | fgagamedev/voID | 37cd56fe2878d036c36dafcf595e48ed85408d02 | [
"MIT"
] | null | null | null | src/Customs/FirstBossScript.cpp | fgagamedev/voID | 37cd56fe2878d036c36dafcf595e48ed85408d02 | [
"MIT"
] | null | null | null | /**
@file FirstBossScript.cpp
@brief Creates and handles with the first boss behavior.
@copyright MIT License.
*/
#include "Customs/FirstBossScript.hpp"
/**
@brief Constructor for the class FirstBossScript.
*/
FirstBossScript::FirstBossScript(GameObject *owner) : Script(owner) {}
/**
@brief Starts the script of the first boss of the game.
*/
void FirstBossScript::Start() {
// Create the animations of the first boss
CreateAnimations();
// Positions the boss in the game's map.
position = GetOwner()->GetPosition();
animator = (Animator *)GetOwner()->GetComponent("Animator");
input = InputSystem::GetInstance();
auto map = SceneManager::GetInstance()->GetScene("Gameplay")->GetGameObject("Map");
if (map) {
GetOwner()->SetZoomProportion(Vector(
map->originalWidth/GetOwner()->originalWidth,
map->originalHeight/GetOwner()->originalHeight));
firstBossCollider = new RectangleCollider(GetOwner(),
Vector(0, 0),
GetOwner()->GetWidth(),
GetOwner()->GetHeight(), 0);
}
}
/**
@brief Creates logic behind the firs boss animations to be shown during the
game.
*/
void FirstBossScript::CreateAnimations() {
// Get images from the first boss.
auto firstBossImage = new Image("assets/boss1.png",0,0,1896, 324);
auto firstBossJumpImage = new Image("assets/boss1_jump.png",0,0,1180, 406);
// Create animations for the first boss.
auto firstBossAnimation = new Animation(GetOwner(),firstBossImage);
for (int i = 0; i < 8; i++) {
firstBossAnimation->AddFrame(new Frame(i * 237,0, 237, 406));
}
auto firstBossJumpAnimation = new Animation(GetOwner(),firstBossJumpImage);
for (int i = 0; i < 5; i++) {
firstBossJumpAnimation->AddFrame(new Frame(i * 236,0, 236, 406));
firstBossJumpAnimation->AddFrame(new Frame(i * 236,0, 236, 406));
if (i == 4) {
for (int animMulti = 0 ; i < 8 ; i++) {
firstBossJumpAnimation->AddFrame(new Frame(i * 236,0, 236, 406));
firstBossJumpAnimation->AddFrame(new Frame(i * 236,0, 236, 406));
}
}
}
// Second Attack.
auto firstBossFallAnimation = new Animation(GetOwner(),firstBossJumpImage);
for (int i = 5; i > 0; i--) {
firstBossFallAnimation->AddFrame(new Frame(i * 236, 0, 236, 406));
firstBossFallAnimation->AddFrame(new Frame(i * 236, 0, 236, 406));
}
// Creates the animator for the first boss.
auto firstBossAnimator = new Animator(GetOwner());
firstBossAnimator->AddAnimation("firstBossAnimation", firstBossAnimation);
firstBossAnimator->AddAnimation("firstBossJumpAnimation",
firstBossJumpAnimation);
firstBossAnimator->AddAnimation("firstBossFallAnimation",
firstBossFallAnimation);
}
/**
@brief Decides what happens to the boss depending on the game's circumstances.
*/
void FirstBossScript::ComponentUpdate() {
if (!SecondAttack && !SecondAttackFall) {
//Idle animation
animator->PlayAnimation("firstBossAnimation");
}
if (input->GetKeyPressed(INPUT_N)) {
SecondAttack = true;
animator->PlayAnimation("firstBossJumpAnimation");
}
}
/**
@brief Handles with the boss behavior depending on which attack is being shot.
*/
void FirstBossScript::FixedComponentUpdate() {
if (FirstAttack) {
timerFirstAttackCooldown.Update(EngineGlobals::fixed_update_interval);
}
if (goneFirstAttack) {
timerFirstAttackGone.Update(EngineGlobals::fixed_update_interval);
}
if (SecondAttack) {
timerSecondAttack.Update(EngineGlobals::fixed_update_interval);
}
if (SecondAttackFall) {
timerSecondAttackFall.Update(EngineGlobals::fixed_update_interval);
}
timerAttackCooldown.Update(EngineGlobals::fixed_update_interval);
Attack();
if (shake) {
// CameraShake(intensity, duration in seconds)
CameraSystem::GetInstance()->CameraShake(8,1,
SceneManager::GetInstance()->GetCurrentScene());
if (!CameraSystem::GetInstance()->IsShaking()) {
shake = false;
}
}
}
/**
@brief Manages the shot's position and its behavior, the time it takes to
happen, etc.
*/
void FirstBossScript::Attack() {
if (GetOwner()->active) {
// Rand first attack or second attack
if (timerAttackCooldown.GetTime() >= 9*1000) {
// Choose a new number
randNum = rand() % 2;
timerAttackCooldown.Restart();
cout << randNum << endl;
}
if (randNum == 0 && SecondAttackFall == false) {
SecondAttack = true;
animator->PlayAnimation("firstBossJumpAnimation");
}
if (randNum == 1) {
FirstAttack = true;
// First Attack
if (timerFirstAttackCooldown.GetTime() >= 2*1000
&& firstAttackCounter < 3) {
FirstBossController::GetInstance()->FirstAttackSurge();
timerFirstAttackCooldown.Restart();
firstAttackCounter++;
// Delay for next sord
}
if (firstAttackCounter == 3) {
// Activate timer to gone tentacle
goneFirstAttack = true;
}
// Wait 6 seconds to make attack gone
if (timerFirstAttackGone.GetTime() >= 2*1000) {
FirstBossController::GetInstance()->FirstAttackGone();
firstAttackCounter = 0;
goneFirstAttack = false;
timerFirstAttackGone.Restart();
timerFirstAttackCooldown.Restart();
randNum = -1;
}
}
if ((timerSecondAttack.GetTime() >= 0.5*1000) && SecondAttack) {
if (GetOwner()->GetPosition()->m_y > -1900) {
Vector *newPosition = GetOwner()->GetPosition();
newPosition->m_y = newPosition->m_y - 90;
GetOwner()->SetPosition(*newPosition);
} else {
SecondAttack = false;
SecondAttackFall = true;
timerSecondAttack.Restart();
}
}
if (timerSecondAttackFall.GetTime() >= 2*1000 && SecondAttackFall) {
// Get player Position
player = SceneManager::GetInstance()->GetCurrentScene()->GetGameObject("NakedMan");
playerPosition.m_x = player->GetPosition()->m_x - 160;
playerPosition.m_y = player->GetPosition()->m_y - 450;
cout << "flag" << endl;
std::cout << playerPosition.m_x << " " << playerPosition.m_y << std::endl;
GetOwner()->m_position->m_x = playerPosition.m_x;
if (GetOwner()->m_position->m_y < playerPosition.m_y) {
GetOwner()->m_position->m_y += 90;
shake = true;
animator->PlayAnimation("firstBossFallAnimation");
} else {
SecondAttackFall = false;
shake = false;
randNum = -1;
}
}
}
}
| 34.849057 | 95 | 0.578506 | [
"vector"
] |
e5de70ce7c7b43d6c02bc59872924e9c225bfce3 | 5,287 | hpp | C++ | include/layered_hardware_gazebo/layered_hardware_gazebo.hpp | yoshito-n-students/layered_hardware_gazebo | 83a3b69f2a87f122e29d29d81eb058881b199121 | [
"MIT"
] | 1 | 2020-09-01T04:18:10.000Z | 2020-09-01T04:18:10.000Z | include/layered_hardware_gazebo/layered_hardware_gazebo.hpp | yoshito-n-students/layered_hardware_gazebo | 83a3b69f2a87f122e29d29d81eb058881b199121 | [
"MIT"
] | null | null | null | include/layered_hardware_gazebo/layered_hardware_gazebo.hpp | yoshito-n-students/layered_hardware_gazebo | 83a3b69f2a87f122e29d29d81eb058881b199121 | [
"MIT"
] | null | null | null | #ifndef LAYERED_HARDWARE_GAZEBO_LAYERED_HARDWARE_GAZEBO_HPP
#define LAYERED_HARDWARE_GAZEBO_LAYERED_HARDWARE_GAZEBO_HPP
#include <string>
#include <vector>
#include <layered_hardware/layer_base.hpp>
#include <layered_hardware/layered_hardware.hpp>
#include <layered_hardware_gazebo/common_namespaces.hpp>
#include <layered_hardware_gazebo/gazebo_layer_base.hpp>
#include <pluginlib/class_loader.hpp>
#include <ros/console.h>
#include <ros/node_handle.h>
#include <gazebo/physics/physics.hh>
namespace layered_hardware_gazebo {
class LayeredHardwareGazebo : public lh::LayeredHardware {
public:
LayeredHardwareGazebo()
: lh::LayeredHardware(), gazebo_layer_loader_("layered_hardware_gazebo",
"layered_hardware_gazebo::GazeboLayerBase") {}
virtual ~LayeredHardwareGazebo() {
// before destructing layer loader,
// deallocate layers which were created by plugins or loader cannot unload plugins
layers_.clear();
}
bool init(const ros::NodeHandle ¶m_nh, const gzp::ModelPtr model) {
// get URDF description from param
const std::string urdf_str(getURDFStr(param_nh));
if (urdf_str.empty()) {
ROS_WARN("LayeredHardwareGazebo::init(): Failed to get URDF description. "
"Every layers will be initialized with empty string.");
// continue because layers may not require robot description
}
// get layer names from param
std::vector< std::string > layer_names;
if (!param_nh.getParam("layers", layer_names)) {
ROS_ERROR_STREAM("LayeredHardwareGazebo::init(): Failed to get param '"
<< param_nh.resolveName("layers") << "'");
return false;
}
if (layer_names.empty()) {
ROS_ERROR_STREAM("LayeredHardwareGazebo::init(): Param '" << param_nh.resolveName("layers")
<< "' must be a string array");
return false;
}
// load & init layer instances from bottom (actuator-side) to upper (controller-side)
layers_.resize(layer_names.size());
for (int i = layers_.size() - 1; i >= 0; --i) {
lh::LayerPtr &layer(layers_[i]);
const std::string &layer_name(layer_names[i]);
const ros::NodeHandle layer_param_nh(param_nh, layer_name);
// get layer's typename from param
std::string lookup_name;
if (!layer_param_nh.getParam("type", lookup_name)) {
ROS_ERROR_STREAM("LayeredHardwareGazebo::init(): Failed to get param '"
<< layer_param_nh.resolveName("type") << "'");
return false;
}
// load as a gazebo layer
if (gazebo_layer_loader_.isClassAvailable(lookup_name)) {
layer = loadGazeboLayer(lookup_name, layer_param_nh, urdf_str, model);
if (!layer) {
ROS_ERROR_STREAM("LayeredHardwareGazebo::init(): Failed to load the gazebo layer '"
<< layer_name << "'");
return false;
}
ROS_INFO_STREAM("LayeredHardwareGazebo::init(): Initialized the gazebo layer '"
<< layer_name << "'");
}
// load as a non-gazebo layer
else if (layer_loader_.isClassAvailable(lookup_name)) {
layer = loadLayer(lookup_name, layer_param_nh, urdf_str);
if (!layer) {
ROS_ERROR_STREAM("LayeredHardwareGazebo::init(): Failed to load the layer '" << layer_name
<< "'");
return false;
}
ROS_INFO_STREAM("LayeredHardwareGazebo::init(): Initialized the layer '" << layer_name
<< "'");
}
// no layer to load
else {
ROS_ERROR_STREAM("LayeredHardwareGazebo::init(): Unavailable lookup name '"
<< lookup_name << "' for the layer '" << layer_name << "'");
return false;
}
}
return true;
}
protected:
// override init() from the parent class to prevent calling
bool init(const ros::NodeHandle ¶m_nh) {
ROS_ERROR("LayeredHardwareGazebo::init(): Disabled version of init(). Call another version.");
return false;
}
GazeboLayerPtr loadGazeboLayer(const std::string &lookup_name, const ros::NodeHandle ¶m_nh,
const std::string &urdf_str, const gzp::ModelPtr &model) {
GazeboLayerPtr layer;
// create a gazebo layer instance by typename
try {
layer = gazebo_layer_loader_.createInstance(lookup_name);
} catch (const pluginlib::PluginlibException &ex) {
ROS_ERROR_STREAM("LayeredHardwareGazebo::loadGazeboLayer(): Failed to create a gazebo layer "
"by the lookup name '"
<< lookup_name << "': " << ex.what());
return GazeboLayerPtr();
}
// init the layer
if (!layer->init(this, param_nh, urdf_str, model)) {
ROS_ERROR_STREAM(
"LayeredHardwareGazebo::loadGazeboLayer(): Failed to initialize a gazebo layer");
return GazeboLayerPtr();
}
return layer;
}
protected:
pluginlib::ClassLoader< GazeboLayerBase > gazebo_layer_loader_;
};
} // namespace layered_hardware_gazebo
#endif | 38.591241 | 100 | 0.621524 | [
"vector",
"model"
] |
e5df7abd48332e28d88145d0f81981b5d5d7f740 | 711 | cpp | C++ | 0700/10/719a.cpp | actium/cf | d7be128c3a9adb014a231a399f1c5f19e1ab2a38 | [
"Unlicense"
] | 1 | 2020-07-03T15:55:52.000Z | 2020-07-03T15:55:52.000Z | 0700/10/719a.cpp | actium/cf | d7be128c3a9adb014a231a399f1c5f19e1ab2a38 | [
"Unlicense"
] | null | null | null | 0700/10/719a.cpp | actium/cf | d7be128c3a9adb014a231a399f1c5f19e1ab2a38 | [
"Unlicense"
] | 3 | 2020-10-01T14:55:28.000Z | 2021-07-11T11:33:58.000Z | #include <iostream>
#include <vector>
template <typename T>
std::istream& operator >>(std::istream& input, std::vector<T>& v)
{
for (T& a : v)
input >> a;
return input;
}
void no_answer()
{
std::cout << -1 << '\n';
}
void answer(const char* v)
{
std::cout << v << '\n';
}
void solve(const std::vector<unsigned>& a)
{
const size_t n = a.size();
if (a.back() == 0)
return answer("UP");
if (a.back() == 15)
return answer("DOWN");
if (n == 1)
return no_answer();
answer(a[n-2] < a[n-1] ? "UP" : "DOWN");
}
int main()
{
size_t n;
std::cin >> n;
std::vector<unsigned> a(n);
std::cin >> a;
solve(a);
return 0;
}
| 13.673077 | 65 | 0.500703 | [
"vector"
] |
e5e12a3b44b21ce24c6c0e3ef48ecbaef6d26a82 | 9,487 | hpp | C++ | src/tests/blueprint/blueprint_test_helpers.hpp | francois-kitware/conduit | e457aeeb249c445d67ca791c14f72062acfafb7f | [
"BSD-3-Clause"
] | 120 | 2015-12-09T00:58:22.000Z | 2022-03-25T00:14:39.000Z | src/tests/blueprint/blueprint_test_helpers.hpp | francois-kitware/conduit | e457aeeb249c445d67ca791c14f72062acfafb7f | [
"BSD-3-Clause"
] | 808 | 2016-02-27T22:25:15.000Z | 2022-03-30T23:42:12.000Z | src/tests/blueprint/blueprint_test_helpers.hpp | francois-kitware/conduit | e457aeeb249c445d67ca791c14f72062acfafb7f | [
"BSD-3-Clause"
] | 49 | 2016-02-12T17:19:16.000Z | 2022-02-01T14:36:21.000Z | // Copyright (c) Lawrence Livermore National Security, LLC and other Conduit
// Project developers. See top-level LICENSE AND COPYRIGHT files for dates and
// other details. No copyright assignment is required to contribute to Conduit.
//-----------------------------------------------------------------------------
///
/// file: blueprint_test_helpers.hpp
///
//-----------------------------------------------------------------------------
#ifndef BLUEPRINT_TEST_HELPERS_HPP
#define BLUEPRINT_TEST_HELPERS_HPP
//-----------------------------------------------------------------------------
// conduit lib includes
//-----------------------------------------------------------------------------
#include <conduit.hpp>
#include <conduit_node.hpp>
#include <conduit_blueprint_mesh_examples.hpp>
#include <conduit_blueprint_table.hpp>
#include <conduit_log.hpp>
#include <gtest/gtest.h>
//-----------------------------------------------------------------------------
// -- begin table --
//-----------------------------------------------------------------------------
namespace table
{
//-----------------------------------------------------------------------------
inline void
compare_to_baseline_leaf(const conduit::Node &test,
const conduit::Node &baseline)
{
if(test.dtype().is_empty() || test.dtype().is_list() || test.dtype().is_object()
|| baseline.dtype().is_empty() || baseline.dtype().is_list()
|| baseline.dtype().is_object())
{
CONDUIT_ERROR("compare_to_baseline_leaf only operates on leaf nodes.");
}
// Sometimes when we read from a file the data types don't match.
// Convert test to the same type as baseline then compare.
conduit::Node temp, info;
if(test.dtype().id() != baseline.dtype().id())
{
test.to_data_type(baseline.dtype().id(), temp);
}
else
{
temp.set_external(test);
}
EXPECT_FALSE(baseline.diff(temp, info)) << "Column " << test.name() << info.to_json();
}
//-----------------------------------------------------------------------------
inline void
compare_to_baseline_values(const conduit::Node &test,
const conduit::Node &baseline)
{
ASSERT_EQ(baseline.number_of_children(), test.number_of_children());
for(conduit::index_t j = 0; j < baseline.number_of_children(); j++)
{
const conduit::Node &baseline_value = baseline[j];
const conduit::Node &test_value = test[j];
EXPECT_EQ(baseline_value.name(), test_value.name());
if(baseline_value.dtype().is_list() || baseline_value.dtype().is_object())
{
// mcarray
ASSERT_EQ(baseline_value.number_of_children(), test_value.number_of_children());
EXPECT_EQ(baseline_value.dtype().is_list(), test_value.dtype().is_list());
EXPECT_EQ(baseline_value.dtype().is_object(), test_value.dtype().is_object());
for(conduit::index_t k = 0; k < baseline_value.number_of_children(); k++)
{
const conduit::Node &baseline_comp = baseline_value[k];
const conduit::Node &test_comp = test_value[k];
EXPECT_EQ(baseline_comp.name(), test_comp.name());
compare_to_baseline_leaf(test_comp, baseline_comp);
}
}
else
{
// data array
compare_to_baseline_leaf(test_value, baseline_value);
}
}
}
//-----------------------------------------------------------------------------
inline void
compare_to_baseline(const conduit::Node &test,
const conduit::Node &baseline, bool order_matters = true)
{
conduit::Node info;
ASSERT_TRUE(conduit::blueprint::table::verify(baseline, info)) << info.to_json();
ASSERT_TRUE(conduit::blueprint::table::verify(test, info)) << info.to_json();
if(baseline.has_child("values"))
{
const conduit::Node &baseline_values = baseline["values"];
const conduit::Node &test_values = test["values"];
compare_to_baseline_values(test_values, baseline_values);
}
else
{
ASSERT_EQ(baseline.number_of_children(), test.number_of_children());
for(conduit::index_t i = 0; i < baseline.number_of_children(); i++)
{
if(order_matters)
{
ASSERT_EQ(baseline[i].name(), test[i].name())
<< "baseline[i].name() = " << baseline[i].name()
<< " test[i].name() = " << test[i].name();
const conduit::Node &baseline_values = baseline[i]["values"];
const conduit::Node &test_values = test[i]["values"];
compare_to_baseline_values(test_values, baseline_values);
}
else
{
ASSERT_TRUE(test.has_child(baseline[i].name()))
<< "With name = " << baseline[i].name()
<< test.schema().to_json();
const conduit::Node &b = baseline[i];
const conduit::Node &baseline_values = b["values"];
const conduit::Node &test_values = test[b.name()]["values"];
compare_to_baseline_values(test_values, baseline_values);
}
}
}
}
}
//-----------------------------------------------------------------------------
// -- end table --
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// -- begin parition --
//-----------------------------------------------------------------------------
namespace partition
{
//-----------------------------------------------------------------------------
/**
Make a field that selects domains like this.
+----+----+
| 3 | 5 |
| +-|-+ |
| +4|4| |
+--+-+-+--|
| +1|1| |
| +-|-+ |
| 0 | 2 |
+----+----+
*/
//-----------------------------------------------------------------------------
inline void
add_field_selection_field(int cx, int cy, int cz,
int iquad, int jquad, conduit::index_t main_dom, conduit::index_t fill_dom,
conduit::Node &output)
{
std::vector<conduit::int64> values(cx*cy*cz, main_dom);
int sq = 2*jquad + iquad;
int idx = 0;
for(int k = 0; k < cz; k++)
for(int j = 0; j < cy; j++)
for(int i = 0; i < cx; i++)
{
int ci = (i < cx/2) ? 0 : 1;
int cj = (j < cy/2) ? 0 : 1;
int csq = 2*cj + ci;
if(csq == sq)
values[idx] = fill_dom;
idx++;
}
output["fields/selection_field/type"] = "scalar";
output["fields/selection_field/association"] = "element";
output["fields/selection_field/topology"] = "mesh";
output["fields/selection_field/values"].set(values);
}
//-----------------------------------------------------------------------------
inline void
make_field_selection_example(conduit::Node &output, int mask)
{
int nx = 11, ny = 11, nz = 3;
int m = 1, dc = 0;
for(int i = 0; i < 4; i++)
{
if(m & mask)
dc++;
m <<= 1;
}
if(mask & 1)
{
conduit::Node &dom0 = (dc > 1) ? output.append() : output;
conduit::blueprint::mesh::examples::braid("uniform", nx, ny, nz, dom0);
dom0["state/cycle"] = 1;
dom0["state/domain_id"] = 0;
dom0["coordsets/coords/origin/x"] = 0.;
dom0["coordsets/coords/origin/y"] = 0.;
dom0["coordsets/coords/origin/z"] = 0.;
add_field_selection_field(nx-1, ny-1, nz-1, 1,1, 0, 11, dom0);
}
if(mask & 2)
{
conduit::Node &dom1 = (dc > 1) ? output.append() : output;
conduit::blueprint::mesh::examples::braid("uniform", nx, ny, nz, dom1);
auto dx = dom1["coordsets/coords/spacing/dx"].to_float();
dom1["state/cycle"] = 1;
dom1["state/domain_id"] = 1;
dom1["coordsets/coords/origin/x"] = dx * static_cast<double>(nx-1);
dom1["coordsets/coords/origin/y"] = 0.;
dom1["coordsets/coords/origin/z"] = 0.;
add_field_selection_field(nx-1, ny-1, nz-1, 0,1, 22, 11, dom1);
}
if(mask & 4)
{
conduit::Node &dom2 = (dc > 1) ? output.append() : output;
conduit::blueprint::mesh::examples::braid("uniform", nx, ny, nz, dom2);
auto dy = dom2["coordsets/coords/spacing/dy"].to_float();
dom2["state/cycle"] = 1;
dom2["state/domain_id"] = 2;
dom2["coordsets/coords/origin/x"] = 0.;
dom2["coordsets/coords/origin/y"] = dy * static_cast<double>(ny-1);
dom2["coordsets/coords/origin/z"] = 0.;
add_field_selection_field(nx-1, ny-1, nz-1, 1,0, 33, 44, dom2);
}
if(mask & 8)
{
conduit::Node &dom3 = (dc > 1) ? output.append() : output;
conduit::blueprint::mesh::examples::braid("uniform", nx, ny, nz, dom3);
auto dx = dom3["coordsets/coords/spacing/dx"].to_float();
auto dy = dom3["coordsets/coords/spacing/dy"].to_float();
dom3["state/cycle"] = 1;
dom3["state/domain_id"] = 3;
dom3["coordsets/coords/origin/x"] = dx * static_cast<double>(nx-1);
dom3["coordsets/coords/origin/y"] = dy * static_cast<double>(ny-1);
dom3["coordsets/coords/origin/z"] = 0.;
add_field_selection_field(nx-1, ny-1, nz-1, 0,0, 55, 44, dom3);
}
}
}
//-----------------------------------------------------------------------------
// -- end parition --
//-----------------------------------------------------------------------------
#endif
| 37.350394 | 92 | 0.493412 | [
"mesh",
"vector"
] |
e5e3989e54a34dc0d026da5523587923b253865e | 42,096 | cpp | C++ | dbswzem/WzemHistRMUserUniversal.cpp | mpsitech/wzem-WhizniumSBE-Engine-Monitor | 0d9a204660bfad57f25dbd641fd86713986f32f1 | [
"MIT"
] | null | null | null | dbswzem/WzemHistRMUserUniversal.cpp | mpsitech/wzem-WhizniumSBE-Engine-Monitor | 0d9a204660bfad57f25dbd641fd86713986f32f1 | [
"MIT"
] | null | null | null | dbswzem/WzemHistRMUserUniversal.cpp | mpsitech/wzem-WhizniumSBE-Engine-Monitor | 0d9a204660bfad57f25dbd641fd86713986f32f1 | [
"MIT"
] | null | null | null | /**
* \file WzemHistRMUserUniversal.cpp
* database access for table TblWzemHistRMUserUniversal (implementation)
* \copyright (C) 2016-2020 MPSI Technologies GmbH
* \author Alexander Wirthmueller (auto-generation)
* \date created: 6 Dec 2020
*/
// IP header --- ABOVE
#include "WzemHistRMUserUniversal.h"
using namespace std;
using namespace Sbecore;
/******************************************************************************
class WzemHistRMUserUniversal
******************************************************************************/
WzemHistRMUserUniversal::WzemHistRMUserUniversal(
const ubigint ref
, const ubigint refWzemMUser
, const uint unvIxWzemVMaintable
, const ubigint unvUref
, const uint ixWzemVCard
, const uint ixWzemVPreset
, const uint preIxWzemVMaintable
, const ubigint preUref
, const uint start
) {
this->ref = ref;
this->refWzemMUser = refWzemMUser;
this->unvIxWzemVMaintable = unvIxWzemVMaintable;
this->unvUref = unvUref;
this->ixWzemVCard = ixWzemVCard;
this->ixWzemVPreset = ixWzemVPreset;
this->preIxWzemVMaintable = preIxWzemVMaintable;
this->preUref = preUref;
this->start = start;
};
bool WzemHistRMUserUniversal::operator==(
const WzemHistRMUserUniversal& comp
) {
return false;
};
bool WzemHistRMUserUniversal::operator!=(
const WzemHistRMUserUniversal& comp
) {
return(!operator==(comp));
};
/******************************************************************************
class ListWzemHistRMUserUniversal
******************************************************************************/
ListWzemHistRMUserUniversal::ListWzemHistRMUserUniversal() {
};
ListWzemHistRMUserUniversal::ListWzemHistRMUserUniversal(
const ListWzemHistRMUserUniversal& src
) {
nodes.resize(src.nodes.size(), NULL);
for (unsigned int i = 0; i < nodes.size(); i++) nodes[i] = new WzemHistRMUserUniversal(*(src.nodes[i]));
};
ListWzemHistRMUserUniversal::~ListWzemHistRMUserUniversal() {
clear();
};
void ListWzemHistRMUserUniversal::clear() {
for (unsigned int i = 0; i < nodes.size(); i++) if (nodes[i]) delete nodes[i];
nodes.resize(0);
};
unsigned int ListWzemHistRMUserUniversal::size() const {
return(nodes.size());
};
void ListWzemHistRMUserUniversal::append(
WzemHistRMUserUniversal* rec
) {
nodes.push_back(rec);
};
WzemHistRMUserUniversal* ListWzemHistRMUserUniversal::operator[](
const uint ix
) {
WzemHistRMUserUniversal* retval = NULL;
if (ix < size()) retval = nodes[ix];
return retval;
};
ListWzemHistRMUserUniversal& ListWzemHistRMUserUniversal::operator=(
const ListWzemHistRMUserUniversal& src
) {
WzemHistRMUserUniversal* rec;
if (&src != this) {
clear();
for (unsigned int i = 0; i < src.size(); i++) {
rec = new WzemHistRMUserUniversal(*(src.nodes[i]));
nodes.push_back(rec);
};
};
return(*this);
};
bool ListWzemHistRMUserUniversal::operator==(
const ListWzemHistRMUserUniversal& comp
) {
bool retval;
retval = (size() == comp.size());
if (retval) {
for (unsigned int i = 0; i < size(); i++) {
retval = ( *(nodes[i]) == *(comp.nodes[i]) );
if (!retval) break;
};
};
return retval;
};
bool ListWzemHistRMUserUniversal::operator!=(
const ListWzemHistRMUserUniversal& comp
) {
return(!operator==(comp));
};
/******************************************************************************
class TblWzemHistRMUserUniversal
******************************************************************************/
TblWzemHistRMUserUniversal::TblWzemHistRMUserUniversal() {
};
TblWzemHistRMUserUniversal::~TblWzemHistRMUserUniversal() {
};
bool TblWzemHistRMUserUniversal::loadRecBySQL(
const string& sqlstr
, WzemHistRMUserUniversal** rec
) {
return false;
};
ubigint TblWzemHistRMUserUniversal::loadRstBySQL(
const string& sqlstr
, const bool append
, ListWzemHistRMUserUniversal& rst
) {
return 0;
};
ubigint TblWzemHistRMUserUniversal::insertRec(
WzemHistRMUserUniversal* rec
) {
return 0;
};
ubigint TblWzemHistRMUserUniversal::insertNewRec(
WzemHistRMUserUniversal** rec
, const ubigint refWzemMUser
, const uint unvIxWzemVMaintable
, const ubigint unvUref
, const uint ixWzemVCard
, const uint ixWzemVPreset
, const uint preIxWzemVMaintable
, const ubigint preUref
, const uint start
) {
ubigint retval = 0;
WzemHistRMUserUniversal* _rec = NULL;
_rec = new WzemHistRMUserUniversal(0, refWzemMUser, unvIxWzemVMaintable, unvUref, ixWzemVCard, ixWzemVPreset, preIxWzemVMaintable, preUref, start);
insertRec(_rec);
retval = _rec->ref;
if (rec == NULL) delete _rec;
else *rec = _rec;
return retval;
};
ubigint TblWzemHistRMUserUniversal::appendNewRecToRst(
ListWzemHistRMUserUniversal& rst
, WzemHistRMUserUniversal** rec
, const ubigint refWzemMUser
, const uint unvIxWzemVMaintable
, const ubigint unvUref
, const uint ixWzemVCard
, const uint ixWzemVPreset
, const uint preIxWzemVMaintable
, const ubigint preUref
, const uint start
) {
ubigint retval = 0;
WzemHistRMUserUniversal* _rec = NULL;
retval = insertNewRec(&_rec, refWzemMUser, unvIxWzemVMaintable, unvUref, ixWzemVCard, ixWzemVPreset, preIxWzemVMaintable, preUref, start);
rst.nodes.push_back(_rec);
if (rec != NULL) *rec = _rec;
return retval;
};
void TblWzemHistRMUserUniversal::insertRst(
ListWzemHistRMUserUniversal& rst
, bool transact
) {
};
void TblWzemHistRMUserUniversal::updateRec(
WzemHistRMUserUniversal* rec
) {
};
void TblWzemHistRMUserUniversal::updateRst(
ListWzemHistRMUserUniversal& rst
, bool transact
) {
};
void TblWzemHistRMUserUniversal::removeRecByRef(
ubigint ref
) {
};
bool TblWzemHistRMUserUniversal::loadRecByRef(
ubigint ref
, WzemHistRMUserUniversal** rec
) {
return false;
};
bool TblWzemHistRMUserUniversal::loadRecByUsrMtbUnvCrd(
ubigint refWzemMUser
, uint unvIxWzemVMaintable
, ubigint unvUref
, uint ixWzemVCard
, WzemHistRMUserUniversal** rec
) {
return false;
};
ubigint TblWzemHistRMUserUniversal::loadRefsByUsrMtbCrd(
ubigint refWzemMUser
, uint unvIxWzemVMaintable
, uint ixWzemVCard
, const bool append
, vector<ubigint>& refs
, ubigint limit
, ubigint offset
) {
return 0;
};
ubigint TblWzemHistRMUserUniversal::loadRstByUsrCrd(
ubigint refWzemMUser
, uint ixWzemVCard
, const bool append
, ListWzemHistRMUserUniversal& rst
) {
return 0;
};
bool TblWzemHistRMUserUniversal::loadUnuByRef(
ubigint ref
, ubigint& unvUref
) {
return false;
};
ubigint TblWzemHistRMUserUniversal::loadRstByRefs(
vector<ubigint>& refs
, const bool append
, ListWzemHistRMUserUniversal& rst
) {
ubigint numload = 0;
WzemHistRMUserUniversal* rec = NULL;
if (!append) rst.clear();
for (unsigned int i = 0; i < refs.size(); i++) if (loadRecByRef(refs[i], &rec)) {
rst.nodes.push_back(rec);
numload++;
};
return numload;
};
#if defined(SBECORE_MAR) || defined(SBECORE_MY)
/******************************************************************************
class MyTblWzemHistRMUserUniversal
******************************************************************************/
MyTblWzemHistRMUserUniversal::MyTblWzemHistRMUserUniversal() :
TblWzemHistRMUserUniversal()
, MyTable()
{
stmtInsertRec = NULL;
stmtUpdateRec = NULL;
stmtRemoveRecByRef = NULL;
};
MyTblWzemHistRMUserUniversal::~MyTblWzemHistRMUserUniversal() {
if (stmtInsertRec) delete(stmtInsertRec);
if (stmtUpdateRec) delete(stmtUpdateRec);
if (stmtRemoveRecByRef) delete(stmtRemoveRecByRef);
};
void MyTblWzemHistRMUserUniversal::initStatements() {
stmtInsertRec = createStatement("INSERT INTO TblWzemHistRMUserUniversal (refWzemMUser, unvIxWzemVMaintable, unvUref, ixWzemVCard, ixWzemVPreset, preIxWzemVMaintable, preUref, start) VALUES (?,?,?,?,?,?,?,?)", false);
stmtUpdateRec = createStatement("UPDATE TblWzemHistRMUserUniversal SET refWzemMUser = ?, unvIxWzemVMaintable = ?, unvUref = ?, ixWzemVCard = ?, ixWzemVPreset = ?, preIxWzemVMaintable = ?, preUref = ?, start = ? WHERE ref = ?", false);
stmtRemoveRecByRef = createStatement("DELETE FROM TblWzemHistRMUserUniversal WHERE ref = ?", false);
};
bool MyTblWzemHistRMUserUniversal::loadRecBySQL(
const string& sqlstr
, WzemHistRMUserUniversal** rec
) {
MYSQL_RES* dbresult; MYSQL_ROW dbrow;
WzemHistRMUserUniversal* _rec = NULL;
bool retval = false;
if (mysql_real_query(dbs, sqlstr.c_str(), sqlstr.length())) {
string dbms = "MyTblWzemHistRMUserUniversal::loadRecBySQL() / " + string(mysql_error(dbs));
throw SbeException(SbeException::DBS_QUERY, {{"dbms",dbms}, {"sql",sqlstr}});
};
dbresult = mysql_store_result(dbs);
if (!dbresult) {
string dbms = "MyTblWzemHistRMUserUniversal::loadRecBySQL() / store result / " + string(mysql_error(dbs));
throw SbeException(SbeException::DBS_QUERY, {{"dbms",dbms}, {"sql",sqlstr}});
};
if (mysql_num_rows(dbresult) == 1) {
dbrow = mysql_fetch_row(dbresult);
_rec = new WzemHistRMUserUniversal();
if (dbrow[0]) _rec->ref = atoll((char*) dbrow[0]); else _rec->ref = 0;
if (dbrow[1]) _rec->refWzemMUser = atoll((char*) dbrow[1]); else _rec->refWzemMUser = 0;
if (dbrow[2]) _rec->unvIxWzemVMaintable = atol((char*) dbrow[2]); else _rec->unvIxWzemVMaintable = 0;
if (dbrow[3]) _rec->unvUref = atoll((char*) dbrow[3]); else _rec->unvUref = 0;
if (dbrow[4]) _rec->ixWzemVCard = atol((char*) dbrow[4]); else _rec->ixWzemVCard = 0;
if (dbrow[5]) _rec->ixWzemVPreset = atol((char*) dbrow[5]); else _rec->ixWzemVPreset = 0;
if (dbrow[6]) _rec->preIxWzemVMaintable = atol((char*) dbrow[6]); else _rec->preIxWzemVMaintable = 0;
if (dbrow[7]) _rec->preUref = atoll((char*) dbrow[7]); else _rec->preUref = 0;
if (dbrow[8]) _rec->start = atol((char*) dbrow[8]); else _rec->start = 0;
retval = true;
};
mysql_free_result(dbresult);
*rec = _rec;
return retval;
};
ubigint MyTblWzemHistRMUserUniversal::loadRstBySQL(
const string& sqlstr
, const bool append
, ListWzemHistRMUserUniversal& rst
) {
MYSQL_RES* dbresult; MYSQL_ROW dbrow; ubigint numrow; ubigint numread = 0;
WzemHistRMUserUniversal* rec;
if (!append) rst.clear();
if (mysql_real_query(dbs, sqlstr.c_str(), sqlstr.length())) {
string dbms = "MyTblWzemHistRMUserUniversal::loadRstBySQL() / " + string(mysql_error(dbs));
throw SbeException(SbeException::DBS_QUERY, {{"dbms",dbms}, {"sql",sqlstr}});
};
dbresult = mysql_store_result(dbs);
if (!dbresult) {
string dbms = "MyTblWzemHistRMUserUniversal::loadRstBySQL() / store result / " + string(mysql_error(dbs));
throw SbeException(SbeException::DBS_QUERY, {{"dbms",dbms}, {"sql",sqlstr}});
};
numrow = mysql_num_rows(dbresult);
if (numrow > 0) {
rst.nodes.reserve(rst.nodes.size() + numrow);
while (numread < numrow) {
dbrow = mysql_fetch_row(dbresult);
rec = new WzemHistRMUserUniversal();
if (dbrow[0]) rec->ref = atoll((char*) dbrow[0]); else rec->ref = 0;
if (dbrow[1]) rec->refWzemMUser = atoll((char*) dbrow[1]); else rec->refWzemMUser = 0;
if (dbrow[2]) rec->unvIxWzemVMaintable = atol((char*) dbrow[2]); else rec->unvIxWzemVMaintable = 0;
if (dbrow[3]) rec->unvUref = atoll((char*) dbrow[3]); else rec->unvUref = 0;
if (dbrow[4]) rec->ixWzemVCard = atol((char*) dbrow[4]); else rec->ixWzemVCard = 0;
if (dbrow[5]) rec->ixWzemVPreset = atol((char*) dbrow[5]); else rec->ixWzemVPreset = 0;
if (dbrow[6]) rec->preIxWzemVMaintable = atol((char*) dbrow[6]); else rec->preIxWzemVMaintable = 0;
if (dbrow[7]) rec->preUref = atoll((char*) dbrow[7]); else rec->preUref = 0;
if (dbrow[8]) rec->start = atol((char*) dbrow[8]); else rec->start = 0;
rst.nodes.push_back(rec);
numread++;
};
};
mysql_free_result(dbresult);
return(numread);
};
ubigint MyTblWzemHistRMUserUniversal::insertRec(
WzemHistRMUserUniversal* rec
) {
unsigned long l[8]; my_bool n[8]; my_bool e[8];
MYSQL_BIND bind[] = {
bindUbigint(&rec->refWzemMUser,&(l[0]),&(n[0]),&(e[0])),
bindUint(&rec->unvIxWzemVMaintable,&(l[1]),&(n[1]),&(e[1])),
bindUbigint(&rec->unvUref,&(l[2]),&(n[2]),&(e[2])),
bindUint(&rec->ixWzemVCard,&(l[3]),&(n[3]),&(e[3])),
bindUint(&rec->ixWzemVPreset,&(l[4]),&(n[4]),&(e[4])),
bindUint(&rec->preIxWzemVMaintable,&(l[5]),&(n[5]),&(e[5])),
bindUbigint(&rec->preUref,&(l[6]),&(n[6]),&(e[6])),
bindUint(&rec->start,&(l[7]),&(n[7]),&(e[7]))
};
if (mysql_stmt_bind_param(stmtInsertRec, bind)) {
string dbms = "MyTblWzemHistRMUserUniversal::insertRec() / bind / " + string(mysql_error(dbs));
throw SbeException(SbeException::DBS_STMTEXEC, {{"dbms",dbms}});
};
if (mysql_stmt_execute(stmtInsertRec)) {
string dbms = "MyTblWzemHistRMUserUniversal::insertRec() / " + string(mysql_error(dbs));
throw SbeException(SbeException::DBS_STMTEXEC, {{"dbms",dbms}});
};
rec->ref = mysql_stmt_insert_id(stmtInsertRec);
return rec->ref;
};
void MyTblWzemHistRMUserUniversal::insertRst(
ListWzemHistRMUserUniversal& rst
, bool transact
) {
if (transact) begin();
for (unsigned int i = 0; i < rst.nodes.size(); i++) insertRec(rst.nodes[i]);
if (transact) if (!commit()) for (unsigned int i=0;i<rst.nodes.size();i++) insertRec(rst.nodes[i]);
};
void MyTblWzemHistRMUserUniversal::updateRec(
WzemHistRMUserUniversal* rec
) {
unsigned long l[9]; my_bool n[9]; my_bool e[9];
MYSQL_BIND bind[] = {
bindUbigint(&rec->refWzemMUser,&(l[0]),&(n[0]),&(e[0])),
bindUint(&rec->unvIxWzemVMaintable,&(l[1]),&(n[1]),&(e[1])),
bindUbigint(&rec->unvUref,&(l[2]),&(n[2]),&(e[2])),
bindUint(&rec->ixWzemVCard,&(l[3]),&(n[3]),&(e[3])),
bindUint(&rec->ixWzemVPreset,&(l[4]),&(n[4]),&(e[4])),
bindUint(&rec->preIxWzemVMaintable,&(l[5]),&(n[5]),&(e[5])),
bindUbigint(&rec->preUref,&(l[6]),&(n[6]),&(e[6])),
bindUint(&rec->start,&(l[7]),&(n[7]),&(e[7])),
bindUbigint(&rec->ref,&(l[8]),&(n[8]),&(e[8]))
};
if (mysql_stmt_bind_param(stmtUpdateRec, bind)) {
string dbms = "MyTblWzemHistRMUserUniversal::updateRec() / bind / " + string(mysql_error(dbs));
throw SbeException(SbeException::DBS_STMTEXEC, {{"dbms",dbms}});
};
if (mysql_stmt_execute(stmtUpdateRec)) {
string dbms = "MyTblWzemHistRMUserUniversal::updateRec() / " + string(mysql_error(dbs));
throw SbeException(SbeException::DBS_STMTEXEC, {{"dbms",dbms}});
};
};
void MyTblWzemHistRMUserUniversal::updateRst(
ListWzemHistRMUserUniversal& rst
, bool transact
) {
if (transact) begin();
for (unsigned int i = 0; i < rst.nodes.size(); i++) updateRec(rst.nodes[i]);
if (transact) if (!commit()) for (unsigned int i = 0; i < rst.nodes.size(); i++) updateRec(rst.nodes[i]);
};
void MyTblWzemHistRMUserUniversal::removeRecByRef(
ubigint ref
) {
unsigned long l; my_bool n; my_bool e;
MYSQL_BIND bind = bindUbigint(&ref,&l,&n,&e);
if (mysql_stmt_bind_param(stmtRemoveRecByRef, &bind)) {
string dbms = "MyTblWzemHistRMUserUniversal::removeRecByRef() / bind / " + string(mysql_error(dbs));
throw SbeException(SbeException::DBS_STMTEXEC, {{"dbms",dbms}});
};
if (mysql_stmt_execute(stmtRemoveRecByRef)) {
string dbms = "MyTblWzemHistRMUserUniversal::removeRecByRef() / " + string(mysql_error(dbs));
throw SbeException(SbeException::DBS_STMTEXEC, {{"dbms",dbms}});
};
};
bool MyTblWzemHistRMUserUniversal::loadRecByRef(
ubigint ref
, WzemHistRMUserUniversal** rec
) {
if (ref == 0) {
*rec = NULL;
return false;
};
return loadRecBySQL("SELECT * FROM TblWzemHistRMUserUniversal WHERE ref = " + to_string(ref), rec);
};
bool MyTblWzemHistRMUserUniversal::loadRecByUsrMtbUnvCrd(
ubigint refWzemMUser
, uint unvIxWzemVMaintable
, ubigint unvUref
, uint ixWzemVCard
, WzemHistRMUserUniversal** rec
) {
return loadRecBySQL("SELECT ref, refWzemMUser, unvIxWzemVMaintable, unvUref, ixWzemVCard, ixWzemVPreset, preIxWzemVMaintable, preUref, start FROM TblWzemHistRMUserUniversal WHERE refWzemMUser = " + to_string(refWzemMUser) + " AND unvIxWzemVMaintable = " + to_string(unvIxWzemVMaintable) + " AND unvUref = " + to_string(unvUref) + " AND ixWzemVCard = " + to_string(ixWzemVCard) + "", rec);
};
ubigint MyTblWzemHistRMUserUniversal::loadRefsByUsrMtbCrd(
ubigint refWzemMUser
, uint unvIxWzemVMaintable
, uint ixWzemVCard
, const bool append
, vector<ubigint>& refs
, ubigint limit
, ubigint offset
) {
if ((limit == 0) && (offset == 0)) limit--;
return loadRefsBySQL("SELECT ref FROM TblWzemHistRMUserUniversal WHERE refWzemMUser = " + to_string(refWzemMUser) + " AND unvIxWzemVMaintable = " + to_string(unvIxWzemVMaintable) + " AND ixWzemVCard = " + to_string(ixWzemVCard) + " ORDER BY start DESC LIMIT " + to_string(offset) + "," + to_string(limit) + "", append, refs);
};
ubigint MyTblWzemHistRMUserUniversal::loadRstByUsrCrd(
ubigint refWzemMUser
, uint ixWzemVCard
, const bool append
, ListWzemHistRMUserUniversal& rst
) {
return loadRstBySQL("SELECT ref, refWzemMUser, unvIxWzemVMaintable, unvUref, ixWzemVCard, ixWzemVPreset, preIxWzemVMaintable, preUref, start FROM TblWzemHistRMUserUniversal WHERE refWzemMUser = " + to_string(refWzemMUser) + " AND ixWzemVCard = " + to_string(ixWzemVCard) + " ORDER BY start DESC", append, rst);
};
bool MyTblWzemHistRMUserUniversal::loadUnuByRef(
ubigint ref
, ubigint& unvUref
) {
return loadRefBySQL("SELECT unvUref FROM TblWzemHistRMUserUniversal WHERE ref = " + to_string(ref) + "", unvUref);
};
#endif
#if defined(SBECORE_PG)
/******************************************************************************
class PgTblWzemHistRMUserUniversal
******************************************************************************/
PgTblWzemHistRMUserUniversal::PgTblWzemHistRMUserUniversal() :
TblWzemHistRMUserUniversal()
, PgTable()
{
};
PgTblWzemHistRMUserUniversal::~PgTblWzemHistRMUserUniversal() {
// TODO: run SQL DEALLOCATE to free prepared statements
};
void PgTblWzemHistRMUserUniversal::initStatements() {
createStatement("TblWzemHistRMUserUniversal_insertRec", "INSERT INTO TblWzemHistRMUserUniversal (refWzemMUser, unvIxWzemVMaintable, unvUref, ixWzemVCard, ixWzemVPreset, preIxWzemVMaintable, preUref, start) VALUES ($1,$2,$3,$4,$5,$6,$7,$8) RETURNING ref", 8);
createStatement("TblWzemHistRMUserUniversal_updateRec", "UPDATE TblWzemHistRMUserUniversal SET refWzemMUser = $1, unvIxWzemVMaintable = $2, unvUref = $3, ixWzemVCard = $4, ixWzemVPreset = $5, preIxWzemVMaintable = $6, preUref = $7, start = $8 WHERE ref = $9", 9);
createStatement("TblWzemHistRMUserUniversal_removeRecByRef", "DELETE FROM TblWzemHistRMUserUniversal WHERE ref = $1", 1);
createStatement("TblWzemHistRMUserUniversal_loadRecByRef", "SELECT ref, refWzemMUser, unvIxWzemVMaintable, unvUref, ixWzemVCard, ixWzemVPreset, preIxWzemVMaintable, preUref, start FROM TblWzemHistRMUserUniversal WHERE ref = $1", 1);
createStatement("TblWzemHistRMUserUniversal_loadRecByUsrMtbUnvCrd", "SELECT ref, refWzemMUser, unvIxWzemVMaintable, unvUref, ixWzemVCard, ixWzemVPreset, preIxWzemVMaintable, preUref, start FROM TblWzemHistRMUserUniversal WHERE refWzemMUser = $1 AND unvIxWzemVMaintable = $2 AND unvUref = $3 AND ixWzemVCard = $4", 4);
createStatement("TblWzemHistRMUserUniversal_loadRefsByUsrMtbCrd", "SELECT ref FROM TblWzemHistRMUserUniversal WHERE refWzemMUser = $1 AND unvIxWzemVMaintable = $2 AND ixWzemVCard = $3 ORDER BY start DESC OFFSET $4 LIMIT $5", 5);
createStatement("TblWzemHistRMUserUniversal_loadRstByUsrCrd", "SELECT ref, refWzemMUser, unvIxWzemVMaintable, unvUref, ixWzemVCard, ixWzemVPreset, preIxWzemVMaintable, preUref, start FROM TblWzemHistRMUserUniversal WHERE refWzemMUser = $1 AND ixWzemVCard = $2 ORDER BY start DESC", 2);
createStatement("TblWzemHistRMUserUniversal_loadUnuByRef", "SELECT unvUref FROM TblWzemHistRMUserUniversal WHERE ref = $1", 1);
};
bool PgTblWzemHistRMUserUniversal::loadRec(
PGresult* res
, WzemHistRMUserUniversal** rec
) {
char* ptr;
WzemHistRMUserUniversal* _rec = NULL;
bool retval = false;
if (PQntuples(res) == 1) {
_rec = new WzemHistRMUserUniversal();
int fnum[] = {
PQfnumber(res, "ref"),
PQfnumber(res, "refwzemmuser"),
PQfnumber(res, "unvixwzemvmaintable"),
PQfnumber(res, "unvuref"),
PQfnumber(res, "ixwzemvcard"),
PQfnumber(res, "ixwzemvpreset"),
PQfnumber(res, "preixwzemvmaintable"),
PQfnumber(res, "preuref"),
PQfnumber(res, "start")
};
ptr = PQgetvalue(res, 0, fnum[0]); _rec->ref = atoll(ptr);
ptr = PQgetvalue(res, 0, fnum[1]); _rec->refWzemMUser = atoll(ptr);
ptr = PQgetvalue(res, 0, fnum[2]); _rec->unvIxWzemVMaintable = atol(ptr);
ptr = PQgetvalue(res, 0, fnum[3]); _rec->unvUref = atoll(ptr);
ptr = PQgetvalue(res, 0, fnum[4]); _rec->ixWzemVCard = atol(ptr);
ptr = PQgetvalue(res, 0, fnum[5]); _rec->ixWzemVPreset = atol(ptr);
ptr = PQgetvalue(res, 0, fnum[6]); _rec->preIxWzemVMaintable = atol(ptr);
ptr = PQgetvalue(res, 0, fnum[7]); _rec->preUref = atoll(ptr);
ptr = PQgetvalue(res, 0, fnum[8]); _rec->start = atol(ptr);
retval = true;
};
PQclear(res);
*rec = _rec;
return retval;
};
ubigint PgTblWzemHistRMUserUniversal::loadRst(
PGresult* res
, const bool append
, ListWzemHistRMUserUniversal& rst
) {
ubigint numrow; ubigint numread = 0; char* ptr;
WzemHistRMUserUniversal* rec;
if (!append) rst.clear();
numrow = PQntuples(res);
if (numrow > 0) {
rst.nodes.reserve(rst.nodes.size() + numrow);
int fnum[] = {
PQfnumber(res, "ref"),
PQfnumber(res, "refwzemmuser"),
PQfnumber(res, "unvixwzemvmaintable"),
PQfnumber(res, "unvuref"),
PQfnumber(res, "ixwzemvcard"),
PQfnumber(res, "ixwzemvpreset"),
PQfnumber(res, "preixwzemvmaintable"),
PQfnumber(res, "preuref"),
PQfnumber(res, "start")
};
while (numread < numrow) {
rec = new WzemHistRMUserUniversal();
ptr = PQgetvalue(res, numread, fnum[0]); rec->ref = atoll(ptr);
ptr = PQgetvalue(res, numread, fnum[1]); rec->refWzemMUser = atoll(ptr);
ptr = PQgetvalue(res, numread, fnum[2]); rec->unvIxWzemVMaintable = atol(ptr);
ptr = PQgetvalue(res, numread, fnum[3]); rec->unvUref = atoll(ptr);
ptr = PQgetvalue(res, numread, fnum[4]); rec->ixWzemVCard = atol(ptr);
ptr = PQgetvalue(res, numread, fnum[5]); rec->ixWzemVPreset = atol(ptr);
ptr = PQgetvalue(res, numread, fnum[6]); rec->preIxWzemVMaintable = atol(ptr);
ptr = PQgetvalue(res, numread, fnum[7]); rec->preUref = atoll(ptr);
ptr = PQgetvalue(res, numread, fnum[8]); rec->start = atol(ptr);
rst.nodes.push_back(rec);
numread++;
};
};
PQclear(res);
return numread;
};
bool PgTblWzemHistRMUserUniversal::loadRecByStmt(
const string& srefStmt
, const unsigned int N
, const char** vals
, const int* l
, const int* f
, WzemHistRMUserUniversal** rec
) {
PGresult* res;
res = PQexecPrepared(dbs, srefStmt.c_str(), N, vals, l, f, 0);
if (PQresultStatus(res) != PGRES_TUPLES_OK) {
string dbms = "PgTblWzemHistRMUserUniversal::loadRecByStmt(" + srefStmt + ") / " + string(PQerrorMessage(dbs));
throw SbeException(SbeException::DBS_STMTEXEC, {{"dbms",dbms}});
};
return loadRec(res, rec);
};
ubigint PgTblWzemHistRMUserUniversal::loadRstByStmt(
const string& srefStmt
, const unsigned int N
, const char** vals
, const int* l
, const int* f
, const bool append
, ListWzemHistRMUserUniversal& rst
) {
PGresult* res;
res = PQexecPrepared(dbs, srefStmt.c_str(), N, vals, l, f, 0);
if (PQresultStatus(res) != PGRES_TUPLES_OK) {
string dbms = "PgTblWzemHistRMUserUniversal::loadRstByStmt(" + srefStmt + ") / " + string(PQerrorMessage(dbs));
throw SbeException(SbeException::DBS_STMTEXEC, {{"dbms",dbms}});
};
return loadRst(res, append, rst);
};
bool PgTblWzemHistRMUserUniversal::loadRecBySQL(
const string& sqlstr
, WzemHistRMUserUniversal** rec
) {
PGresult* res;
res = PQexec(dbs, sqlstr.c_str());
if (PQresultStatus(res) != PGRES_TUPLES_OK) {
string dbms = "PgTblWzemHistRMUserUniversal::loadRecBySQL() / " + string(PQerrorMessage(dbs));
throw SbeException(SbeException::DBS_QUERY, {{"dbms",dbms}, {"sql",sqlstr}});
};
return loadRec(res, rec);
};
ubigint PgTblWzemHistRMUserUniversal::loadRstBySQL(
const string& sqlstr
, const bool append
, ListWzemHistRMUserUniversal& rst
) {
PGresult* res;
res = PQexec(dbs, sqlstr.c_str());
if (PQresultStatus(res) != PGRES_TUPLES_OK) {
string dbms = "PgTblWzemHistRMUserUniversal::loadRstBySQL() / " + string(PQerrorMessage(dbs));
throw SbeException(SbeException::DBS_QUERY, {{"dbms",dbms}, {"sql",sqlstr}});
};
return loadRst(res, append, rst);
};
ubigint PgTblWzemHistRMUserUniversal::insertRec(
WzemHistRMUserUniversal* rec
) {
PGresult* res;
char* ptr;
ubigint _refWzemMUser = htonl64(rec->refWzemMUser);
uint _unvIxWzemVMaintable = htonl(rec->unvIxWzemVMaintable);
ubigint _unvUref = htonl64(rec->unvUref);
uint _ixWzemVCard = htonl(rec->ixWzemVCard);
uint _ixWzemVPreset = htonl(rec->ixWzemVPreset);
uint _preIxWzemVMaintable = htonl(rec->preIxWzemVMaintable);
ubigint _preUref = htonl64(rec->preUref);
uint _start = htonl(rec->start);
const char* vals[] = {
(char*) &_refWzemMUser,
(char*) &_unvIxWzemVMaintable,
(char*) &_unvUref,
(char*) &_ixWzemVCard,
(char*) &_ixWzemVPreset,
(char*) &_preIxWzemVMaintable,
(char*) &_preUref,
(char*) &_start
};
const int l[] = {
sizeof(ubigint),
sizeof(uint),
sizeof(ubigint),
sizeof(uint),
sizeof(uint),
sizeof(uint),
sizeof(ubigint),
sizeof(uint)
};
const int f[] = {1, 1, 1, 1, 1, 1, 1, 1};
res = PQexecPrepared(dbs, "TblWzemHistRMUserUniversal_insertRec", 8, vals, l, f, 0);
if (PQresultStatus(res) != PGRES_TUPLES_OK) {
string dbms = "PgTblWzemHistRMUserUniversal::insertRec() / " + string(PQerrorMessage(dbs));
throw SbeException(SbeException::DBS_STMTEXEC, {{"dbms",dbms}});
};
ptr = PQgetvalue(res, 0, 0); rec->ref = atoll(ptr);
PQclear(res);
return rec->ref;
};
void PgTblWzemHistRMUserUniversal::insertRst(
ListWzemHistRMUserUniversal& rst
, bool transact
) {
if (transact) begin();
for (unsigned int i = 0; i < rst.nodes.size(); i++) insertRec(rst.nodes[i]);
if (transact) if (!commit()) for (unsigned int i = 0; i < rst.nodes.size(); i++) insertRec(rst.nodes[i]);
};
void PgTblWzemHistRMUserUniversal::updateRec(
WzemHistRMUserUniversal* rec
) {
PGresult* res;
ubigint _refWzemMUser = htonl64(rec->refWzemMUser);
uint _unvIxWzemVMaintable = htonl(rec->unvIxWzemVMaintable);
ubigint _unvUref = htonl64(rec->unvUref);
uint _ixWzemVCard = htonl(rec->ixWzemVCard);
uint _ixWzemVPreset = htonl(rec->ixWzemVPreset);
uint _preIxWzemVMaintable = htonl(rec->preIxWzemVMaintable);
ubigint _preUref = htonl64(rec->preUref);
uint _start = htonl(rec->start);
ubigint _ref = htonl64(rec->ref);
const char* vals[] = {
(char*) &_refWzemMUser,
(char*) &_unvIxWzemVMaintable,
(char*) &_unvUref,
(char*) &_ixWzemVCard,
(char*) &_ixWzemVPreset,
(char*) &_preIxWzemVMaintable,
(char*) &_preUref,
(char*) &_start,
(char*) &_ref
};
const int l[] = {
sizeof(ubigint),
sizeof(uint),
sizeof(ubigint),
sizeof(uint),
sizeof(uint),
sizeof(uint),
sizeof(ubigint),
sizeof(uint),
sizeof(ubigint)
};
const int f[] = {1, 1, 1, 1, 1, 1, 1, 1, 1};
res = PQexecPrepared(dbs, "TblWzemHistRMUserUniversal_updateRec", 9, vals, l, f, 0);
if (PQresultStatus(res) != PGRES_COMMAND_OK) {
string dbms = "PgTblWzemHistRMUserUniversal::updateRec() / " + string(PQerrorMessage(dbs));
throw SbeException(SbeException::DBS_STMTEXEC, {{"dbms",dbms}});
};
PQclear(res);
};
void PgTblWzemHistRMUserUniversal::updateRst(
ListWzemHistRMUserUniversal& rst
, bool transact
) {
if (transact) begin();
for (unsigned int i = 0; i < rst.nodes.size(); i++) updateRec(rst.nodes[i]);
if (transact) if (!commit()) for (unsigned int i = 0; i < rst.nodes.size(); i++) updateRec(rst.nodes[i]);
};
void PgTblWzemHistRMUserUniversal::removeRecByRef(
ubigint ref
) {
PGresult* res;
ubigint _ref = htonl64(ref);
const char* vals[] = {
(char*) &_ref
};
const int l[] = {
sizeof(ubigint)
};
const int f[] = {1};
res = PQexecPrepared(dbs, "TblWzemHistRMUserUniversal_removeRecByRef", 1, vals, l, f, 0);
if (PQresultStatus(res) != PGRES_COMMAND_OK) {
string dbms = "PgTblWzemHistRMUserUniversal::removeRecByRef() / " + string(PQerrorMessage(dbs));
throw SbeException(SbeException::DBS_STMTEXEC, {{"dbms",dbms}});
};
PQclear(res);
};
bool PgTblWzemHistRMUserUniversal::loadRecByRef(
ubigint ref
, WzemHistRMUserUniversal** rec
) {
if (ref == 0) {
*rec = NULL;
return false;
};
ubigint _ref = htonl64(ref);
const char* vals[] = {
(char*) &_ref
};
const int l[] = {
sizeof(ubigint)
};
const int f[] = {1};
return loadRecByStmt("TblWzemHistRMUserUniversal_loadRecByRef", 1, vals, l, f, rec);
};
bool PgTblWzemHistRMUserUniversal::loadRecByUsrMtbUnvCrd(
ubigint refWzemMUser
, uint unvIxWzemVMaintable
, ubigint unvUref
, uint ixWzemVCard
, WzemHistRMUserUniversal** rec
) {
ubigint _refWzemMUser = htonl64(refWzemMUser);
uint _unvIxWzemVMaintable = htonl(unvIxWzemVMaintable);
ubigint _unvUref = htonl64(unvUref);
uint _ixWzemVCard = htonl(ixWzemVCard);
const char* vals[] = {
(char*) &_refWzemMUser,
(char*) &_unvIxWzemVMaintable,
(char*) &_unvUref,
(char*) &_ixWzemVCard
};
const int l[] = {
sizeof(ubigint),
sizeof(uint),
sizeof(ubigint),
sizeof(uint)
};
const int f[] = {1,1,1,1};
return loadRecByStmt("TblWzemHistRMUserUniversal_loadRecByUsrMtbUnvCrd", 4, vals, l, f, rec);
};
ubigint PgTblWzemHistRMUserUniversal::loadRefsByUsrMtbCrd(
ubigint refWzemMUser
, uint unvIxWzemVMaintable
, uint ixWzemVCard
, const bool append
, vector<ubigint>& refs
, ubigint limit
, ubigint offset
) {
ubigint _refWzemMUser = htonl64(refWzemMUser);
uint _unvIxWzemVMaintable = htonl(unvIxWzemVMaintable);
uint _ixWzemVCard = htonl(ixWzemVCard);
ubigint _offset = htonl64(offset);
ubigint _limit = htonl64(limit);
char* _limitptr = NULL;
int _limitl = 0;
if (limit != 0) {
_limitptr = (char*) &_limit;
_limitl = sizeof(ubigint);
};
const char* vals[] = {
(char*) &_refWzemMUser,
(char*) &_unvIxWzemVMaintable,
(char*) &_ixWzemVCard,
(char*) &_offset,
_limitptr
};
const int l[] = {
sizeof(ubigint),
sizeof(uint),
sizeof(uint),
sizeof(ubigint),
_limitl
};
const int f[] = {1,1,1,1,1};
return loadRefsByStmt("TblWzemHistRMUserUniversal_loadRefsByUsrMtbCrd", 3, vals, l, f, append, refs);
};
ubigint PgTblWzemHistRMUserUniversal::loadRstByUsrCrd(
ubigint refWzemMUser
, uint ixWzemVCard
, const bool append
, ListWzemHistRMUserUniversal& rst
) {
ubigint _refWzemMUser = htonl64(refWzemMUser);
uint _ixWzemVCard = htonl(ixWzemVCard);
const char* vals[] = {
(char*) &_refWzemMUser,
(char*) &_ixWzemVCard
};
const int l[] = {
sizeof(ubigint),
sizeof(uint)
};
const int f[] = {1,1};
return loadRstByStmt("TblWzemHistRMUserUniversal_loadRstByUsrCrd", 2, vals, l, f, append, rst);
};
bool PgTblWzemHistRMUserUniversal::loadUnuByRef(
ubigint ref
, ubigint& unvUref
) {
ubigint _ref = htonl64(ref);
const char* vals[] = {
(char*) &_ref
};
const int l[] = {
sizeof(ubigint)
};
const int f[] = {1};
return loadRefByStmt("TblWzemHistRMUserUniversal_loadUnuByRef", 1, vals, l, f, unvUref);
};
#endif
#if defined(SBECORE_LITE)
/******************************************************************************
class LiteTblWzemHistRMUserUniversal
******************************************************************************/
LiteTblWzemHistRMUserUniversal::LiteTblWzemHistRMUserUniversal() :
TblWzemHistRMUserUniversal()
, LiteTable()
{
stmtInsertRec = NULL;
stmtUpdateRec = NULL;
stmtRemoveRecByRef = NULL;
stmtLoadRecByUsrMtbUnvCrd = NULL;
stmtLoadRefsByUsrMtbCrd = NULL;
stmtLoadRstByUsrCrd = NULL;
stmtLoadUnuByRef = NULL;
};
LiteTblWzemHistRMUserUniversal::~LiteTblWzemHistRMUserUniversal() {
if (stmtInsertRec) sqlite3_finalize(stmtInsertRec);
if (stmtUpdateRec) sqlite3_finalize(stmtUpdateRec);
if (stmtRemoveRecByRef) sqlite3_finalize(stmtRemoveRecByRef);
if (stmtLoadRecByUsrMtbUnvCrd) sqlite3_finalize(stmtLoadRecByUsrMtbUnvCrd);
if (stmtLoadRefsByUsrMtbCrd) sqlite3_finalize(stmtLoadRefsByUsrMtbCrd);
if (stmtLoadRstByUsrCrd) sqlite3_finalize(stmtLoadRstByUsrCrd);
if (stmtLoadUnuByRef) sqlite3_finalize(stmtLoadUnuByRef);
};
void LiteTblWzemHistRMUserUniversal::initStatements() {
stmtInsertRec = createStatement("INSERT INTO TblWzemHistRMUserUniversal (refWzemMUser, unvIxWzemVMaintable, unvUref, ixWzemVCard, ixWzemVPreset, preIxWzemVMaintable, preUref, start) VALUES (?1,?2,?3,?4,?5,?6,?7,?8)");
stmtUpdateRec = createStatement("UPDATE TblWzemHistRMUserUniversal SET refWzemMUser = ?1, unvIxWzemVMaintable = ?2, unvUref = ?3, ixWzemVCard = ?4, ixWzemVPreset = ?5, preIxWzemVMaintable = ?6, preUref = ?7, start = ?8 WHERE ref = ?9");
stmtRemoveRecByRef = createStatement("DELETE FROM TblWzemHistRMUserUniversal WHERE ref = ?1");
stmtLoadRecByRef = createStatement("SELECT ref, refWzemMUser, unvIxWzemVMaintable, unvUref, ixWzemVCard, ixWzemVPreset, preIxWzemVMaintable, preUref, start FROM TblWzemHistRMUserUniversal WHERE ref = ?1");
stmtLoadRecByUsrMtbUnvCrd = createStatement("SELECT ref, refWzemMUser, unvIxWzemVMaintable, unvUref, ixWzemVCard, ixWzemVPreset, preIxWzemVMaintable, preUref, start FROM TblWzemHistRMUserUniversal WHERE refWzemMUser = ?1 AND unvIxWzemVMaintable = ?2 AND unvUref = ?3 AND ixWzemVCard = ?4");
stmtLoadRefsByUsrMtbCrd = createStatement("SELECT ref FROM TblWzemHistRMUserUniversal WHERE refWzemMUser = ?1 AND unvIxWzemVMaintable = ?2 AND ixWzemVCard = ?3 ORDER BY start DESC LIMIT ?,?");
stmtLoadRstByUsrCrd = createStatement("SELECT ref, refWzemMUser, unvIxWzemVMaintable, unvUref, ixWzemVCard, ixWzemVPreset, preIxWzemVMaintable, preUref, start FROM TblWzemHistRMUserUniversal WHERE refWzemMUser = ?1 AND ixWzemVCard = ?2 ORDER BY start DESC");
stmtLoadUnuByRef = createStatement("SELECT unvUref FROM TblWzemHistRMUserUniversal WHERE ref = ?1");
};
bool LiteTblWzemHistRMUserUniversal::loadRec(
sqlite3_stmt* stmt
, WzemHistRMUserUniversal** rec
) {
int res;
WzemHistRMUserUniversal* _rec = NULL;
bool retval = false;
res = sqlite3_step(stmt);
if (res == SQLITE_ROW) {
_rec = new WzemHistRMUserUniversal();
_rec->ref = sqlite3_column_int64(stmt, 0);
_rec->refWzemMUser = sqlite3_column_int64(stmt, 1);
_rec->unvIxWzemVMaintable = sqlite3_column_int(stmt, 2);
_rec->unvUref = sqlite3_column_int64(stmt, 3);
_rec->ixWzemVCard = sqlite3_column_int(stmt, 4);
_rec->ixWzemVPreset = sqlite3_column_int(stmt, 5);
_rec->preIxWzemVMaintable = sqlite3_column_int(stmt, 6);
_rec->preUref = sqlite3_column_int64(stmt, 7);
_rec->start = sqlite3_column_int(stmt, 8);
res = sqlite3_step(stmt);
if (res == SQLITE_DONE) {
*rec = _rec;
retval = true;
} else {
delete _rec;
};
};
return retval;
};
ubigint LiteTblWzemHistRMUserUniversal::loadRst(
sqlite3_stmt* stmt
, const bool append
, ListWzemHistRMUserUniversal& rst
) {
int res; ubigint numread = 0;
WzemHistRMUserUniversal* rec;
if (!append) rst.clear();
res = sqlite3_step(stmt);
while (res == SQLITE_ROW) {
rec = new WzemHistRMUserUniversal();
rec->ref = sqlite3_column_int64(stmt, 0);
rec->refWzemMUser = sqlite3_column_int64(stmt, 1);
rec->unvIxWzemVMaintable = sqlite3_column_int(stmt, 2);
rec->unvUref = sqlite3_column_int64(stmt, 3);
rec->ixWzemVCard = sqlite3_column_int(stmt, 4);
rec->ixWzemVPreset = sqlite3_column_int(stmt, 5);
rec->preIxWzemVMaintable = sqlite3_column_int(stmt, 6);
rec->preUref = sqlite3_column_int64(stmt, 7);
rec->start = sqlite3_column_int(stmt, 8);
rst.nodes.push_back(rec);
numread++;
res = sqlite3_step(stmt);
};
return(numread);
};
bool LiteTblWzemHistRMUserUniversal::loadRecByStmt(
sqlite3_stmt* stmt
, WzemHistRMUserUniversal** rec
) {
bool retval = loadRec(stmt, rec);
sqlite3_reset(stmt);
return retval;
};
ubigint LiteTblWzemHistRMUserUniversal::loadRstByStmt(
sqlite3_stmt* stmt
, const bool append
, ListWzemHistRMUserUniversal& rst
) {
ubigint retval = loadRst(stmt, append, rst);
sqlite3_reset(stmt);
return retval;
};
bool LiteTblWzemHistRMUserUniversal::loadRecBySQL(
const string& sqlstr
, WzemHistRMUserUniversal** rec
) {
int res;
sqlite3_stmt* stmt;
bool retval = false;
res = sqlite3_prepare_v2(dbs, sqlstr.c_str(), sqlstr.length()+1, &stmt, NULL);
if (res != SQLITE_OK) {
string dbms = "LiteTblWzemHistRMUserUniversal::loadRecBySQL() / " + string(sqlite3_errmsg(dbs));
throw SbeException(SbeException::DBS_QUERY, {{"dbms",dbms}, {"sql",sqlstr}});
};
retval = loadRec(stmt, rec);
sqlite3_finalize(stmt);
return retval;
};
ubigint LiteTblWzemHistRMUserUniversal::loadRstBySQL(
const string& sqlstr
, const bool append
, ListWzemHistRMUserUniversal& rst
) {
int res;
sqlite3_stmt* stmt;
ubigint retval = 0;
res = sqlite3_prepare_v2(dbs, sqlstr.c_str(), sqlstr.length()+1, &stmt, NULL);
if (res != SQLITE_OK) {
string dbms = "LiteTblWzemHistRMUserUniversal::loadRstBySQL() / " + string(sqlite3_errmsg(dbs));
throw SbeException(SbeException::DBS_QUERY, {{"dbms",dbms}, {"sql",sqlstr}});
};
retval = loadRst(stmt, append, rst);
sqlite3_finalize(stmt);
return retval;
};
ubigint LiteTblWzemHistRMUserUniversal::insertRec(
WzemHistRMUserUniversal* rec
) {
sqlite3_bind_int64(stmtInsertRec, 1, rec->refWzemMUser);
sqlite3_bind_int(stmtInsertRec, 2, rec->unvIxWzemVMaintable);
sqlite3_bind_int64(stmtInsertRec, 3, rec->unvUref);
sqlite3_bind_int(stmtInsertRec, 4, rec->ixWzemVCard);
sqlite3_bind_int(stmtInsertRec, 5, rec->ixWzemVPreset);
sqlite3_bind_int(stmtInsertRec, 6, rec->preIxWzemVMaintable);
sqlite3_bind_int64(stmtInsertRec, 7, rec->preUref);
sqlite3_bind_int(stmtInsertRec, 8, rec->start);
if (sqlite3_step(stmtInsertRec) != SQLITE_DONE) {
string dbms = "LiteTblWzemHistRMUserUniversal::insertRec() / " + string(sqlite3_errmsg(dbs));
throw SbeException(SbeException::DBS_STMTEXEC, {{"dbms",dbms}});
};
rec->ref = sqlite3_last_insert_rowid(dbs);
sqlite3_reset(stmtInsertRec);
return rec->ref;
};
void LiteTblWzemHistRMUserUniversal::insertRst(
ListWzemHistRMUserUniversal& rst
, bool transact
) {
if (transact) begin();
for (unsigned int i = 0; i < rst.nodes.size(); i++) insertRec(rst.nodes[i]);
if (transact) if (!commit()) for (unsigned int i = 0; i < rst.nodes.size(); i++) insertRec(rst.nodes[i]);
};
void LiteTblWzemHistRMUserUniversal::updateRec(
WzemHistRMUserUniversal* rec
) {
sqlite3_bind_int64(stmtUpdateRec, 1, rec->refWzemMUser);
sqlite3_bind_int(stmtUpdateRec, 2, rec->unvIxWzemVMaintable);
sqlite3_bind_int64(stmtUpdateRec, 3, rec->unvUref);
sqlite3_bind_int(stmtUpdateRec, 4, rec->ixWzemVCard);
sqlite3_bind_int(stmtUpdateRec, 5, rec->ixWzemVPreset);
sqlite3_bind_int(stmtUpdateRec, 6, rec->preIxWzemVMaintable);
sqlite3_bind_int64(stmtUpdateRec, 7, rec->preUref);
sqlite3_bind_int(stmtUpdateRec, 8, rec->start);
sqlite3_bind_int64(stmtUpdateRec, 9, rec->ref);
if (sqlite3_step(stmtUpdateRec) != SQLITE_DONE) {
string dbms = "LiteTblWzemHistRMUserUniversal::updateRec() / " + string(sqlite3_errmsg(dbs));
throw SbeException(SbeException::DBS_STMTEXEC, {{"dbms",dbms}});
};
sqlite3_reset(stmtUpdateRec);
};
void LiteTblWzemHistRMUserUniversal::updateRst(
ListWzemHistRMUserUniversal& rst
, bool transact
) {
if (transact) begin();
for (unsigned int i = 0; i < rst.nodes.size(); i++) updateRec(rst.nodes[i]);
if (transact) if (!commit()) for (unsigned int i = 0; i < rst.nodes.size(); i++) updateRec(rst.nodes[i]);
};
void LiteTblWzemHistRMUserUniversal::removeRecByRef(
ubigint ref
) {
sqlite3_bind_int64(stmtRemoveRecByRef, 1, ref);
if (sqlite3_step(stmtRemoveRecByRef) != SQLITE_DONE) {
string dbms = "LiteTblWzemHistRMUserUniversal::removeRecByRef() / " + string(sqlite3_errmsg(dbs));
throw SbeException(SbeException::DBS_STMTEXEC, {{"dbms",dbms}});
};
sqlite3_reset(stmtRemoveRecByRef);
};
bool LiteTblWzemHistRMUserUniversal::loadRecByRef(
ubigint ref
, WzemHistRMUserUniversal** rec
) {
if (ref == 0) {
*rec = NULL;
return false;
};
sqlite3_bind_int64(stmtLoadRecByRef, 1, ref);
return loadRecByStmt(stmtLoadRecByRef, rec);
};
bool LiteTblWzemHistRMUserUniversal::loadRecByUsrMtbUnvCrd(
ubigint refWzemMUser
, uint unvIxWzemVMaintable
, ubigint unvUref
, uint ixWzemVCard
, WzemHistRMUserUniversal** rec
) {
sqlite3_bind_int64(stmtLoadRecByUsrMtbUnvCrd, 1, refWzemMUser);
sqlite3_bind_int(stmtLoadRecByUsrMtbUnvCrd, 2, unvIxWzemVMaintable);
sqlite3_bind_int64(stmtLoadRecByUsrMtbUnvCrd, 3, unvUref);
sqlite3_bind_int(stmtLoadRecByUsrMtbUnvCrd, 4, ixWzemVCard);
return loadRecByStmt(stmtLoadRecByUsrMtbUnvCrd, rec);
};
ubigint LiteTblWzemHistRMUserUniversal::loadRefsByUsrMtbCrd(
ubigint refWzemMUser
, uint unvIxWzemVMaintable
, uint ixWzemVCard
, const bool append
, vector<ubigint>& refs
, ubigint limit
, ubigint offset
) {
sqlite3_bind_int64(stmtLoadRefsByUsrMtbCrd, 1, refWzemMUser);
sqlite3_bind_int(stmtLoadRefsByUsrMtbCrd, 2, unvIxWzemVMaintable);
sqlite3_bind_int(stmtLoadRefsByUsrMtbCrd, 3, ixWzemVCard);
sqlite3_bind_int64(stmtLoadRefsByUsrMtbCrd, 4, offset);
if (limit == 0) sqlite3_bind_int64(stmtLoadRefsByUsrMtbCrd, 5, -1); else sqlite3_bind_int64(stmtLoadRefsByUsrMtbCrd, 5, limit);
return loadRefsByStmt(stmtLoadRefsByUsrMtbCrd, append, refs);
};
ubigint LiteTblWzemHistRMUserUniversal::loadRstByUsrCrd(
ubigint refWzemMUser
, uint ixWzemVCard
, const bool append
, ListWzemHistRMUserUniversal& rst
) {
sqlite3_bind_int64(stmtLoadRstByUsrCrd, 1, refWzemMUser);
sqlite3_bind_int(stmtLoadRstByUsrCrd, 2, ixWzemVCard);
return loadRstByStmt(stmtLoadRstByUsrCrd, append, rst);
};
bool LiteTblWzemHistRMUserUniversal::loadUnuByRef(
ubigint ref
, ubigint& unvUref
) {
sqlite3_bind_int64(stmtLoadUnuByRef, 1, ref);
return loadRefByStmt(stmtLoadUnuByRef, unvUref);
};
#endif
| 30.884813 | 389 | 0.701326 | [
"vector"
] |
e5e8b209e66cbd3596a71899213855d9ad635963 | 3,534 | cc | C++ | kernel/krnl/irq.cc | foreverbell/BadAppleOS | 695e4de5f41cc64e0d6a1b147ab6d84d50b91416 | [
"MIT"
] | 52 | 2015-07-11T02:35:11.000Z | 2022-01-06T22:03:23.000Z | kernel/krnl/irq.cc | foreverbell/BadAppleOS | 695e4de5f41cc64e0d6a1b147ab6d84d50b91416 | [
"MIT"
] | null | null | null | kernel/krnl/irq.cc | foreverbell/BadAppleOS | 695e4de5f41cc64e0d6a1b147ab6d84d50b91416 | [
"MIT"
] | 3 | 2018-06-10T06:52:37.000Z | 2021-11-05T05:49:15.000Z |
#include <stdint.h>
#include <system.h>
#include <port.h>
#include <stdio.h>
#include <string.h>
#include <linkage.h>
asmlinkage {
void irq_handler0();
void irq_handler1();
void irq_handler2();
void irq_handler3();
void irq_handler4();
void irq_handler5();
void irq_handler6();
void irq_handler7();
void irq_handler8();
void irq_handler9();
void irq_handler10();
void irq_handler11();
void irq_handler12();
void irq_handler13();
void irq_handler14();
void irq_handler15();
}
namespace irq {
namespace {
#define IRQ_VECTOR_OFFSET 32
#define MAX_IRQ_ENTRY 16
#define PORT_MASTER_PIC_CMD 0x20
#define PORT_MASTER_PIC_DAT 0x21
#define PORT_SLAVE_PIC_CMD 0xa0
#define PORT_SLAVE_PIC_DAT 0xa1
fn_irq_handler_t lpfn_irq_handler[MAX_IRQ_ENTRY];
void dispatcher(irq_context_t *ptr) {
int irq_index = ptr->irq_index;
fn_irq_handler_t handler = lpfn_irq_handler[irq_index];
if (handler == NULL) {
printf("[IRQ dispatcher] Unhandled IRQ %d.\n", irq_index);
} else {
handler(ptr);
}
/* send an EOI (end of interrupt) to indicate that we are done. */
if (irq_index >= 8) {
port::outb(PORT_SLAVE_PIC_CMD, 0x20);
}
port::outb(PORT_MASTER_PIC_CMD, 0x20);
}
}
void initialize(void) {
/* remap IRQ to proper IDT entries (32 ~ 47) */
port::outb(PORT_MASTER_PIC_CMD, 0x11);
port::outb(PORT_SLAVE_PIC_CMD, 0x11);
port::outb(PORT_MASTER_PIC_DAT, IRQ_VECTOR_OFFSET); // vector offset for master PIC is 32
port::outb(PORT_SLAVE_PIC_DAT, IRQ_VECTOR_OFFSET + 8); // vector offset for slave PIC is 40
port::outb(PORT_MASTER_PIC_DAT, 0x4); // tell master PIC that there is a slave PIC at IRQ2
port::outb(PORT_SLAVE_PIC_DAT, 0x2); // tell slave PIC its cascade identity
port::outb(PORT_MASTER_PIC_DAT, 0x1);
port::outb(PORT_SLAVE_PIC_DAT, 0x1);
/* disable all IRQs by default. */
port::outb(PORT_MASTER_PIC_DAT, 0xff);
port::outb(PORT_SLAVE_PIC_DAT, 0xff);
/* initialize IRQ to correct entries in the IDT. */
#define set_irq(n) idt::set_gate(n + IRQ_VECTOR_OFFSET, (uint32_t) irq_handler##n, KERNEL_CODE_SEL, 0x8e);
set_irq(0);
set_irq(1);
set_irq(2);
set_irq(3);
set_irq(4);
set_irq(5);
set_irq(6);
set_irq(7);
set_irq(8);
set_irq(9);
set_irq(10);
set_irq(11);
set_irq(12);
set_irq(13);
set_irq(14);
set_irq(15);
#undef set_irq
memset(lpfn_irq_handler, 0, sizeof(lpfn_irq_handler));
}
/* install an IRQ handler. */
void install(int index, fn_irq_handler_t handler) {
if (lpfn_irq_handler[index] != NULL) {
printf("[irq::install] IRQ%d handler already exists, overwritten.\n", index);
}
lpfn_irq_handler[index] = handler;
}
/* uninstall an IRQ handler. */
void uninstall(int index) {
if (lpfn_irq_handler[index] == NULL) {
printf("[irq::uninstall] IRQ%d handler not exists.\n", index);
}
lpfn_irq_handler[index] = NULL;
}
/* disable an IRQ by setting mask. */
void disable(int index) {
uint16_t port;
uint8_t value;
if (index < 8) {
port = PORT_MASTER_PIC_DAT;
} else {
port = PORT_SLAVE_PIC_DAT;
index -= 8;
}
value = port::inb(port) | (1 << index);
port::outb(port, value);
}
/* enable an IRQ by clearing mask. */
void enable(int index) {
uint16_t port;
uint8_t value;
if (index < 8) {
port = PORT_MASTER_PIC_DAT;
} else {
port = PORT_SLAVE_PIC_DAT;
index -= 8;
}
value = port::inb(port) & ~(1 << index);
port::outb(port, value);
}
} /* irq */
asmlinkage void irq_dispatcher(irq::irq_context_t *ptr) {
irq::dispatcher(ptr);
}
| 23.403974 | 110 | 0.684493 | [
"vector"
] |
e5eb1e2772bb2879f72ed879d7c7bb77b2103a89 | 235 | cpp | C++ | sprint01/t01/main.cpp | viacheslavpleshkov/unit-factory-ucode-half-marathon-c | 9ff260290382ea03b07e28a92c0f922ec85d31d0 | [
"MIT"
] | null | null | null | sprint01/t01/main.cpp | viacheslavpleshkov/unit-factory-ucode-half-marathon-c | 9ff260290382ea03b07e28a92c0f922ec85d31d0 | [
"MIT"
] | null | null | null | sprint01/t01/main.cpp | viacheslavpleshkov/unit-factory-ucode-half-marathon-c | 9ff260290382ea03b07e28a92c0f922ec85d31d0 | [
"MIT"
] | null | null | null | #include "src/moveAlong.h"
int main(int argc, char **argv) {
errors(argc);
std::vector<std::string> arguments;
for (int i = 1; i < argc; ++i)
arguments.push_back(argv[i]);
moveAlong(arguments);
return 0;
} | 21.363636 | 39 | 0.6 | [
"vector"
] |
e5ecf415749efd2712f87157367ae46df31d8a9f | 8,858 | cc | C++ | syncer/client/parsing_worker.cc | wahidHarb/rdp-1 | 73a0813d9a08f0aad34b56ba678167e6387b5e74 | [
"Apache-2.0"
] | 112 | 2018-12-05T07:45:42.000Z | 2022-01-24T11:28:11.000Z | syncer/client/parsing_worker.cc | wahidHarb/rdp-1 | 73a0813d9a08f0aad34b56ba678167e6387b5e74 | [
"Apache-2.0"
] | 2 | 2020-02-29T02:34:59.000Z | 2020-05-12T06:34:29.000Z | syncer/client/parsing_worker.cc | wahidHarb/rdp-1 | 73a0813d9a08f0aad34b56ba678167e6387b5e74 | [
"Apache-2.0"
] | 88 | 2018-12-16T07:35:10.000Z | 2022-03-09T17:41:16.000Z | //
//Copyright 2018 vip.com.
//
//Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
//the License. You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
//an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
//specific language governing permissions and limitations under the License.
//
#include <rdp-comm/signal_handler.h>
#include <rdp-comm/logger.h>
#include <boost/lexical_cast.hpp>
#include "syncer_filter.h"
#include "parsing_worker.h"
#include "log_event_parser.h"
#include "encoded_msg_map.h"
#include "syncer_app.h"
#include "split_package.h"
#include "memory_pool.h"
#include "rdp_syncer_metric.h"
#include "rebuild.h"
namespace syncer {
// Parsing thread cleanup handler
static void WorkerThreadCleanupHandler(void *args) {
CoordinatorInfo *p = (CoordinatorInfo *)args;
if (NULL != p) {
RDP_LOG_DBG << "Parsing thread #" << p->thd_no << " cancelled";
delete p;
p = NULL;
}
}
void CleanTrans(rdp::messages::Transaction &transaction) {
for (int i = 0; i < transaction.events_size(); i++) {
rdp::messages::Event *event = transaction.mutable_events(i);
if (IsDataEvent(event->event_type()) &&
event->rows_size() > 0) {
return;
}
if (event->has_ddl() && event->ddl() == rdp::messages::kDDLChanged) {
return;
}
}
transaction.clear_events();
return;
}
void CleanTransaction(Transaction *transaction, SeqTransCtx *seq_trans_ctx, bool is_truncated) {
assert(transaction != NULL);
assert(seq_trans_ctx != NULL);
if (is_truncated) {
RDP_LOG_WARN << " Transaction is truncated, binlog_file_name:"<< transaction->binlog_file_name()
<< ", postition:" << transaction->position()
<< ", next_binlog_file_name:" << transaction->next_binlog_file_name()
<< ", next_position:" << transaction->next_position();
ClearTransEventAlarm(transaction);
}
if (seq_trans_ctx->enable_split_msg) {
return;
}
if (seq_trans_ctx->enable_trans_clean) {
CleanTrans(*transaction);
}
return;
}
// Parsing thread loop
void *ParsingWorkerThread(void *args) {
CoordinatorInfo *ci = (CoordinatorInfo *)args;
assert(ci);
PthreadCall("pthread_detach", pthread_detach(pthread_self()));
pthread_cleanup_push(WorkerThreadCleanupHandler, ci);
char thd_name[16] = {0x0};
snprintf(thd_name, sizeof(thd_name), "parsing.thd%02d", ci->thd_no);
rdp_comm::signalhandler::AddThread(pthread_self(), thd_name);
TrxMsg *trx_msg = NULL;
EventMsg *em = NULL;
LogEventParser le_parser;
SeqTrans *seq_trans = NULL;
rdp::messages::Transaction *transaction = NULL;
bool enable_checksum = g_syncer_app->app_conf_->GetValue<string>("checksum.enable", "0").compare("1") == 0 ? true : false;
bool enable_compress = g_syncer_app->app_conf_->GetValue<string>("compress.enable", "0").compare("1") == 0 ? true : false;
size_t split_msg_bytes = g_syncer_app->app_conf_->GetValue<size_t>("kafka.producer.split_msg_bytes");
bool enable_split_msg = g_syncer_app->app_conf_->GetValue<uint32_t>("kafka.producer.enable_split_msg", 0) == 1 ? true : false;
bool enable_trans_clean = g_syncer_app->app_conf_->GetValue<uint32_t>("kafka.producer.enable_trans_clean", 0) == 1 ? true : false;
SeqTransCtx *seq_trans_ctx = new SeqTransCtx(split_msg_bytes,
enable_checksum,
enable_compress,
enable_split_msg,
enable_trans_clean,
2 * 1024 * 1024);
// Enter parse loop infinitely, for each binlog file
while (rdp_comm::signalhandler::IsRunning()) {
transaction = new rdp::messages::Transaction;
// Get an entry blockingly
trx_msg = ci->GetTask();
if (NULL == trx_msg) break;
timeval start, end;
gettimeofday(&start, NULL);
STAT_TIME_POINT(STAT_T6, trx_msg->seq_no, trx_msg->stat_point);
EventMsg *first_event = NULL, *last_event = NULL;
PreHeader *ph_tmp = NULL;
uint32_t event_num = 0;
string next_binlog_name;
uint64_t next_binlog_pos;
// Group commit id
int64_t last_committed = 0;
int64_t sequence_number = 0;
// Parser a transaction
RDP_LOG_DBG << "---------Thread #" << ci->thd_no
<< "New (" << (trx_msg->trx_opt == TRX_DDL ? "DDL" : "DML") << ") Transaction("
<< trx_msg->seq_no << ")";
transaction->set_seq(trx_msg->seq_no);
std::vector<EventMsg *>::iterator iter = trx_msg->events.begin();
for (; iter != trx_msg->events.end(); ++iter) {
em = *iter;
assert(em);
// Per log event
PreHeader *ph = (PreHeader *)em->msg;
assert(em->len > BINLOG_CHECKSUM_LEN);
rdp::messages::Event *event = transaction->add_events();
assert(event);
uint32_t event_len = em->len;
if (trx_msg->checksum != binary_log::BINLOG_CHECKSUM_ALG_UNDEF &&
(ph->event_type == binary_log::FORMAT_DESCRIPTION_EVENT ||
trx_msg->checksum != binary_log::BINLOG_CHECKSUM_ALG_OFF) &&
!IsEventTruncated(ph->event_type, event_len)) {
// TODO
event_len = event_len - BINLOG_CHECKSUM_LEN;
}
// if parse trx failt, exit thread, check all threads alive thread will
// catch this event and exit program
if (ERROR_STOP ==
le_parser.Parse(em->msg, event_len, em->binlog_fname,
trx_msg->trx_opt == TRX_DDL ? true : false, ph, event,
transaction->mutable_gtid(),
next_binlog_name, next_binlog_pos,
last_committed,sequence_number)) {
RDP_LOG_ERROR << "Parse Seq No: " << trx_msg->seq_no << ", Failt";
g_syncer_app->Alarm("Parse transaction Failt");
goto end;
}
}
first_event = trx_msg->events[0];
transaction->set_binlog_file_name(first_event->binlog_fname);
ph_tmp = (PreHeader *)first_event->msg;
assert(ph_tmp->log_pos > ph_tmp->event_size);
transaction->set_position(ph_tmp->log_pos - ph_tmp->event_size);
event_num = trx_msg->events.size();
assert(event_num > 0);
last_event = trx_msg->events[event_num - 1];
transaction->set_next_binlog_file_name(last_event->binlog_fname);
ph_tmp = (PreHeader *)last_event->msg;
transaction->set_next_position(ph_tmp->log_pos);
if (next_binlog_name.size()) {
transaction->set_next_binlog_file_name(next_binlog_name);
transaction->set_next_position(next_binlog_pos);
}
transaction->set_last_committed(last_committed);
transaction->set_sequence_number(sequence_number);
RDP_LOG_DBG << "---------Thread #" <<ci->thd_no
<< "End (" << (trx_msg->trx_opt == TRX_DDL ? "DDL" : "DML") << ") Transaction"
<< "(" << trx_msg->seq_no << ")";
STAT_TIME_POINT(STAT_T7, trx_msg->seq_no, trx_msg->stat_point);
CleanTransaction(transaction, seq_trans_ctx, trx_msg->is_truncated);
seq_trans = TransactionToSeqTrans(transaction, seq_trans_ctx, trx_msg->seq_no);
if (seq_trans == NULL) {
RDP_LOG_ERROR << "Transaction To Seq Trans Failt";
abort();
}
g_encode_msg_map.AddMsg(trx_msg->seq_no, seq_trans);
seq_trans = NULL;
STAT_TIME_POINT(STAT_T11, trx_msg->seq_no, trx_msg->stat_point);
le_parser.clear_tablemap();
delete transaction;
transaction = NULL;
g_syncer_metric->parser_event_eps_->AddValue(trx_msg->events.size());
g_syncer_metric->parser_trans_tps_->AddValue(1);
// Delete this entry
delete trx_msg;
trx_msg = NULL;
ci->TaskDone();
gettimeofday(&end, NULL);
g_syncer_metric->parser_trans_avg_proc_time_->PushValue(rdp_comm::TimevalToUs(end) - rdp_comm::TimevalToUs(start));
}
end:
if (NULL != transaction) {
delete transaction;
transaction = NULL;
}
if (NULL != trx_msg) {
delete trx_msg;
trx_msg = NULL;
}
if (NULL != seq_trans) {
delete seq_trans;
seq_trans = NULL;
}
if (NULL != seq_trans_ctx) {
delete seq_trans_ctx;
seq_trans_ctx = NULL;
}
ci->TaskDone();
// Quit parsing from signal thread
rdp_comm::signalhandler::Wait();
RDP_LOG_DBG << "Quit " << thd_name;
pthread_cleanup_pop(1);
return NULL;
}
// Spawn a new parsing thread
bool StartParsingWorker(CoordinatorInfo *ci) {
pthread_t tid;
PthreadCall("pthread_create", pthread_create(&tid, NULL, ParsingWorkerThread, ci));
return true;
}
void StopParsingWorker(void) {}
} // namespace syncer
| 32.094203 | 132 | 0.653985 | [
"vector"
] |
e5ef1610fe410a37b0eee2a1ee7127964531e3a5 | 5,171 | cpp | C++ | Engine/source/rendering/DrawingSystem.cpp | KnightTec/BaryonEngine | dd0ea1b1671c164471b1a5820394243abe621227 | [
"MIT"
] | null | null | null | Engine/source/rendering/DrawingSystem.cpp | KnightTec/BaryonEngine | dd0ea1b1671c164471b1a5820394243abe621227 | [
"MIT"
] | null | null | null | Engine/source/rendering/DrawingSystem.cpp | KnightTec/BaryonEngine | dd0ea1b1671c164471b1a5820394243abe621227 | [
"MIT"
] | null | null | null | #include "DrawingSystem.h"
#include "Shader.h"
#include "GpuData.h"
#include "DXErr.h"
#include "VirtualScreen.h"
#include "ConstantBuffer.h"
#include "DirectXMath.h"
using namespace Baryon;
using namespace DirectX;
using namespace Microsoft::WRL;
static ComPtr<ID3D11RasterizerState1> rasterState;
static ComPtr<ID3D11SamplerState> samplerState;
static ComPtr<ID3D11DepthStencilState> depthStencilState;
DrawingSystem::DrawingSystem(EntityManager* entityManager, std::vector<VirtualScreen>& virtualScreens)
: super(entityManager), virtualScreens(virtualScreens)
{
}
void DrawingSystem::initialize()
{
vs.compile();
ps.compile();
TAA.compile();
postVS.compile();
lightPS.compile();
postPS.compile();
// Create rasterizer state
D3D11_RASTERIZER_DESC1 rasterizerState;
rasterizerState.FillMode = D3D11_FILL_SOLID;
rasterizerState.CullMode = D3D11_CULL_BACK;
rasterizerState.FrontCounterClockwise = true;
rasterizerState.DepthBias = false;
rasterizerState.DepthBiasClamp = 0;
rasterizerState.SlopeScaledDepthBias = 0;
rasterizerState.DepthClipEnable = true;
rasterizerState.ScissorEnable = false;
rasterizerState.MultisampleEnable = false;
rasterizerState.AntialiasedLineEnable = false;
rasterizerState.ForcedSampleCount = 0;
HRF(getDevice()->CreateRasterizerState1(&rasterizerState, rasterState.GetAddressOf()));
getContext()->RSSetState(rasterState.Get());
D3D11_SAMPLER_DESC samplerDesc = {};
samplerDesc.AddressU = D3D11_TEXTURE_ADDRESS_CLAMP;
samplerDesc.AddressV = D3D11_TEXTURE_ADDRESS_CLAMP;
samplerDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;
samplerDesc.AddressW = D3D11_TEXTURE_ADDRESS_CLAMP;
HRF(getDevice()->CreateSamplerState(&samplerDesc, samplerState.GetAddressOf()));
getContext()->PSSetSamplers(0, 1, samplerState.GetAddressOf());
D3D11_DEPTH_STENCIL_DESC dsDesc = {};
dsDesc.DepthEnable = true;
dsDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL;
dsDesc.DepthFunc = D3D11_COMPARISON_GREATER;
dsDesc.StencilEnable = false;
dsDesc.StencilReadMask = D3D11_DEFAULT_STENCIL_READ_MASK;
dsDesc.StencilWriteMask = D3D11_DEFAULT_STENCIL_WRITE_MASK;
const D3D11_DEPTH_STENCILOP_DESC defaultStencilOp =
{
D3D11_STENCIL_OP_KEEP,
D3D11_STENCIL_OP_KEEP,
D3D11_STENCIL_OP_KEEP,
D3D11_COMPARISON_ALWAYS
};
dsDesc.FrontFace = defaultStencilOp;
dsDesc.BackFace = defaultStencilOp;
HRF(getDevice()->CreateDepthStencilState(&dsDesc, depthStencilState.GetAddressOf()));
getContext()->OMSetDepthStencilState(depthStencilState.Get(), 0);
/*
* TODO: Blend State
*/
}
void DrawingSystem::terminate()
{
}
void DrawingSystem::tick()
{
vs.apply();
ps.apply();
for (VirtualScreen& screen : virtualScreens)
{
screen.clear();
}
// render geometry pass
getContext()->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
super::tick();
postVS.apply();
getContext()->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP);
for (VirtualScreen& screen : virtualScreens)
{
CameraComponent* cam = screen.getActiveCamera();
if (cam == nullptr)
{
continue;
}
auto& bufferData = cBuffer(PER_CAMERA_DATA);
const Size2D& screenResolution = screen.getResolution();
bufferData->screenParams = {1.f / screenResolution.x, 1.f / screenResolution.y};
bufferData->viewProjection = cam->getViewProjectionXM();
bufferData->invViewProj = XMMatrixInverse(nullptr, cam->getViewProjectionXM());
bufferData->cameraPosition = cam->position;
bufferData->cameraLinearVelocity = cam->linearVelocity;
bufferData.uploadBuffer();
bufferData->prevFrameViewProjMat = cam->getViewProjectionXM();
// render light pass
lightPS.apply();
screen.setupIntermediateViewport();
screen.setupLightPass();
getContext()->Draw(3, 0);
// anti-aliasing
TAA.apply();
screen.setupAAPass();
getContext()->Draw(3, 0);
// render post processing
postPS.apply();
screen.setupFinalViewport();
screen.setupPostProcessPass();
getContext()->Draw(3, 0);
screen.present();
}
ID3D11ShaderResourceView* nulls[] = {nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr};
getContext()->PSSetShaderResources(0, 8, nulls);
}
void DrawingSystem::update(WorldMatrixComponent& wmc, MeshComponent& mesh)
{
if (mesh.mesh == nullptr)
{
return;
}
XMMATRIX worldMatrix = XMLoadFloat4x3(&wmc.worldMatrix);
uint32_t strides = sizeof(Vertex);
uint32_t offsets = 0;
ID3D11Buffer* vertexBuffer = mesh.mesh->getVertexBuffer();
getContext()->IASetVertexBuffers(0, 1, &vertexBuffer, &strides, &offsets);
getContext()->IASetIndexBuffer(mesh.mesh->getIndexBuffer(), DXGI_FORMAT_R32_UINT, 0);
for (VirtualScreen& screen : virtualScreens)
{
CameraComponent* cam = screen.getActiveCamera();
if (cam == nullptr)
{
continue;
}
screen.setupIntermediateViewport();
screen.setupGeometryPass();
// update constant buffer (matrices)
auto& buffer = cBuffer(PER_OBJECT_DATA);
buffer->worldViewProjMat = worldMatrix * cam->getViewProjectionXM() * screen.getTaaJitterMatrix();
buffer->worldNormalsMat = XMMatrixTranspose(XMMatrixInverse(nullptr, worldMatrix));
buffer.uploadBuffer();
getContext()->DrawIndexed(mesh.mesh->getIndexCount(), 0, 0);
}
}
| 28.888268 | 110 | 0.769097 | [
"mesh",
"geometry",
"render",
"vector"
] |
e5f1cb1b5dd42a823b2407d8f84c3614a56d6219 | 5,361 | hpp | C++ | include/chemfiles/selections/lexer.hpp | jjzhang166/chemfiles | 8b5ca75ef5af9cd4499aaf79a78e0cbc6e83429a | [
"BSD-3-Clause"
] | null | null | null | include/chemfiles/selections/lexer.hpp | jjzhang166/chemfiles | 8b5ca75ef5af9cd4499aaf79a78e0cbc6e83429a | [
"BSD-3-Clause"
] | null | null | null | include/chemfiles/selections/lexer.hpp | jjzhang166/chemfiles | 8b5ca75ef5af9cd4499aaf79a78e0cbc6e83429a | [
"BSD-3-Clause"
] | null | null | null | // Chemfiles, a modern library for chemistry file reading and writing
// Copyright (C) Guillaume Fraux and contributors -- BSD license
#ifndef CHEMFILES_SELECTION_LEXER_HPP
#define CHEMFILES_SELECTION_LEXER_HPP
#include <string>
#include <sstream>
#include <vector>
#include <cassert>
#include <chemfiles/exports.hpp>
namespace chemfiles {
namespace selections {
/// A token in the selection stream
///
/// Various tokens are alowed here:
///
/// - binary comparison operators (== != < <= > >=);
/// - boolean operators (and not or);
/// - numbers, the scientific notation is alowed;
/// - identifiers, obeing to the ([a-Z][a-Z_1-9]+) regular expression
class CHFL_EXPORT Token {
public:
/// Available token types
enum Type {
/// Left parenthesis
LPAREN,
/// Right parenthesis
RPAREN,
/// Comma
COMMA,
/// "==" token
EQ,
/// "!=" token
NEQ,
/// "<" token
LT,
/// "<=" token
LE,
/// ">" token
GT,
/// ">=" token
GE,
/// "not" token
NOT,
/// "and" token
AND,
/// "or" token
OR,
/// Generic identifier
IDENT,
/// Number
NUMBER,
/// "#(\d+)" token
VARIABLE,
};
/// Basic copy and move constructors
Token(const Token&) = default;
Token& operator=(const Token&) = default;
Token(Token&&) = default;
Token& operator=(Token&&) = default;
/// Create an identifier token with `data` name
static Token ident(const std::string& data) {
return Token(IDENT, data, 0.0, 0);
}
/// Create a number token with `data` value
static Token number(double data) {
std::stringstream sstream;
sstream << data;
return Token(NUMBER, sstream.str(), data, 0);
}
/// Create a variable token with `data` value
static Token variable(uint8_t variable) {
return Token(VARIABLE, "", 0.0, variable);
}
/// Create a token with type `ttype`.
/// \pre `ttype` can not be NUM or IDENT.
/// \post `type()` is `ttype`.
Token(Type ttype): Token(ttype, "", 0.0, 0) {
assert(
ttype != IDENT && ttype != NUMBER && ttype != VARIABLE &&
"Can only use this constructor for token without associated data"
);
}
/// Get the string which is at the origin of this token
std::string str() const;
/// Get the number value associated with this token.
/// \pre type() must be `NUMBER`.
double number() const {
assert(type_ == NUMBER && "Can only get number from NUM token");
return number_;
}
/// Get the identifier name associated with this token.
/// \pre type() must be `IDENT` or `NUMBER`.
const std::string& ident() const {
assert(
(type_ == IDENT || type_ == NUMBER) &&
"Can only get identifiers from IDENT or NUMBER token"
);
return ident_;
}
/// Get the variable associated with this token.
/// \pre type() must be `VARIABLE`.
unsigned variable() const {
assert(type_ == VARIABLE && "Can only get variable from VARIABLE token");
return variable_;
}
/// Check whether this token is a boolean operator,///i.e.* one of `and`,
/// `or` or `not`
bool is_boolean_op() const {
return (type() == AND || type() == OR || type() == NOT);
}
/// Check whether this token is a binary comparison operator,///i.e.* one
/// of `==`, `!=`, `<`, `<=`, `>` or `>=`.
bool is_binary_op() const {
return (type() == EQ || type() == NEQ ||
type() == LT || type() == LE ||
type() == GT || type() == GE);
}
/// Check whether this token is an operator, either a binary comparison operator or a
/// boolean operator
bool is_operator() const {
return is_binary_op() || is_boolean_op();
}
/// Check whether this token is an identifier
bool is_ident() const {
return (type_ == IDENT || type_ == NUMBER);
}
/// Check whether this token is a number
bool is_number() const {
return type_ == NUMBER;
}
/// Check whether this token is a variable
bool is_variable() const {
return type_ == VARIABLE;
}
/// Get the precedence of this token. Parentheses have a precedence of 0, operators
/// are classified by precedence.
/// \pre This token must be an operator (`is_operator()` is `true`) or a parenthese.
unsigned precedence() const;
/// Get the token type of this token
Type type() const {return type_;}
private:
Token(Type type, const std::string& ident, double number, uint8_t variable)
: type_(type), number_(number), ident_(ident), variable_(variable) {}
/// Token type
Type type_;
/// Value of the number if the token is a NUMBER
double number_;
/// Value of the identifier if the token is an IDENT
std::string ident_;
/// Value of the variable if the token is a VARIABLE
unsigned variable_;
};
/// Convert an `input` string to a stream of tokens
///
/// @throws SelectionError if the input string can not be tokenized
CHFL_EXPORT std::vector<Token> tokenize(const std::string& input);
}} // namespace chemfiles && namespace selections
#endif
| 29.295082 | 89 | 0.579929 | [
"vector"
] |
e5fda074d6fa61ba44173381089f9056a843d5b0 | 4,721 | hpp | C++ | include/tcframe/spec/io/IOFormat.hpp | tcgen/tcgen | d3b79585b40995ea8fc8091ecc6b6b19c2cb46ad | [
"MIT"
] | 76 | 2015-03-31T01:36:17.000Z | 2021-12-29T08:16:25.000Z | include/tcframe/spec/io/IOFormat.hpp | tcgen/tcgen | d3b79585b40995ea8fc8091ecc6b6b19c2cb46ad | [
"MIT"
] | 68 | 2016-11-28T18:58:26.000Z | 2018-08-10T13:33:35.000Z | include/tcframe/spec/io/IOFormat.hpp | tcgen/tcgen | d3b79585b40995ea8fc8091ecc6b6b19c2cb46ad | [
"MIT"
] | 17 | 2015-04-24T03:52:32.000Z | 2022-03-11T23:28:02.000Z | #pragma once
#include <functional>
#include <stdexcept>
#include <utility>
#include <vector>
#include "GridIOSegment.hpp"
#include "IOSegment.hpp"
#include "LineIOSegment.hpp"
#include "LinesIOSegment.hpp"
#include "RawLineIOSegment.hpp"
#include "RawLinesIOSegment.hpp"
using std::function;
using std::move;
using std::runtime_error;
using std::vector;
namespace tcframe {
struct IOFormat {
friend class IOFormatBuilder;
private:
IOSegments inputFormat_;
function<void()> beforeOutputFormat_;
vector<IOSegments> outputFormats_;
public:
const IOSegments& inputFormat() const {
return inputFormat_;
}
const function<void()>& beforeOutputFormat() const {
return beforeOutputFormat_;
}
const vector<IOSegments>& outputFormats() const {
return outputFormats_;
}
bool operator==(const IOFormat& o) const {
return equals(inputFormat_, o.inputFormat_) && equals(outputFormats_, o.outputFormats_);
}
private:
bool equals(const IOSegments& a, const IOSegments& b) const {
if (a.size() != b.size()) {
return false;
}
for (int i = 0; i < a.size(); i++) {
if (!a[i]->equals(b[i])) {
return false;
}
}
return true;
}
bool equals(const vector<IOSegments>& a, const vector<IOSegments>& b) const {
if (a.size() != b.size()) {
return false;
}
for (int i = 0; i < a.size(); i++) {
if (!equals(a[i], b[i])) {
return false;
}
}
return true;
}
};
class IOFormatBuilder {
private:
IOFormat subject_;
IOSegments* currentFormat_ = nullptr;
IOSegmentBuilder* lastBuilder_ = nullptr;
public:
void prepareForInputFormat() {
addLastSegment();
currentFormat_ = &subject_.inputFormat_;
}
void setBeforeOutputFormat(function<void()> beforeOutputFormat) {
subject_.beforeOutputFormat_ = beforeOutputFormat;
}
void newOutputFormat() {
addLastSegment();
subject_.outputFormats_.push_back(IOSegments());
currentFormat_ = &subject_.outputFormats_.back();
}
LineIOSegmentBuilder& newLineIOSegment() {
addLastSegment();
LineIOSegmentBuilder* builder = new LineIOSegmentBuilder();
lastBuilder_ = builder;
return *builder;
}
LinesIOSegmentBuilder& newLinesIOSegment() {
addLastSegment();
LinesIOSegmentBuilder* builder = new LinesIOSegmentBuilder();
lastBuilder_ = builder;
return *builder;
}
RawLineIOSegmentBuilder& newRawLineIOSegment() {
addLastSegment();
RawLineIOSegmentBuilder* builder = new RawLineIOSegmentBuilder();
lastBuilder_ = builder;
return *builder;
}
RawLinesIOSegmentBuilder& newRawLinesIOSegment() {
addLastSegment();
RawLinesIOSegmentBuilder* builder = new RawLinesIOSegmentBuilder();
lastBuilder_ = builder;
return *builder;
}
GridIOSegmentBuilder& newGridIOSegment() {
addLastSegment();
GridIOSegmentBuilder* builder = new GridIOSegmentBuilder();
lastBuilder_ = builder;
return *builder;
}
IOFormat build() {
addLastSegment();
if (!subject_.outputFormats_.empty() && subject_.outputFormats_.back().empty()) {
subject_.outputFormats_.pop_back();
}
return move(subject_);
}
private:
void addLastSegment() {
if (lastBuilder_ != nullptr) {
if (currentFormat_ != nullptr) {
checkLastSegment();
currentFormat_->push_back(lastBuilder_->build());
}
lastBuilder_ = nullptr;
}
}
void checkLastSegment() {
if (currentFormat_->empty()) {
return;
}
IOSegment* lastSegment = currentFormat_->back();
if (isLinesSegmentWithoutSize(lastSegment)) {
throw runtime_error("Lines segment without size can only be the last segment");
}
if (isRawLinesSegmentWithoutSize(lastSegment)) {
throw runtime_error("Raw lines segment without size can only be the last segment");
}
}
bool isLinesSegmentWithoutSize(IOSegment* segment) {
if (segment->type() != IOSegmentType::LINES) {
return false;
}
return ((LinesIOSegment*) segment)->size()() == NO_SIZE;
}
bool isRawLinesSegmentWithoutSize(IOSegment* segment) {
if (segment->type() != IOSegmentType::RAW_LINES) {
return false;
}
return ((RawLinesIOSegment*) segment)->size()() == NO_SIZE;
}
};
}
| 26.522472 | 96 | 0.611311 | [
"vector"
] |
f900f8391d1d785d557afa86805e522497625ea9 | 6,146 | cpp | C++ | tengine/renderer/game_renderingcontext.cpp | BSVino/Digitanks | 1bd1ed115493bce22001ae6684b70b8fcf135db0 | [
"BSD-4-Clause"
] | 5 | 2015-07-03T18:42:32.000Z | 2017-08-25T10:28:12.000Z | tengine/renderer/game_renderingcontext.cpp | BSVino/Digitanks | 1bd1ed115493bce22001ae6684b70b8fcf135db0 | [
"BSD-4-Clause"
] | null | null | null | tengine/renderer/game_renderingcontext.cpp | BSVino/Digitanks | 1bd1ed115493bce22001ae6684b70b8fcf135db0 | [
"BSD-4-Clause"
] | null | null | null | #include "game_renderingcontext.h"
#include <maths.h>
#include <simplex.h>
#include <models/models.h>
#include <renderer/shaders.h>
#include <tinker/application.h>
#include <tinker/cvar.h>
#include <tinker/profiler.h>
#include <game/gameserver.h>
#include <textures/texturelibrary.h>
#include <renderer/renderer.h>
#include <toys/toy.h>
#include <textures/materiallibrary.h>
#include <game/entities/game.h>
#include <game/entities/character.h>
#ifndef TINKER_NO_TOOLS
#include <tools/workbench.h>
#endif
#include "game_renderer.h"
CGameRenderingContext::CGameRenderingContext(CGameRenderer* pRenderer, bool bInherit)
: CRenderingContext(pRenderer, bInherit)
{
m_pRenderer = pRenderer;
}
void CGameRenderingContext::RenderModel(size_t iModel, const CBaseEntity* pEntity)
{
CModel* pModel = CModelLibrary::GetModel(iModel);
if (!pModel)
return;
bool bBatchThis = true;
if (!m_pRenderer->IsBatching())
bBatchThis = false;
else if (m_pRenderer && GetContext().m_pFrameBuffer != m_pRenderer->GetSceneBuffer())
bBatchThis = false;
else if (!pEntity)
bBatchThis = false;
else if (!pEntity->ShouldBatch())
bBatchThis = false;
else if (GetContext().m_eBlend != BLEND_NONE)
bBatchThis = false;
if (bBatchThis)
{
m_pRenderer->AddToBatch(pModel, pEntity, GetContext().m_mTransformations, m_clrRender, GetContext().m_bWinding);
}
else
{
m_pRenderer->m_pRendering = pEntity;
CRenderContext& oContext = GetContext();
for (size_t m = 0; m < pModel->m_aiVertexBuffers.size(); m++)
{
if (!pModel->m_aiVertexBufferSizes[m])
continue;
CMaterialHandle& hMaterial = pModel->m_ahMaterials[m];
if (!hMaterial)
continue;
UseMaterial(hMaterial);
if ((!m_pRenderer->IsRenderingTransparent()) ^ (oContext.m_eBlend == BLEND_NONE))
continue;
if (pEntity)
{
if (!pEntity->ModifyShader(this))
continue;
}
if (!m_pRenderer->ModifyShader(pEntity, this))
continue;
RenderModel(pModel, m);
}
m_pRenderer->m_pRendering = nullptr;
}
if (pModel->m_pToy && pModel->m_pToy->GetNumSceneAreas())
{
size_t iSceneArea = m_pRenderer->GetSceneAreaPosition(pModel);
auto pLocalPlayer = Game()?Game()->GetLocalPlayer():nullptr;
CCharacter* pCharacter = pLocalPlayer?pLocalPlayer->GetCharacter():nullptr;
bool bNoClip = pCharacter?pCharacter->GetNoClip():false;
bool bWorkbenchActive = false;
#ifndef TINKER_NO_TOOLS
bWorkbenchActive = CWorkbench::IsActive();
#endif
if (bWorkbenchActive || bNoClip || iSceneArea >= pModel->m_pToy->GetNumSceneAreas())
{
for (size_t i = 0; i < pModel->m_pToy->GetNumSceneAreas(); i++)
{
AABB aabbBounds = pModel->m_pToy->GetSceneAreaAABB(i);
if (!m_pRenderer->IsSphereInFrustum(aabbBounds.Center(), aabbBounds.Size().Length()/2))
continue;
RenderModel(CModelLibrary::FindModel(pModel->m_pToy->GetSceneAreaFileName(i)), pEntity);
}
}
else
{
for (size_t i = 0; i < pModel->m_pToy->GetSceneAreaNumVisible(iSceneArea); i++)
{
size_t iSceneAreaToRender = pModel->m_pToy->GetSceneAreasVisible(iSceneArea, i);
AABB aabbBounds = pModel->m_pToy->GetSceneAreaAABB(iSceneAreaToRender);
if (!m_pRenderer->IsSphereInFrustum(aabbBounds.Center(), aabbBounds.Size().Length()/2))
continue;
RenderModel(CModelLibrary::FindModel(pModel->m_pToy->GetSceneAreaFileName(iSceneAreaToRender)), pEntity);
}
}
}
}
#define BUFFER_OFFSET(i) (size_t)((char *)NULL + (i))
void CGameRenderingContext::RenderModel(CModel* pModel, size_t iMaterial)
{
SetUniform("vecColor", m_clrRender);
SetUniform("bNormalsAvailable", pModel->m_pToy && !!(pModel->m_pToy->GetVertexNormalOffsetInBytes(iMaterial) > 0));
TAssert(m_pShader);
if (!pModel || !m_pShader)
return;
BeginRenderVertexArray(pModel->m_aiVertexBuffers[iMaterial]);
if (pModel->m_pToy)
{
SetPositionBuffer((size_t)0u, pModel->m_pToy->GetVertexSizeInBytes(iMaterial));
if (pModel->m_pToy->GetVertexUVOffsetInBytes(iMaterial) > 0)
SetTexCoordBuffer(BUFFER_OFFSET(pModel->m_pToy->GetVertexUVOffsetInBytes(iMaterial)), pModel->m_pToy->GetVertexSizeInBytes(iMaterial));
if (pModel->m_pToy->GetVertexNormalOffsetInBytes(iMaterial) > 0)
SetNormalsBuffer(BUFFER_OFFSET(pModel->m_pToy->GetVertexNormalOffsetInBytes(iMaterial)), pModel->m_pToy->GetVertexSizeInBytes(iMaterial));
if (pModel->m_pToy->GetVertexTangentOffsetInBytes(iMaterial) > 0)
SetTangentsBuffer(BUFFER_OFFSET(pModel->m_pToy->GetVertexTangentOffsetInBytes(iMaterial)), pModel->m_pToy->GetVertexSizeInBytes(iMaterial));
if (pModel->m_pToy->GetVertexBitangentOffsetInBytes(iMaterial) > 0)
SetBitangentsBuffer(BUFFER_OFFSET(pModel->m_pToy->GetVertexBitangentOffsetInBytes(iMaterial)), pModel->m_pToy->GetVertexSizeInBytes(iMaterial));
}
else
{
// If there's no toy then we are using fixed size source models.
SetPositionBuffer((size_t)0u, 4*FIXED_FLOATS_PER_VERTEX);
SetTexCoordBuffer(BUFFER_OFFSET(4*FIXED_UV_OFFSET), 4*FIXED_FLOATS_PER_VERTEX);
}
EndRenderVertexArray(pModel->m_aiVertexBufferSizes[iMaterial]);
}
void CGameRenderingContext::RenderMaterialModel(const CMaterialHandle& hMaterial, const class CBaseEntity* pEntity)
{
TAssert(hMaterial.IsValid());
if (!hMaterial.IsValid())
return;
if (!hMaterial->m_ahTextures.size())
return;
CTextureHandle hBaseTexture = hMaterial->m_ahTextures[0];
if (!hBaseTexture)
return;
Vector vecLeft = Vector(0, 0.5f, 0) * ((float)hBaseTexture->m_iWidth/hMaterial->m_iTexelsPerMeter);
Vector vecUp = Vector(0, 0, 0.5f) * ((float)hBaseTexture->m_iHeight/hMaterial->m_iTexelsPerMeter);
UseMaterial(hMaterial);
m_pRenderer->ModifyShader(pEntity, this);
SetUniform("vecColor", m_clrRender);
BeginRenderTriFan();
TexCoord(0.0f, 1.0f);
Vertex(-vecLeft + vecUp);
TexCoord(0.0f, 0.0f);
Vertex(-vecLeft - vecUp);
TexCoord(1.0f, 0.0f);
Vertex(vecLeft - vecUp);
TexCoord(1.0f, 1.0f);
Vertex(vecLeft + vecUp);
EndRender();
}
void CGameRenderingContext::RenderBillboard(const tstring& sMaterial, float flRadius)
{
Vector vecLeft, vecUp;
m_pRenderer->GetCameraVectors(NULL, &vecLeft, &vecUp);
BaseClass::RenderBillboard(sMaterial, flRadius, vecLeft, vecUp);
}
| 29.980488 | 147 | 0.741946 | [
"vector"
] |
f909e1e2dba4867b5ed395e61755685ee938d9ed | 1,263 | cpp | C++ | src/shared/Sphere.cpp | RainerBlessing/TheRayTracerChallenge-C- | 22c990201507f46d5bb1604bc1f6ee88e59cef95 | [
"MIT"
] | null | null | null | src/shared/Sphere.cpp | RainerBlessing/TheRayTracerChallenge-C- | 22c990201507f46d5bb1604bc1f6ee88e59cef95 | [
"MIT"
] | null | null | null | src/shared/Sphere.cpp | RainerBlessing/TheRayTracerChallenge-C- | 22c990201507f46d5bb1604bc1f6ee88e59cef95 | [
"MIT"
] | null | null | null | //
// Created by rainer on 27.12.19.
//
#include <vector>
#include "Sphere.h"
#include "Ray.h"
std::vector<double> Sphere::intersects(Ray ray) {
std::vector<double> intersections;
auto ray2 = ray.transform(this->transform().inverse());
auto sphere_to_ray = ray2.origin - Point(0, 0, 0);
auto a = ray2.direction.dot(ray2.direction);
auto b = 2 * ray2.direction.dot(sphere_to_ray);
auto c = sphere_to_ray.dot(sphere_to_ray) - 1;
auto discriminant = b * b - 4 * a * c;
if (discriminant >= 0) {
double d = 2 * a;
double root_discriminant = sqrt(discriminant);
intersections.push_back((-b - root_discriminant) / d);
intersections.push_back((-b + root_discriminant) / d);
}
return intersections;
}
Matrix Sphere::transform() {
return translation;
}
void Sphere::setTransform(Matrix m) {
this->translation = m;
}
Vector Sphere::normalAt(Point worldPoint) {
auto sphere_inverse = transform().inverse();
auto object_point = sphere_inverse.multiply(worldPoint);
auto object_normal = Vector(object_point - Point(0, 0, 0));
auto world_normal = sphere_inverse.transpose().multiply(object_normal);
world_normal.w = 0;
return Vector(world_normal).normalize();
}
| 25.77551 | 75 | 0.665083 | [
"vector",
"transform"
] |
f91115e2c423c18941da7626f2d189253a5207c6 | 2,192 | cpp | C++ | 008_String_to_Integer/String_to_Integer.cpp | Rookie39/Algorithms_Leetcode | 433d1360a91774df21b283e8d5d1a4a6c2a8c63d | [
"Apache-2.0"
] | null | null | null | 008_String_to_Integer/String_to_Integer.cpp | Rookie39/Algorithms_Leetcode | 433d1360a91774df21b283e8d5d1a4a6c2a8c63d | [
"Apache-2.0"
] | null | null | null | 008_String_to_Integer/String_to_Integer.cpp | Rookie39/Algorithms_Leetcode | 433d1360a91774df21b283e8d5d1a4a6c2a8c63d | [
"Apache-2.0"
] | null | null | null | /*
*Author: Rookie118
*Title: String to Integer
*Completion time: 2018-03-12
*/
//The first version
//Time complexity: O(n^2)
//Space complexity: O(1)
class Solution {
public:
int myAtoi(string str) {
bool flag_neg = false, flag_num = false; //负数标记,数字标记
vector<int> nums;
int result = 0, count = 0, temp, record, division = 1;
if(str.size() == 0)
return 0;
for(int i = 0; i < str.size(); ++i)
{
if((str[i] > '9' || str[i] < '0') && str[i] != ' ' && str[i] != '-' && str[i] != '+') //第一个非空字符不是数字也不是+-号,则返回0
return 0;
else if(str[i] == '-' && (str[i+1] > '9' || str[i+1] < '0')) //第一个非空字符为-号,且下一个字符不为数字,则返回0
return 0;
else if(str[i] == '+' && (str[i+1] > '9' || str[i+1] < '0')) //第一个非空字符为+号,且下一个字符不为数字,则返回0
return 0;
if(str[i] >= '0' && str[i] <= '9')
{
nums.push_back(str[i] - '0');
flag_num = true; //数字标记为真
}
if(str[i-1] == '-' && flag_num) //判断是否为负数
flag_neg = true;
if((str[i+1] > '9' || str[i+1] < '0') && flag_num) //判断数字序列是否结束
break;
}
for(int j = 0; j < nums.size(); ++j)
{
count = nums.size() - j - 1; //计算位数
division = 1; //被除数重置
if(flag_neg)
temp = record = -nums[j];
else
temp = record = nums[j];
while(count)
{
temp *= 10;
division *= 10;
if(flag_neg && temp % 10 != 0) //检测乘积过程中负数溢出
{
return INT_MIN;
}
else if(temp % 10 != 0) //检测乘积过程中正数溢出
{
return INT_MAX;
}
--count;
}
result += temp;
if(result / division % 10 != record) //检测最终求和溢出
{
if(flag_neg)
return INT_MIN;
else
return INT_MAX;
}
}
return result;
}
};
| 30.027397 | 123 | 0.380474 | [
"vector"
] |
f91722399f7264d798eb19f705937d07b262b634 | 5,150 | cpp | C++ | src/gui/graphsettings.cpp | evoplex/evoplex | c6e78af5fb0d2fc5a5ce7b02e5e4ec61de8934b6 | [
"Apache-2.0"
] | 101 | 2018-06-21T04:29:18.000Z | 2022-03-09T13:04:15.000Z | src/gui/graphsettings.cpp | ElsevierSoftwareX/SOFTX_2018_211 | cbfac5af0ad76b7c88a7ea296d94785692da3048 | [
"Apache-2.0"
] | 30 | 2018-06-26T15:12:03.000Z | 2019-10-10T04:02:13.000Z | src/gui/graphsettings.cpp | ElsevierSoftwareX/SOFTX_2018_211 | cbfac5af0ad76b7c88a7ea296d94785692da3048 | [
"Apache-2.0"
] | 23 | 2018-06-23T16:10:24.000Z | 2021-11-03T15:12:51.000Z | /**
* This file is part of Evoplex.
*
* Evoplex is a multi-agent system for networks.
* Copyright (C) 2018 - Marcos Cardinot <marcos@cardinot.net>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <QSettings>
#include <QSlider>
#include "graphsettings.h"
#include "ui_graphsettings.h"
#include "maingui.h"
#include "graphview.h"
namespace evoplex {
GraphSettings::GraphSettings(ColorMapMgr* cMgr, ExperimentPtr exp, GraphView* parent)
: QDialog(parent, MainGUI::kDefaultDlgFlags),
m_ui(new Ui_GraphSettings),
m_parent(parent),
m_cMgr(cMgr),
m_exp(exp)
{
m_ui->setupUi(this);
connect(m_exp.get(), SIGNAL(restarted()), SLOT(init()));
connect(m_ui->nodesColor, SIGNAL(cmapUpdated(ColorMap*)),
parent, SLOT(setNodeCMap(ColorMap*)));
connect(m_ui->edgesColor, SIGNAL(cmapUpdated(ColorMap*)),
parent, SLOT(setEdgeCMap(ColorMap*)));
connect(m_ui->nodeScale, SIGNAL(valueChanged(int)), SLOT(slotNodeScale(int)));
connect(m_ui->edgeScale, SIGNAL(valueChanged(int)), SLOT(slotEdgeScale(int)));
connect(m_ui->edgeWidth, SIGNAL(valueChanged(int)), SLOT(slotEdgeWidth(int)));
connect(m_ui->bOk, SIGNAL(pressed()), SLOT(close()));
connect(m_ui->bRestore, SIGNAL(pressed()), SLOT(restoreSettings()));
connect(m_ui->bSaveAsDefault, SIGNAL(pressed()), SLOT(saveAsDefault()));
}
GraphSettings::~GraphSettings()
{
delete m_ui;
}
void GraphSettings::init()
{
Q_ASSERT_X(m_exp->modelPlugin(), "GraphSettings",
"tried to init the graph settings for a null model!");
QSettings userPrefs;
m_ui->nodeScale->setValue(userPrefs.value("graphSettings/nodeScale", 10).toInt());
m_ui->edgeScale->setValue(userPrefs.value("graphSettings/edgeScale", 25).toInt());
m_ui->edgeWidth->setValue(userPrefs.value("graphSettings/edgeWidth", 1).toInt());
auto cmap = m_cMgr->defaultCMapKey();
CMapKey n(userPrefs.value("graphSettings/nodeCMap", cmap.first).toString(),
userPrefs.value("graphSettings/nodeCMapSize", cmap.second).toInt());
m_ui->nodesColor->init(m_cMgr, n, m_exp->modelPlugin()->nodeAttrsScope());
m_ui->nodesColor->setVisible(!m_exp->modelPlugin()->nodeAttrsScope().empty());
CMapKey e(userPrefs.value("graphSettings/edgeCMap", cmap.first).toString(),
userPrefs.value("graphSettings/edgeCMapSize", cmap.second).toInt());
m_ui->edgesColor->init(m_cMgr, e, m_exp->modelPlugin()->edgeAttrsScope());
m_ui->edgesColor->setVisible(!m_exp->modelPlugin()->edgeAttrsScope().empty());
}
void GraphSettings::restoreSettings()
{
QSettings userPrefs;
userPrefs.setValue("graphSettings/nodeScale", 10);
userPrefs.setValue("graphSettings/edgeScale", 25);
userPrefs.setValue("graphSettings/edgeWidth", 1);
auto cmap = m_cMgr->defaultCMapKey();
userPrefs.setValue("graphSettings/nodeCMap", cmap.first);
userPrefs.setValue("graphSettings/nodeCMapSize", cmap.second);
userPrefs.setValue("graphSettings/edgeCMap", cmap.first);
userPrefs.setValue("graphSettings/edgeCMapSize", cmap.second);
init();
}
void GraphSettings::saveAsDefault()
{
QSettings userPrefs;
userPrefs.setValue("graphSettings/nodeScale", nodeScale());
userPrefs.setValue("graphSettings/edgeScale", edgeScale());
userPrefs.setValue("graphSettings/edgeWidth", edgeWidth());
userPrefs.setValue("graphSettings/nodeCMap", nodeColorSelector()->cmapName());
userPrefs.setValue("graphSettings/nodeCMapSize", nodeColorSelector()->cmapSize());
userPrefs.setValue("graphSettings/edgeCMap", edgeColorSelector()->cmapName());
userPrefs.setValue("graphSettings/edgeCMapSize", edgeColorSelector()->cmapSize());
}
void GraphSettings::slotNodeScale(int v)
{
m_parent->setNodeScale(v);
m_ui->nodeScale->setToolTip(QString::number(v));
}
void GraphSettings::slotEdgeScale(int v)
{
m_parent->setEdgeScale(v);
m_ui->edgeScale->setToolTip(QString::number(v));
}
void GraphSettings::slotEdgeWidth(int v)
{
m_parent->setEdgeWidth(v);
m_ui->edgeWidth->setToolTip(QString::number(v));
}
int GraphSettings::nodeScale() const
{
return m_ui->nodeScale->value();
}
int GraphSettings::edgeScale() const
{
return m_ui->edgeScale->value();
}
int GraphSettings::edgeWidth() const
{
return m_ui->edgeWidth->value();
}
AttrColorSelector* GraphSettings::nodeColorSelector() const
{
return m_ui->nodesColor;
}
AttrColorSelector* GraphSettings::edgeColorSelector() const
{
return m_ui->edgesColor;
}
} // evoplex
| 33.881579 | 86 | 0.713981 | [
"model"
] |
f918a0fc00438e22948f9faa839a2e82ab90f73c | 17,294 | cpp | C++ | src/application.cpp | danilopeixoto/thesaurus | d4b5f9b24726fb1f26b3fd121c5845a818c63c42 | [
"BSD-3-Clause"
] | null | null | null | src/application.cpp | danilopeixoto/thesaurus | d4b5f9b24726fb1f26b3fd121c5845a818c63c42 | [
"BSD-3-Clause"
] | null | null | null | src/application.cpp | danilopeixoto/thesaurus | d4b5f9b24726fb1f26b3fd121c5845a818c63c42 | [
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2017, Danilo Peixoto. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of the copyright holder nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "application.h"
#include <iostream>
#include <cstdlib>
#include <cmath>
#include <fstream>
THESAURUS_NAMESPACE_BEGIN
Application::Preferences::Preferences(const Translator::Language & language,
const Theme & theme) : language(language), theme(theme) {}
Application::Preferences::~Preferences() {}
Application::Application() {
preferenceFile = fopen("preferences", "rb+");
if (preferenceFile != THESAURUS_NULL) {
fread(&preferences, sizeof(Preferences), 1, preferenceFile);
}
else {
preferenceFile = fopen("preferences", "wb+");
if (preferenceFile != THESAURUS_NULL)
fwrite(&preferences, sizeof(Preferences), 1, preferenceFile);
}
fclose(preferenceFile);
translator.setLanguage(preferences.language);
setTheme(preferences.theme);
clear();
}
Application::~Application() {
if (preferenceFile != THESAURUS_NULL)
fclose(preferenceFile);
}
void Application::execute() {
clear();
createTitle();
separator();
Vector<String> menu;
menu.push(translator.ADD);
menu.push(translator.REMOVE);
menu.push(translator.EDIT);
menu.push(translator.SEARCH);
menu.push(translator.LIST);
menu.push(translator.EXPORT);
menu.push(translator.PREFERENCES);
menu.push(translator.ABOUT);
menu.push(translator.EXIT);
createMenu(menu);
separator();
requestOption();
switch (option) {
case 1:
addAction();
break;
case 2:
removeAction();
break;
case 3:
editAction();
break;
case 4:
searchAction();
break;
case 5:
listAction();
break;
case 6:
exportAction();
break;
case 7:
preferencesAction();
break;
case 8:
aboutAction();
break;
case 9:
exitAction();
break;
default:
execute();
}
}
void Application::setTheme(const Theme & theme) {
switch (theme) {
case Theme::Dark:
system("color 0F");
break;
default:
system("color F0");
}
}
void Application::requestText(String & str) {
char c = (char)std::getchar();
while (c != '\n') {
str.push(c);
c = (char)std::getchar();
}
}
void Application::requestOption() {
String optionString;
requestText(optionString);
if (optionString.getSize() > THESAURUS_MAX_OPTION_LENGTH) {
char temp[THESAURUS_MAX_OPTION_LENGTH + 1];
optionString.getString(temp, THESAURUS_MAX_OPTION_LENGTH);
optionString = temp;
}
option = 0;
if (!isUInt(optionString))
return;
String::Iterator it = optionString.getBegin();
size_t count = optionString.getSize();
while (count != 0) {
option += (size_t)std::pow(10, count - 1) * ((size_t)(*it++) - 48);
count--;
}
}
void Application::createTitle() {
print("* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *");
print("* THESAURUS *");
print("* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *");
}
void Application::createMenu(const Vector<String> & menu) {
Vector<String>::ConstIterator it = menu.getBegin();
for (size_t i = 0; i < menu.getSize(); i++)
std::cout << i + 1 << ". " << *it++ << std::endl;
}
void Application::print(const String & str) {
std::cout << str << std::endl;
}
void Application::separator() {
std::cout << std::endl;
}
void Application::clear() {
system("cls");
}
bool Application::isUInt(const String & str) const {
String::ConstIterator it = str.getBegin();
size_t c;
while (it != str.getEnd()) {
c = (size_t)*it++;
if (c < 48 || c > 57)
return false;
}
return !str.isEmpty();
}
void Application::addAction() {
clear();
createTitle();
separator();
print(translator.ADD);
separator();
Word word;
print(translator.WORD);
requestText(word.data);
separator();
print(translator.TRANSLATION);
requestText(word.translation);
separator();
Vector<String> menu;
menu.push(translator.ADD);
menu.push(translator.CANCEL);
menu.push(translator.EXIT);
createMenu(menu);
separator();
requestOption();
separator();
switch (option) {
case 1:
dictionary.insertAscending(word);
execute();
break;
case 2:
execute();
break;
case 3:
exitAction();
break;
default:
addAction();
}
}
void Application::removeAction() {
clear();
createTitle();
separator();
print(translator.REMOVE);
separator();
String str;
print(translator.WORD);
requestText(str);
separator();
Vector<Dictionary::Iterator> temp;
Dictionary::Iterator it = dictionary.getBegin();
Dictionary::Iterator prevIt;
size_t i = 1;
while (it != dictionary.getEnd()) {
if ((*it).data == str) {
std::cout << i++ << ". " << *it << std::endl;
temp.push(prevIt);
}
prevIt = it;
it++;
}
Vector<String> menu;
if (temp.isEmpty()) {
print(translator.SEARCH_ERROR);
separator();
menu.push(translator.OK);
menu.push(translator.REMOVE);
menu.push(translator.EXIT);
createMenu(menu);
separator();
requestOption();
separator();
switch (option) {
case 1:
execute();
break;
case 2:
removeAction();
break;
case 3:
exitAction();
break;
default:
removeAction();
}
}
else {
separator();
size_t wordOption;
do {
print(translator.REMOVE_WORD);
requestOption();
separator();
wordOption = option;
} while (wordOption < 1 || wordOption > temp.getSize());
menu.push(translator.REMOVE);
menu.push(translator.CANCEL);
menu.push(translator.EXIT);
createMenu(menu);
separator();
requestOption();
separator();
Vector<Dictionary::Iterator>::Iterator tempIt;
switch (option) {
case 1:
tempIt = temp.getBegin();
i = 1;
while (i < wordOption) {
tempIt++;
i++;
}
dictionary.removeAfter((*tempIt).pointer);
execute();
break;
case 2:
execute();
break;
case 3:
exitAction();
break;
default:
removeAction();
}
}
}
void Application::editAction() {
clear();
createTitle();
separator();
print(translator.EDIT);
separator();
String str;
print(translator.WORD);
requestText(str);
separator();
Vector<Dictionary::Iterator> temp;
Dictionary::Iterator it = dictionary.getBegin();
Dictionary::Iterator prevIt;
size_t i = 1;
while (it != dictionary.getEnd()) {
if ((*it).data == str) {
std::cout << i++ << ". " << *it << std::endl;
temp.push(prevIt);
}
prevIt = it;
it++;
}
Vector<String> menu;
if (temp.isEmpty()) {
print(translator.SEARCH_ERROR);
separator();
menu.push(translator.OK);
menu.push(translator.EDIT);
menu.push(translator.EXIT);
createMenu(menu);
separator();
requestOption();
separator();
switch (option) {
case 1:
execute();
break;
case 2:
editAction();
break;
case 3:
exitAction();
break;
default:
editAction();
}
}
else {
separator();
size_t wordOption;
do {
print(translator.EDIT_WORD);
requestOption();
separator();
wordOption = option;
}
while (wordOption < 1 || wordOption > temp.getSize());
Word word;
print(translator.WORD);
requestText(word.data);
separator();
print(translator.TRANSLATION);
requestText(word.translation);
separator();
menu.push(translator.EDIT);
menu.push(translator.CANCEL);
menu.push(translator.EXIT);
createMenu(menu);
separator();
requestOption();
separator();
Vector<Dictionary::Iterator>::Iterator tempIt;
switch (option) {
case 1:
tempIt = temp.getBegin();
i = 1;
while (i < wordOption) {
tempIt++;
i++;
}
dictionary.removeAfter((*tempIt).pointer);
dictionary.insertAscending(word);
execute();
break;
case 2:
execute();
break;
case 3:
exitAction();
break;
default:
editAction();
}
}
}
void Application::searchAction() {
clear();
createTitle();
separator();
print(translator.SEARCH);
separator();
String word;
print(translator.WORD);
requestText(word);
separator();
Dictionary::Iterator it = dictionary.getBegin();
size_t i = 1;
while (it != dictionary.getEnd()) {
if ((*it).data == word)
std::cout << i++ << ". " << *it << std::endl;
it++;
}
if (i == 1)
print(translator.SEARCH_ERROR);
separator();
Vector<String> menu;
menu.push(translator.OK);
menu.push(translator.SEARCH);
menu.push(translator.EXIT);
createMenu(menu);
separator();
requestOption();
separator();
switch (option) {
case 1:
execute();
break;
case 2:
searchAction();
break;
case 3:
exitAction();
break;
default:
searchAction();
}
}
void Application::listAction() {
clear();
createTitle();
separator();
print(translator.LIST);
separator();
std::cout << translator.WORD_COUNT << " " << dictionary.getSize() << std::endl;
separator();
Dictionary::Iterator it = dictionary.getBegin();
for (size_t i = 1; i < dictionary.getSize() + 1; i++)
std::cout << i << ". " << *it++ << std::endl;
if (!dictionary.isEmpty())
separator();
Vector<String> menu;
menu.push(translator.OK);
menu.push(translator.EXIT);
createMenu(menu);
separator();
requestOption();
separator();
switch (option) {
case 1:
execute();
break;
case 2:
exitAction();
break;
default:
listAction();
}
}
void Application::exportAction() {
clear();
createTitle();
separator();
print(translator.EXPORT);
separator();
print(translator.EXPORT_MESSAGE);
String filename;
std::fstream file;
requestText(filename);
separator();
Vector<String> menu;
menu.push(translator.EXPORT);
menu.push(translator.CANCEL);
menu.push(translator.EXIT);
createMenu(menu);
separator();
requestOption();
separator();
switch (option) {
case 1:
char temp[THESAURUS_MAX_PATH_LENGTH + 1];
filename.getString(temp, THESAURUS_MAX_PATH_LENGTH);
file.open(temp, std::fstream::out);
if (file.is_open()) {
Dictionary::Iterator itd = dictionary.getBegin();
while (itd != dictionary.getEnd())
file << *itd++ << std::endl;
file.close();
execute();
}
else
exportAction();
break;
case 2:
execute();
break;
case 3:
exitAction();
break;
default:
exportAction();
}
}
void Application::preferencesAction() {
clear();
createTitle();
separator();
print(translator.PREFERENCES);
separator();
print(translator.DEFAULT_LANGUAGE);
separator();
Vector<String> menu;
menu.push(translator.ENGLISH);
menu.push(translator.PORTUGUESE);
menu.push(translator.DEFAULT);
createMenu(menu);
separator();
requestOption();
separator();
if (option < 1 || option > menu.getSize())
preferencesAction();
preferences.language = (Translator::Language)(option - 1);
print(translator.DEFAULT_THEME);
separator();
menu.clear();
menu.push(translator.LIGHT);
menu.push(translator.DARK);
menu.push(translator.DEFAULT);
createMenu(menu);
separator();
requestOption();
separator();
if (option < 1 || option > menu.getSize())
preferencesAction();
preferences.theme = (Theme)(option - 1);
menu.clear();
menu.push(translator.SAVE);
menu.push(translator.CANCEL);
menu.push(translator.EXIT);
createMenu(menu);
separator();
requestOption();
switch (option) {
case 1:
preferenceFile = fopen("preferences", "wb+");
if (preferenceFile != THESAURUS_NULL)
fwrite(&preferences, sizeof(Preferences), 1, preferenceFile);
fclose(preferenceFile);
translator.setLanguage(preferences.language);
setTheme(preferences.theme);
execute();
break;
case 2:
execute();
break;
case 3:
exitAction();
break;
default:
preferencesAction();
}
}
void Application::aboutAction() {
clear();
createTitle();
separator();
print(translator.ABOUT);
separator();
print(translator.ABOUT_THESAURUS);
separator();
print(translator.COPYRIGHT);
print(translator.LICENSE);
separator();
Vector<String> menu;
menu.push(translator.OK);
menu.push(translator.EXIT);
createMenu(menu);
separator();
requestOption();
separator();
switch (option) {
case 1:
execute();
break;
case 2:
exitAction();
break;
default:
aboutAction();
}
}
void Application::exitAction() {
clear();
createTitle();
separator();
print(translator.EXIT);
separator();
print(translator.EXIT_MESSAGE);
separator();
Vector<String> menu;
menu.push(translator.YES);
menu.push(translator.NO);
createMenu(menu);
separator();
requestOption();
separator();
switch (option) {
case 1:
exit(0);
break;
case 2:
execute();
break;
default:
exitAction();
}
}
THESAURUS_NAMESPACE_END | 21.6175 | 94 | 0.527408 | [
"vector"
] |
23526687a3e21f186e3fcaf2dba9cd1ea8d89856 | 7,538 | cpp | C++ | src/pause_state.cpp | diegomacario/Teapong | ef09a8ae4b7c7fe5c12df09592bc267ee9ea586e | [
"MIT"
] | 25 | 2020-01-05T02:59:39.000Z | 2021-09-04T15:47:15.000Z | src/pause_state.cpp | diegomacario/Teapong | ef09a8ae4b7c7fe5c12df09592bc267ee9ea586e | [
"MIT"
] | 2 | 2020-01-05T20:55:04.000Z | 2020-01-22T15:13:20.000Z | src/pause_state.cpp | diegomacario/Teapong | ef09a8ae4b7c7fe5c12df09592bc267ee9ea586e | [
"MIT"
] | 5 | 2020-02-04T23:18:30.000Z | 2021-05-28T20:07:46.000Z | #include "play_state.h"
#include "pause_state.h"
PauseState::PauseState(const std::shared_ptr<FiniteStateMachine>& finiteStateMachine,
const std::shared_ptr<Window>& window,
const std::shared_ptr<Camera>& camera,
const std::shared_ptr<Shader>& gameObject3DShader,
const std::shared_ptr<GameObject3D>& table,
const std::shared_ptr<Paddle>& leftPaddle,
const std::shared_ptr<Paddle>& rightPaddle,
const std::shared_ptr<Ball>& ball,
const std::shared_ptr<GameObject3D>& point)
: mFSM(finiteStateMachine)
, mWindow(window)
, mCamera(camera)
, mGameObject3DShader(gameObject3DShader)
, mTable(table)
, mLeftPaddle(leftPaddle)
, mRightPaddle(rightPaddle)
, mBall(ball)
, mPoint(point)
, mPointsScoredByLeftPaddle(0)
, mPointsScoredByRightPaddle(0)
, mPositionsOfPointsScoredByLeftPaddle({glm::vec3(-47.5f, -34.0f, 0.0f),
glm::vec3(-43.5f, -34.0f, 0.0f),
glm::vec3(-39.5f, -34.0f, 0.0f)})
, mPositionsOfPointsScoredByRightPaddle({glm::vec3(47.5f, -34.0f, 0.0f),
glm::vec3(43.5f, -34.0f, 0.0f),
glm::vec3(39.5f, -34.0f, 0.0f)})
{
}
void PauseState::enter()
{
const PlayState& playState = dynamic_cast<PlayState&>(*mFSM->getPreviousState());
mPointsScoredByLeftPaddle = playState.getPointsScoredByLeftPaddle();
mPointsScoredByRightPaddle = playState.getPointsScoredByRightPaddle();
}
void PauseState::processInput(float deltaTime)
{
// Close the game
if (mWindow->keyIsPressed(GLFW_KEY_ESCAPE)) { mWindow->setShouldClose(true); }
// Make the game full screen or windowed
if (mWindow->keyIsPressed(GLFW_KEY_F) && !mWindow->keyHasBeenProcessed(GLFW_KEY_F))
{
mWindow->setKeyAsProcessed(GLFW_KEY_F);
mWindow->setFullScreen(!mWindow->isFullScreen());
// In the pause state, the following rules are applied to the cursor:
// - Fullscreen: Cursor is always disabled
// - Windowed with a free camera: Cursor is disabled
// - Windowed with a fixed camera: Cursor is enabled
if (mWindow->isFullScreen())
{
// Disable the cursor when fullscreen
mWindow->enableCursor(false);
if (mCamera->isFree())
{
// Going from windowed to fullscreen changes the position of the cursor, so we reset the first move flag to avoid a jump
mWindow->resetFirstMove();
}
}
else if (!mWindow->isFullScreen())
{
if (mCamera->isFree())
{
// Disable the cursor when windowed with a free camera
mWindow->enableCursor(false);
// Going from fullscreen to windowed changes the position of the cursor, so we reset the first move flag to avoid a jump
mWindow->resetFirstMove();
}
else
{
// Enable the cursor when windowed with a fixed camera
mWindow->enableCursor(true);
}
}
}
// Change the number of samples used for anti aliasing
if (mWindow->keyIsPressed(GLFW_KEY_1) && !mWindow->keyHasBeenProcessed(GLFW_KEY_1))
{
mWindow->setKeyAsProcessed(GLFW_KEY_1);
mWindow->setNumberOfSamples(1);
}
else if (mWindow->keyIsPressed(GLFW_KEY_2) && !mWindow->keyHasBeenProcessed(GLFW_KEY_2))
{
mWindow->setKeyAsProcessed(GLFW_KEY_2);
mWindow->setNumberOfSamples(2);
}
else if (mWindow->keyIsPressed(GLFW_KEY_4) && !mWindow->keyHasBeenProcessed(GLFW_KEY_4))
{
mWindow->setKeyAsProcessed(GLFW_KEY_4);
mWindow->setNumberOfSamples(4);
}
else if (mWindow->keyIsPressed(GLFW_KEY_8) && !mWindow->keyHasBeenProcessed(GLFW_KEY_8))
{
mWindow->setKeyAsProcessed(GLFW_KEY_8);
mWindow->setNumberOfSamples(8);
}
// Unpause the game
if (mWindow->keyIsPressed(GLFW_KEY_P) && !mWindow->keyHasBeenProcessed(GLFW_KEY_P))
{
mWindow->setKeyAsProcessed(GLFW_KEY_P);
mFSM->changeState("play");
}
// Reset the camera
if (mWindow->keyIsPressed(GLFW_KEY_R)) { resetCamera(); }
// Make the camera free or fixed
if (mWindow->keyIsPressed(GLFW_KEY_C) && !mWindow->keyHasBeenProcessed(GLFW_KEY_C))
{
mWindow->setKeyAsProcessed(GLFW_KEY_C);
mCamera->setFree(!mCamera->isFree());
if (!mWindow->isFullScreen())
{
if (mCamera->isFree())
{
// Disable the cursor when windowed with a free camera
mWindow->enableCursor(false);
}
else
{
// Enable the cursor when windowed with a fixed camera
mWindow->enableCursor(true);
}
}
mWindow->resetMouseMoved();
}
// Move and orient the camera
if (mCamera->isFree())
{
// Move
if (mWindow->keyIsPressed(GLFW_KEY_W)) { mCamera->processKeyboardInput(Camera::MovementDirection::Forward, deltaTime); }
if (mWindow->keyIsPressed(GLFW_KEY_S)) { mCamera->processKeyboardInput(Camera::MovementDirection::Backward, deltaTime); }
if (mWindow->keyIsPressed(GLFW_KEY_A)) { mCamera->processKeyboardInput(Camera::MovementDirection::Left, deltaTime); }
if (mWindow->keyIsPressed(GLFW_KEY_D)) { mCamera->processKeyboardInput(Camera::MovementDirection::Right, deltaTime); }
// Orient
if (mWindow->mouseMoved())
{
mCamera->processMouseMovement(mWindow->getCursorXOffset(), mWindow->getCursorYOffset());
mWindow->resetMouseMoved();
}
// Zoom
if (mWindow->scrollWheelMoved())
{
mCamera->processScrollWheelMovement(mWindow->getScrollYOffset());
mWindow->resetScrollWheelMoved();
}
}
mWindow->pollEvents();
}
void PauseState::update(float /*deltaTime*/)
{
}
void PauseState::render()
{
mWindow->clearAndBindMultisampleFramebuffer();
// Enable depth testing for 3D objects
glEnable(GL_DEPTH_TEST);
mGameObject3DShader->use();
mGameObject3DShader->setMat4("projectionView", mCamera->getPerspectiveProjectionViewMatrix());
mGameObject3DShader->setVec3("cameraPos", mCamera->getPosition());
mTable->render(*mGameObject3DShader);
mLeftPaddle->render(*mGameObject3DShader);
mRightPaddle->render(*mGameObject3DShader);
// Disable face culling so that we render the inside of the teapot
glDisable(GL_CULL_FACE);
mBall->render(*mGameObject3DShader);
glEnable(GL_CULL_FACE);
displayScore();
mWindow->generateAntiAliasedImage();
mWindow->swapBuffers();
mWindow->pollEvents();
}
void PauseState::exit()
{
}
void PauseState::resetCamera()
{
mCamera->reposition(glm::vec3(0.0f, 0.0f, 95.0f),
glm::vec3(0.0f, 1.0f, 0.0f),
0.0f,
0.0f,
45.0f);
}
void PauseState::displayScore()
{
for (unsigned int i = 0; i < mPointsScoredByLeftPaddle; ++i)
{
mPoint->setPosition(mPositionsOfPointsScoredByLeftPaddle[i]);
mPoint->render(*mGameObject3DShader);
}
for (unsigned int i = 0; i < mPointsScoredByRightPaddle; ++i)
{
mPoint->setPosition(mPositionsOfPointsScoredByRightPaddle[i]);
mPoint->render(*mGameObject3DShader);
}
}
| 33.207048 | 132 | 0.622712 | [
"render",
"3d"
] |
2354546712a338a405beb04b7313b8e10082cd56 | 1,129 | hpp | C++ | Source/TitaniumKit/include/Titanium/UI/OptionDialogShowParams.hpp | garymathews/titanium_mobile_windows | ff2a02d096984c6cad08f498e1227adf496f84df | [
"Apache-2.0"
] | 20 | 2015-04-02T06:55:30.000Z | 2022-03-29T04:27:30.000Z | Source/TitaniumKit/include/Titanium/UI/OptionDialogShowParams.hpp | garymathews/titanium_mobile_windows | ff2a02d096984c6cad08f498e1227adf496f84df | [
"Apache-2.0"
] | 692 | 2015-04-01T21:05:49.000Z | 2020-03-10T10:11:57.000Z | Source/TitaniumKit/include/Titanium/UI/OptionDialogShowParams.hpp | garymathews/titanium_mobile_windows | ff2a02d096984c6cad08f498e1227adf496f84df | [
"Apache-2.0"
] | 22 | 2015-04-01T20:57:51.000Z | 2022-01-18T17:33:15.000Z | /**
* TitaniumKit OptionDialogShowParams
*
* Copyright (c) 2015 by Appcelerator, Inc. All Rights Reserved.
* Licensed under the terms of the Apache Public License.
* Please see the LICENSE included with this distribution for details.
*/
#ifndef _TITANIUM_UI_OPTIONDIALOGSHOWPARAMS_HPP_
#define _TITANIUM_UI_OPTIONDIALOGSHOWPARAMS_HPP_
#include "Titanium/detail/TiBase.hpp"
#include "Titanium/UI/Dimension.hpp"
namespace Titanium
{
namespace UI
{
class View;
using namespace HAL;
/*!
@struct
@discussion This is the OptionDialogShowParams.
Dictionary of options for the Titanium.UI.OptionDialog.show method.
See api/http://docs.appcelerator.com/titanium/3.0/#!/api/showParams
*/
struct OptionDialogShowParams
{
bool animated {false};
Dimension rect;
std::shared_ptr<Titanium::UI::View> view;
};
OptionDialogShowParams js_to_OptionDialogShowParams(const JSObject& object);
JSObject OptionDialogShowParams_to_js(const JSContext& js_context, const OptionDialogShowParams& dict);
} // namespace UI
} // namespace Titanium
#endif // _TITANIUM_UI_OPTIONDIALOGSHOWPARAMS_HPP_
| 26.880952 | 105 | 0.76705 | [
"object"
] |
23554a2bde0fabb6a42e14d9b7775a211a5449f3 | 6,345 | cpp | C++ | examples/todos_qt/window.cpp | deiflou/uroboros | defd4b02e7498abdd6eb2dd867a1a8e5ceda2820 | [
"MIT"
] | null | null | null | examples/todos_qt/window.cpp | deiflou/uroboros | defd4b02e7498abdd6eb2dd867a1a8e5ceda2820 | [
"MIT"
] | null | null | null | examples/todos_qt/window.cpp | deiflou/uroboros | defd4b02e7498abdd6eb2dd867a1a8e5ceda2820 | [
"MIT"
] | null | null | null | //
// MIT License
//
// Copyright (c) 2019 Deif Lou
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
#include "window.hpp"
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QLineEdit>
#include <QScrollArea>
#include <QComboBox>
#include <algorithm>
#include <utility>
todo_widget::todo_widget(QWidget * parent) :
QWidget(parent)
{
QHBoxLayout * horizontal_layout = new QHBoxLayout;
check_box = new QCheckBox;
button = new QPushButton("Remove");
horizontal_layout->setMargin(0);
horizontal_layout->setSpacing(5);
horizontal_layout->addWidget(check_box, 1);
horizontal_layout->addWidget(button);
setLayout(horizontal_layout);
}
window::window(store_type & store) :
store(store)
{
QVBoxLayout * vertical_layout = new QVBoxLayout;
QHBoxLayout * horizontal_layout = new QHBoxLayout;
QPushButton * button = new QPushButton("Add Todo");
QLineEdit * line_edit = new QLineEdit;
QComboBox * combo_box = new QComboBox;
QScrollArea * scroll_area = new QScrollArea;
todos_container = new QWidget;
setMinimumSize(500, 400);
vertical_layout->setMargin(0);
vertical_layout->setSpacing(0);
horizontal_layout->setMargin(10);
horizontal_layout->setSpacing(5);
line_edit->setPlaceholderText("Insert TODO text here");
combo_box->addItems({"Show all", "Show completed", "Show active"});
scroll_area->setWidget(todos_container);
scroll_area->setWidgetResizable(true);
scroll_area->setFrameStyle(QScrollArea::NoFrame);
todos_container->setLayout(new QVBoxLayout);
todos_container->layout()->setAlignment(Qt::AlignTop);
todos_container->layout()->setMargin(10);
todos_container->layout()->setSpacing(5);
horizontal_layout->addWidget(line_edit);
horizontal_layout->addWidget(button);
horizontal_layout->addWidget(combo_box);
vertical_layout->addLayout(horizontal_layout, 0);
vertical_layout->addWidget(scroll_area, 1);
setLayout(vertical_layout);
connect
(
button,
&QPushButton::clicked,
[&store, line_edit]()
{
store.dispatch(add_todo_action_type{line_edit->text().toStdString()});
}
);
connect
(
combo_box,
QOverload<int>::of(&QComboBox::currentIndexChanged),
[&store](int index)
{
visibility_filter_type filter;
if (index == 0)
filter = visibility_filter_type::show_all;
else if (index == 1)
filter = visibility_filter_type::show_completed;
else
filter = visibility_filter_type::show_active;
store.dispatch(set_visibility_action_type{filter});
}
);
}
void
window::notify_state_change()
{
std::vector<std::pair<int, todo_type>> selected_todos;
if (store.state().visibility_filter == visibility_filter_type::show_all)
for (int i = 0; i < store.state().todos.size(); ++i)
selected_todos.push_back({i, store.state().todos[i]});
else if (store.state().visibility_filter == visibility_filter_type::show_completed)
for (int i = 0; i < store.state().todos.size(); ++i)
{
if (store.state().todos[i].is_completed)
selected_todos.push_back({i, store.state().todos[i]});
}
else
for (int i = 0; i < store.state().todos.size(); ++i)
{
if (!store.state().todos[i].is_completed)
selected_todos.push_back({i, store.state().todos[i]});
}
int const size1 = selected_todos.size();
int const size2 = todo_widgets.size();
int diff = size1 - size2;
if (diff > 0)
for (int i = size2; i < size1; ++i)
{
todo_widget * widget = new todo_widget(todos_container);
todos_container->layout()->addWidget(widget);
todo_widgets.push_back(widget);
widget->show();
}
else if (diff < 0)
while (diff++)
{
todo_widget * widget = todo_widgets.back();
widget->setParent(nullptr);
delete widget;
todo_widgets.pop_back();
}
else
if (size1 == 0)
return;
for (int i = 0; i < size1; ++i)
{
todo_widgets[i]->check_box->disconnect();
todo_widgets[i]->button->disconnect();
todo_widgets[i]->check_box->setText
(
selected_todos[i].second.text.c_str()
);
todo_widgets[i]->check_box->setChecked
(
selected_todos[i].second.is_completed
);
connect
(
todo_widgets[i]->check_box,
&QCheckBox::toggled,
[this, index = selected_todos[i].first]()
{
store.dispatch(toggle_todo_action_type{index});
}
);
connect
(
todo_widgets[i]->button,
&QPushButton::clicked,
[this, index = selected_todos[i].first]()
{
store.dispatch(delete_todo_action_type{index});
}
);
}
}
| 32.875648 | 88 | 0.608983 | [
"vector"
] |
235678281ca935d2f181df71a925cc1162699372 | 9,224 | cpp | C++ | src/direct_bt/DBTEnv.cpp | xranby/direct_bt | 135a8cce2307df1c899eac5f25527aadcd529687 | [
"MIT"
] | 1 | 2020-09-04T18:44:13.000Z | 2020-09-04T18:44:13.000Z | src/direct_bt/DBTEnv.cpp | xranby/direct_bt-1 | 135a8cce2307df1c899eac5f25527aadcd529687 | [
"MIT"
] | null | null | null | src/direct_bt/DBTEnv.cpp | xranby/direct_bt-1 | 135a8cce2307df1c899eac5f25527aadcd529687 | [
"MIT"
] | null | null | null | /*
* Author: Sven Gothel <sgothel@jausoft.com>
* Copyright (c) 2020 Gothel Software e.K.
* Copyright (c) 2020 ZAFENA AB
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include <cstring>
#include <string>
#include <memory>
#include <cstdint>
#include <vector>
#include <cstdio>
#include "direct_bt/DBTEnv.hpp"
#include "direct_bt/dbt_debug.hpp"
using namespace direct_bt;
const uint64_t DBTEnv::startupTimeMilliseconds = direct_bt::getCurrentMilliseconds();
bool DBTEnv::debug = false;
std::string DBTEnv::getProperty(const std::string & name) {
const char * value = getenv(name.c_str());
if( nullptr != value ) {
return std::string( value );
} else {
return std::string();
}
}
std::string DBTEnv::getProperty(const std::string & name, const std::string & default_value) {
const std::string value = getProperty(name);
if( 0 == value.length() ) {
COND_PRINT(debug, "DBTEnv::getProperty %s: null -> %s (default)", name.c_str(), default_value.c_str());
return default_value;
} else {
COND_PRINT(debug, "DBTEnv::getProperty %s (default %s): %s", name.c_str(), default_value.c_str(), value.c_str());
return value;
}
}
bool DBTEnv::getBooleanProperty(const std::string & name, const bool default_value) {
const std::string value = getProperty(name);
if( 0 == value.length() ) {
COND_PRINT(debug, "DBTEnv::getBooleanProperty %s: null -> %d (default)", name.c_str(), default_value);
return default_value;
} else {
const bool res = "true" == value;
COND_PRINT(debug, "DBTEnv::getBooleanProperty %s (default %d): %d/%s", name.c_str(), default_value, res, value.c_str());
return res;
}
}
#include <limits.h>
int32_t DBTEnv::getInt32Property(const std::string & name, const int32_t default_value,
const int32_t min_allowed, const int32_t max_allowed)
{
const std::string value = getProperty(name);
if( 0 == value.length() ) {
COND_PRINT(debug, "DBTEnv::getInt32Property %s: null -> %" PRId32 " (default)", name.c_str(), default_value);
return default_value;
} else {
int32_t res = default_value;
char *endptr = NULL;
const long int res0 = strtol(value.c_str(), &endptr, 10);
if( *endptr == '\0' ) {
// string value completely valid
if( INT32_MIN <= res0 && res0 <= INT32_MAX ) {
// matching int32_t value range
const int32_t res1 = (int32_t)res0;
if( min_allowed <= res1 && res1 <= max_allowed ) {
// matching user value range
res = res1;
COND_PRINT(debug, "DBTEnv::getInt32Property %s (default %" PRId32 "): %" PRId32 "/%s",
name.c_str(), default_value, res, value.c_str());
} else {
// invalid user value range
ERR_PRINT("DBTEnv::getInt32Property %s: %" PRId32 "/%s (invalid user range [% " PRId32 "..%" PRId32 "]) -> %" PRId32 " (default)",
name.c_str(), res1, value.c_str(), min_allowed, max_allowed, res);
}
} else {
// invalid int32_t range
ERR_PRINT("DBTEnv::getInt32Property %s: %" PRIu64 "/%s (invalid int32_t range) -> %" PRId32 " (default)",
name.c_str(), (uint64_t)res0, value.c_str(), res);
}
} else {
// string value not fully valid
ERR_PRINT("DBTEnv::getInt32Property %s: %s (invalid string) -> %" PRId32 " (default)",
name.c_str(), value.c_str(), res);
}
return res;
}
}
uint32_t DBTEnv::getUint32Property(const std::string & name, const uint32_t default_value,
const uint32_t min_allowed, const uint32_t max_allowed)
{
const std::string value = getProperty(name);
if( 0 == value.length() ) {
COND_PRINT(debug, "DBTEnv::getUint32Property %s: null -> %" PRIu32 " (default)", name.c_str(), default_value);
return default_value;
} else {
uint32_t res = default_value;
char *endptr = NULL;
unsigned long int res0 = strtoul(value.c_str(), &endptr, 10);
if( *endptr == '\0' ) {
// string value completely valid
if( res0 <= UINT32_MAX ) {
// matching uint32_t value range
const uint32_t res1 = (uint32_t)res0;
if( min_allowed <= res1 && res1 <= max_allowed ) {
// matching user value range
res = res1;
COND_PRINT(debug, "DBTEnv::getUint32Property %s (default %" PRIu32 "): %" PRIu32 "/%s",
name.c_str(), default_value, res, value.c_str());
} else {
// invalid user value range
ERR_PRINT("DBTEnv::getUint32Property %s: %" PRIu32 "/%s (invalid user range [% " PRIu32 "..%" PRIu32 "]) -> %" PRIu32 " (default)",
name.c_str(), res1, value.c_str(), min_allowed, max_allowed, res);
}
} else {
// invalid uint32_t range
ERR_PRINT("DBTEnv::getUint32Property %s: %" PRIu64 "/%s (invalid uint32_t range) -> %" PRIu32 " (default)",
name.c_str(), (uint64_t)res0, value.c_str(), res);
}
} else {
// string value not fully valid
ERR_PRINT("DBTEnv::getUint32Property %s: %s (invalid string) -> %" PRIu32 " (default)",
name.c_str(), value.c_str(), res);
}
return res;
}
}
void DBTEnv::envSet(std::string prefixDomain, std::string basepair) {
trimInPlace(basepair);
if( basepair.length() > 0 ) {
size_t pos = 0, start = 0;
if( (pos = basepair.find('=', start)) != std::string::npos ) {
const size_t elem_len = pos-start; // excluding '='
std::string name = prefixDomain+"."+basepair.substr(start, elem_len);
std::string value = basepair.substr(pos+1, std::string::npos);
trimInPlace(name);
trimInPlace(value);
if( name.length() > 0 ) {
if( value.length() > 0 ) {
COND_PRINT(debug, "DBTEnv::setProperty %s -> %s (explode)", name.c_str(), value.c_str());
setenv(name.c_str(), value.c_str(), 1 /* overwrite */);
} else {
COND_PRINT(debug, "DBTEnv::setProperty %s -> true (explode default-1)", name.c_str());
setenv(name.c_str(), "true", 1 /* overwrite */);
}
}
} else {
const std::string name = prefixDomain+"."+basepair;
COND_PRINT(debug, "DBTEnv::setProperty %s -> true (explode default-0)", name.c_str());
setenv(name.c_str(), "true", 1 /* overwrite */);
}
}
}
void DBTEnv::envExplodeProperties(std::string prefixDomain, std::string list) {
size_t pos = 0, start = 0;
while( (pos = list.find(',', start)) != std::string::npos ) {
const size_t elem_len = pos-start; // excluding ','
envSet(prefixDomain, list.substr(start, elem_len));
start = pos+1; // skip ','
}
const size_t elem_len = list.length()-start; // last one
if( elem_len > 0 ) {
envSet(prefixDomain, list.substr(start, elem_len));
}
COND_PRINT(debug, "DBTEnv::setProperty %s -> true (explode default)", prefixDomain.c_str());
setenv(prefixDomain.c_str(), "true", 1 /* overwrite */);
}
bool DBTEnv::getExplodingProperties(const std::string & prefixDomain) {
std::string value = DBTEnv::getProperty(prefixDomain, "false");
if( "false" == value ) {
return false;
}
if( "true" == value ) {
return true;
}
if( "direct_bt.debug" == prefixDomain ) {
debug = true;
}
envExplodeProperties(prefixDomain, value);
return true;
}
DBTEnv::DBTEnv()
: DEBUG( getExplodingProperties("direct_bt.debug") ),
VERBOSE( getExplodingProperties("direct_bt.verbose") || DBTEnv::DEBUG )
{
}
| 42.311927 | 151 | 0.581093 | [
"vector"
] |
2356f2a36381e1a1a9d0f32b02d9acc04d8dbe57 | 17,700 | hpp | C++ | Base/include/Framework/Collection/List.impl.hpp | BlockProject3D/Framework | 1c27ef19d9a12d158a2b53f6bd28dd2d8e678912 | [
"BSD-3-Clause"
] | 2 | 2019-02-02T20:48:17.000Z | 2019-02-22T09:59:40.000Z | Base/include/Framework/Collection/List.impl.hpp | BlockProject3D/Framework | 1c27ef19d9a12d158a2b53f6bd28dd2d8e678912 | [
"BSD-3-Clause"
] | 125 | 2020-01-14T18:26:38.000Z | 2021-02-23T15:33:55.000Z | Base/include/Framework/Collection/List.impl.hpp | BlockProject3D/Framework | 1c27ef19d9a12d158a2b53f6bd28dd2d8e678912 | [
"BSD-3-Clause"
] | 1 | 2020-05-26T08:55:10.000Z | 2020-05-26T08:55:10.000Z | // Copyright (c) 2020, BlockProject 3D
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// * Neither the name of BlockProject 3D nor the names of its contributors
// may be used to endorse or promote products derived from this software
// without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#pragma once
#include "Framework/Memory/MemUtils.hpp"
namespace bpf
{
namespace collection
{
template <typename T>
inline List<T>::List()
: _first(nullptr)
, _last(nullptr)
, _count(0)
{
}
template <typename T>
inline List<T>::List(List<T> &&other) noexcept
: _first(other._first)
, _last(other._last)
, _count(other._count)
{
other._first = nullptr;
other._last = nullptr;
other._count = 0;
}
template <typename T>
List<T>::List(const List<T> &other)
: _first(nullptr)
, _last(nullptr)
, _count(0)
{
for (auto &elem : other)
Add(elem);
}
template <typename T>
List<T>::List(const std::initializer_list<T> &lst)
: _first(nullptr)
, _last(nullptr)
, _count(0)
{
for (auto &elem : lst)
Add(elem);
}
template <typename T>
inline List<T>::~List()
{
Clear();
}
template <typename T>
List<T> &List<T>::operator=(List<T> &&other) noexcept
{
Clear();
_first = other._first;
_last = other._last;
_count = other._count;
other._first = nullptr;
other._last = nullptr;
other._count = 0;
return (*this);
}
template <typename T>
List<T> &List<T>::operator=(const List<T> &other)
{
if (this == &other)
return (*this);
Clear();
for (auto &elem : other)
Add(elem);
return (*this);
}
template <typename T>
List<T> List<T>::operator+(const List<T> &other) const
{
List<T> cpy = *this;
for (const auto &elem : other)
cpy.Add(elem);
return (cpy);
}
template <typename T>
void List<T>::operator+=(const List<T> &other)
{
for (const auto &elem : other)
Add(elem);
}
template <typename T>
void List<T>::Insert(fsize pos, const T &elem)
{
Node *nd = GetNode(pos);
Node *newi = memory::MemUtils::New<Node>(elem);
newi->Next = nd;
if (nd != nullptr)
{
newi->Prev = nd->Prev;
nd->Prev = newi;
if (newi->Prev != nullptr)
newi->Prev->Next = newi;
if (pos == 0)
_first = newi;
}
else if (_last)
{
newi->Prev = _last;
_last->Next = newi;
_last = newi;
}
else
_first = _last = newi;
++_count;
}
template <typename T>
void List<T>::Insert(fsize pos, T &&elem)
{
Node *nd = GetNode(pos);
Node *newi = memory::MemUtils::New<Node>(std::move(elem));
newi->Next = nd;
if (nd != nullptr)
{
newi->Prev = nd->Prev;
nd->Prev = newi;
if (newi->Prev != nullptr)
newi->Prev->Next = newi;
if (pos == 0)
_first = newi;
}
else if (_last)
{
newi->Prev = _last;
_last->Next = newi;
_last = newi;
}
else
_first = _last = newi;
++_count;
}
template <typename T>
void List<T>::Insert(const Iterator &pos, const T &elem)
{
Node *nd = pos._cur;
Node *newi = memory::MemUtils::New<Node>(elem);
newi->Next = nd;
if (nd != nullptr)
{
newi->Prev = nd->Prev;
nd->Prev = newi;
if (newi->Prev != nullptr)
newi->Prev->Next = newi;
if (pos._cur == _first)
_first = newi;
}
else if (_last)
{
newi->Prev = _last;
_last->Next = newi;
_last = newi;
}
else
_first = _last = newi;
++_count;
}
template <typename T>
void List<T>::Insert(const Iterator &pos, T &&elem)
{
Node *nd = pos._cur;
Node *newi = memory::MemUtils::New<Node>(std::move(elem));
newi->Next = nd;
if (nd != nullptr)
{
newi->Prev = nd->Prev;
nd->Prev = newi;
if (newi->Prev != nullptr)
newi->Prev->Next = newi;
if (pos._cur == _first)
_first = newi;
}
else if (_last)
{
newi->Prev = _last;
_last->Next = newi;
_last = newi;
}
else
_first = _last = newi;
++_count;
}
template <typename T>
void List<T>::Add(const T &elem)
{
Node *newi = memory::MemUtils::New<Node>(elem);
if (_last == nullptr)
_first = newi;
else
{
newi->Prev = _last;
_last->Next = newi;
}
_last = newi;
++_count;
}
template <typename T>
void List<T>::Add(T &&elem)
{
Node *newi = memory::MemUtils::New<Node>(std::move(elem));
if (_last == nullptr)
_first = newi;
else
{
newi->Prev = _last;
_last->Next = newi;
}
_last = newi;
++_count;
}
template <typename T>
inline void List<T>::Clear()
{
while (_count > 0)
RemoveLast();
}
template <typename T>
inline void List<T>::Swap(Node *a, Node *b)
{
T tmpdata = std::move(a->Data);
a->Data = std::move(b->Data);
b->Data = std::move(tmpdata);
}
template <typename T>
template <template <typename> class Comparator>
void List<T>::Merge(Node **startl1, Node **endl1, Node **startr1, Node **endr1)
{
if (Comparator<T>::Eval((*startr1)->Data, (*startl1)->Data))
{
std::swap(*startl1, *startr1);
std::swap(*endl1, *endr1);
}
Node *startl = *startl1;
Node *endl = *endl1;
Node *startr = *startr1;
Node *endrnext = (*endr1)->Next;
while (startl != endl && startr != endrnext)
{
if (Comparator<T>::Eval(startr->Data, startl->Next->Data))
{
Node *tmp = startr->Next;
startr->Next = startl->Next;
startl->Next = startr;
startr = tmp;
}
startl = startl->Next;
}
if (startl == endl)
startl->Next = startr;
else
*endr1 = *endl1;
}
template <typename T>
template <template <typename> class Comparator>
void List<T>::MergeSort()
{
Node *curNode = nullptr;
Node *startl;
Node *startr;
Node *endl;
Node *endr;
for (fsize sz = 1; sz < _count; sz *= 2)
{
startl = _first;
while (startl != nullptr)
{
bool first = false;
if (startl == _first)
first = true;
endl = startl;
for (fsize i = 0; endl->Next != nullptr && i != sz - 1; ++i)
endl = endl->Next;
startr = endl->Next;
if (startr == nullptr)
break;
endr = startr;
for (fsize i = 0; endr->Next != nullptr && i != sz - 1; ++i)
endr = endr->Next;
Node *cpy = endr->Next; // Get a hold on the start for the next partitions before Merge function destroys it...
Merge<Comparator>(&startl, &endl, &startr, &endr);
if (first)
_first = startl;
else
curNode->Next = startl;
curNode = endr;
startl = cpy;
}
curNode->Next = startl;
}
}
template <typename T>
template <template <typename> class Comparator>
typename List<T>::Node *List<T>::Partition(Node *start, Node *end)
{
Node *x = end;
Node *iter = start;
for (Node *j = start; j != end; j = j->Next)
{
if (Comparator<T>::Eval(j->Data, x->Data))
{
Swap(iter, j);
iter = iter->Next;
}
}
Swap(iter, end);
return (iter);
}
template <typename T>
template <template <typename> class Comparator>
void List<T>::QuickSort(Node *start, Node *end)
{
if (end != nullptr && start != end && start != end->Next)
{
Node *res = Partition<Comparator>(start, end);
QuickSort<Comparator>(start, res->Prev);
QuickSort<Comparator>(res->Next, end);
}
}
template <typename T>
template <template <typename> class Comparator>
void List<T>::Sort(const bool stable) //TODO: Adapt to use different sorting functions
{
if (Size() == 0 || Size() == 1)
return;
if (!stable)
QuickSort<Comparator>(_first, _last);
else
{
MergeSort<Comparator>();
/* Re-chain the broken list */
Node *cur = _first;
Node *last = nullptr;
while (cur != nullptr)
{
cur->Prev = last;
last = cur;
cur = cur->Next;
}
_last = last;
}
}
template <typename T>
void List<T>::Swap(const Iterator &a, const Iterator &b)
{
Node *an = a._cur;
Node *bn = b._cur;
if (an == nullptr || bn == nullptr || an == bn)
return;
Swap(an, bn);
}
template <typename T>
void List<T>::RemoveAt(Iterator &pos)
{
if (pos._cur == nullptr)
return;
Node *next = pos._cur->Next;
RemoveNode(pos._cur);
pos._cur = next;
}
template <typename T>
void List<T>::RemoveAt(Iterator &&pos)
{
if (pos._cur == nullptr)
return;
Node *next = pos._cur->Next;
RemoveNode(pos._cur);
pos._cur = next;
}
template <typename T>
typename List<T>::Node *List<T>::GetNode(fsize id) const
{
if (id < _count)
{
if (id <= (_count / 2))
{
Node *cur = _first;
while (id-- > 0)
cur = cur->Next;
return (cur);
}
else
{
Node *cur = _last;
while (++id < _count)
cur = cur->Prev;
return cur;
}
}
return nullptr;
}
template <typename T>
void List<T>::RemoveAt(fsize const pos)
{
Node *toRM = GetNode(pos);
if (toRM)
RemoveNode(toRM);
}
template <typename T>
void List<T>::RemoveNode(Node *toRM)
{
if (toRM == _last)
RemoveLast();
else
{
Node *prev = toRM->Prev;
Node *next = toRM->Next;
if (prev)
prev->Next = next;
else
_first = next;
if (next)
next->Prev = prev;
memory::MemUtils::Delete(toRM);
--_count;
}
}
template <typename T>
template <template <typename> class Comparator>
void List<T>::Remove(const T &elem, const bool all)
{
Node *cur = _first;
while (cur)
{
if (Comparator<T>::Eval(cur->Data, elem))
{
Node *toRM = cur;
cur = (all) ? cur->Next : nullptr;
RemoveNode(toRM);
}
else
cur = cur->Next;
}
}
template <typename T>
void List<T>::RemoveLast()
{
if (_last)
{
Node *lst = _last->Prev;
if (lst)
lst->Next = nullptr;
else
_first = nullptr;
memory::MemUtils::Delete(_last);
_last = lst;
--_count;
}
}
template <typename T>
inline const T &List<T>::operator[](fsize const id) const
{
Node *elem = GetNode(id);
if (elem == nullptr)
throw IndexException((fint)id);
return (elem->Data);
}
template <typename T>
inline T &List<T>::operator[](fsize const id)
{
Node *elem = GetNode(id);
if (elem == nullptr)
throw IndexException((fint)id);
return (elem->Data);
}
template <typename T>
typename List<T>::Iterator List<T>::FindByKey(const fsize pos)
{
Node *elem = GetNode(pos);
return (Iterator(elem, _last));
}
template <typename T>
template <template <typename> class Comparator>
typename List<T>::Iterator List<T>::FindByValue(const T &val)
{
Node *cur = _first;
while (cur)
{
if (Comparator<T>::Eval(cur->Data, val))
return (Iterator(cur, _last));
else
cur = cur->Next;
}
return (Iterator(nullptr, _last));
}
template <typename T>
typename List<T>::Iterator List<T>::Find(const std::function<bool(const fsize pos, const T &val)> &comparator)
{
Node *cur = _first;
fsize pos = 0;
while (cur)
{
if (comparator(pos, cur->Data))
return (Iterator(cur, _last));
cur = cur->Next;
++pos;
}
return (Iterator(nullptr, _last));
}
template <typename T>
bool List<T>::operator==(const List<T> &other) const noexcept
{
if (_count != other._count)
return (false);
Node *cur = _first;
Node *cur1 = other._first;
while (cur != nullptr)
{
if (cur->Data != cur1->Data)
return (false);
cur = cur->Next;
cur1 = cur1->Next;
}
return (true);
}
}
}
| 29.598662 | 131 | 0.42661 | [
"3d"
] |
238593d1d4d3e831e33751c68a3acd75171000aa | 1,282 | cpp | C++ | Problems/Facebook/Facebook_Hacker_Cup/2018/Round_1/B.Ethan_Traverses_a_Tree.cpp | metehkaya/Algo-Archive | 03b5fdcf06f84a03125c57762c36a4e03ca6e756 | [
"MIT"
] | 2 | 2020-07-20T06:40:22.000Z | 2021-11-20T01:23:26.000Z | Problems/Facebook/Facebook_Hacker_Cup/2018/Round_1/B.Ethan_Traverses_a_Tree.cpp | metehkaya/Algo-Archive | 03b5fdcf06f84a03125c57762c36a4e03ca6e756 | [
"MIT"
] | null | null | null | Problems/Facebook/Facebook_Hacker_Cup/2018/Round_1/B.Ethan_Traverses_a_Tree.cpp | metehkaya/Algo-Archive | 03b5fdcf06f84a03125c57762c36a4e03ca6e756 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
#define maxn 2003
#define pb push_back
using namespace std;
int T,n,k,m;
int a[maxn];
int b[maxn];
int mark[maxn];
vector<int> v1,v2;
vector<int> adj[maxn];
void io() {
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
}
void reset() {
m = 0;
v1.clear();
v2.clear();
for( int i = 1 ; i <= n ; i++ )
adj[i].clear();
memset(mark,0,sizeof(mark));
}
void read() {
scanf("%d%d",&n,&k);
for( int i = 1 ; i <= n ; i++ )
scanf("%d%d",&a[i],&b[i]);
}
void dfs2(int node) {
mark[node] = m;
for( int i = 0 ; i < (int) adj[node].size() ; i++ ) {
int to = adj[node][i];
if(!mark[to])
dfs2(to);
}
}
void dfs1(int node) {
v1.pb(node);
if(a[node])
dfs1(a[node]);
if(b[node])
dfs1(b[node]);
v2.pb(node);
}
void solve() {
dfs1(1);
for( int i = 0 ; i < n ; i++ ) {
adj[v1[i]].pb(v2[i]);
adj[v2[i]].pb(v1[i]);
}
for( int i = 1 ; i <= n ; i++ )
if(!mark[i]) {
m++;
dfs2(i);
}
}
void print(int tc) {
if(m < k)
printf("Case #%d: Impossible\n",tc);
else {
printf("Case #%d:",tc);
for( int i = 1 ; i <= n ; i++ )
printf(" %d",min(mark[i],k));
puts("");
}
}
int main() {
io();
scanf("%d",&T);
for( int tc = 1 ; tc <= T ; tc++ ) {
reset();
read();
solve();
print(tc);
}
return 0;
}
| 14.735632 | 54 | 0.49844 | [
"vector"
] |
2385b9ba9cc7b63a4597c6732c7a10290464c0e3 | 802 | cpp | C++ | competitive/c++/codeforces/round 695 div 2/mainb-f.cpp | HackintoshwithUbuntu/BigRepo | 70746ddf7edc1ec9f13fe5f53a40eb4c3ebd2874 | [
"MIT"
] | null | null | null | competitive/c++/codeforces/round 695 div 2/mainb-f.cpp | HackintoshwithUbuntu/BigRepo | 70746ddf7edc1ec9f13fe5f53a40eb4c3ebd2874 | [
"MIT"
] | null | null | null | competitive/c++/codeforces/round 695 div 2/mainb-f.cpp | HackintoshwithUbuntu/BigRepo | 70746ddf7edc1ec9f13fe5f53a40eb4c3ebd2874 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
int n;
vector<int> a(n);
bool isHill(int i){
if(i > 0 && i < n && a[i] > a[i-1] && a[i] > a[i + 1]){
return true;
}else return false;
}
bool isValley(int i){
if(i > 0 && i < n - 1 && a[i] < a[i-1] && a[i] < a[i + 1]){
return true;
}else return false;
}
void solve() {
cin >> n;
int c = 0;
for(int i = 0; i < n; i++){
int x; cin >> x;
a[i] = x;
}
for(int i = 1; i < n - 1; i++){
if(isHill(i) || isValley(i))
c++;
}
for(int i = 0; i < n - 1; i++){
}
int ans;
cout << ans << "\n";
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int t;
cin >> t;
while(t--) {
solve();
}
return 0;
} | 16.367347 | 63 | 0.410224 | [
"vector"
] |
23864ad01e172aeb32f3afd96fcb1f62e907dd8e | 5,057 | cpp | C++ | src/Utility.cpp | jd-zhao/MirrorMirror | c90ed1f4ea521c0315aa003693eb2eea538d7c28 | [
"MIT"
] | 18 | 2016-06-21T19:56:33.000Z | 2021-05-09T19:17:22.000Z | src/Utility.cpp | LTHODAVDOPL/MirrorMirror | 52802123e28840d00f14406ff9789237fbb9faab | [
"MIT"
] | null | null | null | src/Utility.cpp | LTHODAVDOPL/MirrorMirror | 52802123e28840d00f14406ff9789237fbb9faab | [
"MIT"
] | 12 | 2016-12-09T23:49:51.000Z | 2021-05-09T20:05:14.000Z | #include "Utility.h"
const int MAX_FILENAME_LENGTH = 512;
#ifdef _WIN32
#include "io.h"
#include "direct.h"
#include "windows.h"
int utility::CUtility::FindImageFiles(string fName, vector<string>& nameVec,
vector<string> &extVec) {
_assert(fName.length() != 0);
WIN32_FIND_DATA fileName;
WCHAR wch_fileName[MAX_FILENAME_LENGTH];
fName += "*.*";
MultiByteToWideChar(0, 0, fName.c_str(), MAX_FILENAME_LENGTH - 1,
wch_fileName, MAX_FILENAME_LENGTH);
LPCWSTR wstr_fileName = wch_fileName;
HANDLE handle = FindFirstFile(wstr_fileName, &fileName);
int nFiles = 0;
if (handle != INVALID_HANDLE_VALUE) {
do {
int nLen = lstrlen(fileName.cFileName);
char* nPtr = new char[nLen + 1];
nFiles++;
FOR (i, nLen)
nPtr[i] = char(fileName.cFileName[i]);
nPtr[lstrlen(fileName.cFileName)] = '\0';
if (nFiles != 1 && nFiles != 2) {
string strFileName = string(nPtr);
string ext;
if (ParseImageFileName(strFileName, ext)) {
nameVec.push_back(strFileName);
extVec.push_back(ext);
}
}
} while (FindNextFile(handle, &fileName));
} else
DEBUG_ERROR("Fail to open folder.");
FindClose(handle);
return nameVec.size();
}
void utility::CUtility::mkdirs( vector<string> _dirNameVec ) {
FOR (i, (int)_dirNameVec.size()) {
string dir = _dirNameVec[i];
//if (_access(dir.c_str(), 0) == -1)
_mkdir(dir.c_str());
}
}
int utility::CUtility::FindFiles( string _fName, vector<string>& _nameVec ) {
_assert(_fName.length() != 0);
WIN32_FIND_DATA fileName;
WCHAR wch_fileName[MAX_FILENAME_LENGTH];
_fName += "*.*";
char chr[MAX_FILENAME_LENGTH];
strcpy(chr, _fName.c_str());
MultiByteToWideChar(0, 0, chr, MAX_FILENAME_LENGTH,
wch_fileName, MAX_FILENAME_LENGTH);
LPCWSTR wstr_fileName = wch_fileName;
HANDLE handle = FindFirstFile(wstr_fileName, &fileName);
int nFiles = 0;
if (handle != INVALID_HANDLE_VALUE) {
do {
int nLen = lstrlen(fileName.cFileName);
char* nPtr = new char[nLen + 1];
nFiles++;
FOR (i, nLen)
nPtr[i] = char(fileName.cFileName[i]);
nPtr[lstrlen(fileName.cFileName)] = '\0';
string strFileName = string(nPtr);
if (nFiles != 1 && nFiles != 2)
_nameVec.push_back(strFileName);
} while (FindNextFile(handle, &fileName));
} else
DEBUG_ERROR("Fail to open folder.");
FindClose(handle);
return _nameVec.size();
}
#endif
#ifdef __linux__
#include "sys/types.h"
#include "dirent.h"
int utility::CUtility::FindImageFiles(string fName, vector<string>& nameVec,
vector<string> &extVec) {
extVec.clear();
nameVec.clear();
struct dirent* de = NULL;
DIR* dir = opendir(fName.c_str());
if (dir == NULL)
DEBUG_ERROR("Fail to open folder.", fName.c_str());
while ((de = readdir(dir)) != NULL) {
string fileName = string(de->d_name);
string ext;
if (ParseImageFileName(fileName, ext)) {
extVec.push_back(ext);
nameVec.push_back(fileName);
}
}
closedir(dir);
return (int) nameVec.size();
}
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
void utility::CUtility::mkdirs( vector<string> _dirNameVec ) {
FOR (i, (int)_dirNameVec.size()) {
string dir = _dirNameVec[i];
struct stat sb;
if (stat(dir.c_str(), &sb) == -1)
mkdir(dir.c_str(), 0700);
}
}
int utility::CUtility::FindFiles( string _fName, vector<string>& _nameVec ) {
_nameVec.clear();
struct dirent* de = NULL;
DIR* dir = opendir(_fName.c_str());
if (dir == NULL)
DEBUG_WARN("Fail to open folder.", _fName.c_str());
while ((de = readdir(dir)) != NULL) {
string fileName = string(de->d_name);
if (fileName == "." || fileName == "..")
continue;
_nameVec.push_back(fileName);
}
closedir(dir);
return (int)_nameVec.size();
}
#endif
// for both linux and windows
bool utility::CUtility::ParseImageFileName(string& fileName, string& ext) {
string::size_type pos = string::npos;
if ((pos = fileName.find_last_of('.')) != string::npos) {
ext = fileName.substr(pos +1);
if (ext == "jpg" || ext == "JPG" || ext == "png" || ext == "PNG"
|| ext == "bmp" || ext == "BMP" || ext == "jpeg" || ext == "JPEG") {
ext = fileName.substr(pos);
fileName = fileName.substr(0, pos);
return true;
}
}
return false;
}
void utility::CUtility::AddSuffix( vector<string>& _nameVec, string _suffix, vector<string>& _outNameVec ) {
int nNames = (int)_nameVec.size();
_outNameVec.resize(nNames);
#pragma omp parallel for
FOR (i, nNames)
_outNameVec[i] = _nameVec[i] + _suffix;
}
void utility::CUtility::mkdirs( string _dirName ) {
vectorString tmp;
tmp.push_back(_dirName);
mkdirs(tmp);
tmp.clear();
}
| 25.80102 | 109 | 0.601542 | [
"vector"
] |
2388aa75fb938f6e33586f5c316146e5dfa620e1 | 16,369 | cpp | C++ | dali/internal/web-engine/common/web-engine-impl.cpp | dalihub/dali-adaptor | b7943ae5aeb7ddd069be7496a1c1cee186b740c5 | [
"Apache-2.0",
"BSD-3-Clause"
] | 6 | 2016-11-18T10:26:46.000Z | 2021-11-01T12:29:05.000Z | dali/internal/web-engine/common/web-engine-impl.cpp | dalihub/dali-adaptor | b7943ae5aeb7ddd069be7496a1c1cee186b740c5 | [
"Apache-2.0",
"BSD-3-Clause"
] | 5 | 2020-07-15T11:30:49.000Z | 2020-12-11T19:13:46.000Z | dali/internal/web-engine/common/web-engine-impl.cpp | dalihub/dali-adaptor | b7943ae5aeb7ddd069be7496a1c1cee186b740c5 | [
"Apache-2.0",
"BSD-3-Clause"
] | 7 | 2019-05-17T07:14:40.000Z | 2021-05-24T07:25:26.000Z | /*
* Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
// CLASS HEADER
#include <dali/internal/web-engine/common/web-engine-impl.h>
// EXTERNAL INCLUDES
#include <dali/integration-api/debug.h>
#include <dali/public-api/object/type-registry.h>
#include <dlfcn.h>
#include <sstream>
// INTERNAL INCLUDES
#include <dali/devel-api/adaptor-framework/environment-variable.h>
#include <dali/devel-api/adaptor-framework/web-engine-back-forward-list.h>
#include <dali/devel-api/adaptor-framework/web-engine-certificate.h>
#include <dali/devel-api/adaptor-framework/web-engine-console-message.h>
#include <dali/devel-api/adaptor-framework/web-engine-context-menu.h>
#include <dali/devel-api/adaptor-framework/web-engine-context.h>
#include <dali/devel-api/adaptor-framework/web-engine-cookie-manager.h>
#include <dali/devel-api/adaptor-framework/web-engine-http-auth-handler.h>
#include <dali/devel-api/adaptor-framework/web-engine-load-error.h>
#include <dali/devel-api/adaptor-framework/web-engine-policy-decision.h>
#include <dali/devel-api/adaptor-framework/web-engine-settings.h>
#include <dali/internal/system/common/environment-variables.h>
#include <dali/public-api/adaptor-framework/native-image-source.h>
#include <dali/public-api/images/pixel-data.h>
namespace Dali
{
namespace Internal
{
namespace Adaptor
{
namespace // unnamed namespace
{
constexpr char const* const kPluginFullNamePrefix = "libdali2-web-engine-";
constexpr char const* const kPluginFullNamePostfix = "-plugin.so";
constexpr char const* const kPluginFullNameDefault = "libdali2-web-engine-plugin.so";
// Note: Dali WebView policy does not allow to use multiple web engines in an application.
// So once pluginName is set to non-empty string, it will not change.
std::string pluginName;
std::string MakePluginName(const char* environmentName)
{
std::stringstream fullName;
fullName << kPluginFullNamePrefix << environmentName << kPluginFullNamePostfix;
return std::move(fullName.str());
}
Dali::BaseHandle Create()
{
return Dali::WebEngine::New();
}
Dali::TypeRegistration type(typeid(Dali::WebEngine), typeid(Dali::BaseHandle), Create);
} // unnamed namespace
WebEnginePtr WebEngine::New()
{
WebEngine* instance = new WebEngine();
if(!instance->Initialize())
{
delete instance;
return nullptr;
}
return instance;
}
WebEngine::WebEngine()
: mPlugin(NULL),
mHandle(NULL),
mCreateWebEnginePtr(NULL),
mDestroyWebEnginePtr(NULL)
{
}
WebEngine::~WebEngine()
{
if(mHandle != NULL)
{
if(mDestroyWebEnginePtr != NULL)
{
mPlugin->Destroy();
mDestroyWebEnginePtr(mPlugin);
}
dlclose(mHandle);
}
}
bool WebEngine::InitializePluginHandle()
{
if(pluginName.length() == 0)
{
// pluginName is not initialized yet.
const char* name = EnvironmentVariable::GetEnvironmentVariable(DALI_ENV_WEB_ENGINE_NAME);
if(name)
{
pluginName = MakePluginName(name);
mHandle = dlopen(pluginName.c_str(), RTLD_LAZY);
if(mHandle)
{
return true;
}
}
pluginName = std::string(kPluginFullNameDefault);
}
mHandle = dlopen(pluginName.c_str(), RTLD_LAZY);
if(!mHandle)
{
DALI_LOG_ERROR("Can't load %s : %s\n", pluginName.c_str(), dlerror());
return false;
}
return true;
}
bool WebEngine::Initialize()
{
char* error = NULL;
if(!InitializePluginHandle())
{
return false;
}
mCreateWebEnginePtr = reinterpret_cast<CreateWebEngineFunction>(dlsym(mHandle, "CreateWebEnginePlugin"));
if(mCreateWebEnginePtr == NULL)
{
DALI_LOG_ERROR("Can't load symbol CreateWebEnginePlugin(), error: %s\n", error);
return false;
}
mDestroyWebEnginePtr = reinterpret_cast<DestroyWebEngineFunction>(dlsym(mHandle, "DestroyWebEnginePlugin"));
if(mDestroyWebEnginePtr == NULL)
{
DALI_LOG_ERROR("Can't load symbol DestroyWebEnginePlugin(), error: %s\n", error);
return false;
}
mPlugin = mCreateWebEnginePtr();
if(mPlugin == NULL)
{
DALI_LOG_ERROR("Can't create the WebEnginePlugin object\n");
return false;
}
return true;
}
void WebEngine::Create(uint32_t width, uint32_t height, const std::string& locale, const std::string& timezoneId)
{
mPlugin->Create(width, height, locale, timezoneId);
}
void WebEngine::Create(uint32_t width, uint32_t height, uint32_t argc, char** argv)
{
mPlugin->Create(width, height, argc, argv);
}
void WebEngine::Destroy()
{
mPlugin->Destroy();
}
Dali::NativeImageSourcePtr WebEngine::GetNativeImageSource()
{
return mPlugin->GetNativeImageSource();
}
Dali::WebEngineSettings& WebEngine::GetSettings() const
{
return mPlugin->GetSettings();
}
Dali::WebEngineContext& WebEngine::GetContext() const
{
return mPlugin->GetContext();
}
Dali::WebEngineCookieManager& WebEngine::GetCookieManager() const
{
return mPlugin->GetCookieManager();
}
Dali::WebEngineBackForwardList& WebEngine::GetBackForwardList() const
{
return mPlugin->GetBackForwardList();
}
void WebEngine::LoadUrl(const std::string& url)
{
mPlugin->LoadUrl(url);
}
std::string WebEngine::GetTitle() const
{
return mPlugin->GetTitle();
}
Dali::PixelData WebEngine::GetFavicon() const
{
return mPlugin->GetFavicon();
}
std::string WebEngine::GetUrl() const
{
return mPlugin->GetUrl();
}
std::string WebEngine::GetUserAgent() const
{
return mPlugin->GetUserAgent();
}
void WebEngine::SetUserAgent(const std::string& userAgent)
{
mPlugin->SetUserAgent(userAgent);
}
void WebEngine::LoadHtmlString(const std::string& htmlString)
{
mPlugin->LoadHtmlString(htmlString);
}
bool WebEngine::LoadHtmlStringOverrideCurrentEntry(const std::string& html, const std::string& basicUri, const std::string& unreachableUrl)
{
return mPlugin->LoadHtmlStringOverrideCurrentEntry(html, basicUri, unreachableUrl);
}
bool WebEngine::LoadContents(const std::string& contents, uint32_t contentSize, const std::string& mimeType, const std::string& encoding, const std::string& baseUri)
{
return mPlugin->LoadContents(contents, contentSize, mimeType, encoding, baseUri);
}
void WebEngine::Reload()
{
mPlugin->Reload();
}
bool WebEngine::ReloadWithoutCache()
{
return mPlugin->ReloadWithoutCache();
}
void WebEngine::StopLoading()
{
mPlugin->StopLoading();
}
void WebEngine::Suspend()
{
mPlugin->Suspend();
}
void WebEngine::Resume()
{
mPlugin->Resume();
}
void WebEngine::SuspendNetworkLoading()
{
mPlugin->SuspendNetworkLoading();
}
void WebEngine::ResumeNetworkLoading()
{
mPlugin->ResumeNetworkLoading();
}
bool WebEngine::AddCustomHeader(const std::string& name, const std::string& value)
{
return mPlugin->AddCustomHeader(name, value);
}
bool WebEngine::RemoveCustomHeader(const std::string& name)
{
return mPlugin->RemoveCustomHeader(name);
}
uint32_t WebEngine::StartInspectorServer(uint32_t port)
{
return mPlugin->StartInspectorServer(port);
}
bool WebEngine::StopInspectorServer()
{
return mPlugin->StopInspectorServer();
}
void WebEngine::ScrollBy(int32_t deltaX, int32_t deltaY)
{
mPlugin->ScrollBy(deltaX, deltaY);
}
bool WebEngine::ScrollEdgeBy(int32_t deltaX, int32_t deltaY)
{
return mPlugin->ScrollEdgeBy(deltaX, deltaY);
}
void WebEngine::SetScrollPosition(int32_t x, int32_t y)
{
mPlugin->SetScrollPosition(x, y);
}
Dali::Vector2 WebEngine::GetScrollPosition() const
{
return mPlugin->GetScrollPosition();
}
Dali::Vector2 WebEngine::GetScrollSize() const
{
return mPlugin->GetScrollSize();
}
Dali::Vector2 WebEngine::GetContentSize() const
{
return mPlugin->GetContentSize();
}
void WebEngine::RegisterJavaScriptAlertCallback(Dali::WebEnginePlugin::JavaScriptAlertCallback callback)
{
mPlugin->RegisterJavaScriptAlertCallback(callback);
}
void WebEngine::JavaScriptAlertReply()
{
mPlugin->JavaScriptAlertReply();
}
void WebEngine::RegisterJavaScriptConfirmCallback(Dali::WebEnginePlugin::JavaScriptConfirmCallback callback)
{
mPlugin->RegisterJavaScriptConfirmCallback(callback);
}
void WebEngine::JavaScriptConfirmReply(bool confirmed)
{
mPlugin->JavaScriptConfirmReply(confirmed);
}
void WebEngine::RegisterJavaScriptPromptCallback(Dali::WebEnginePlugin::JavaScriptPromptCallback callback)
{
mPlugin->RegisterJavaScriptPromptCallback(callback);
}
void WebEngine::JavaScriptPromptReply(const std::string& result)
{
mPlugin->JavaScriptPromptReply(result);
}
std::unique_ptr<Dali::WebEngineHitTest> WebEngine::CreateHitTest(int32_t x, int32_t y, Dali::WebEngineHitTest::HitTestMode mode)
{
return mPlugin->CreateHitTest(x, y, mode);
}
bool WebEngine::CreateHitTestAsynchronously(int32_t x, int32_t y, Dali::WebEngineHitTest::HitTestMode mode, Dali::WebEnginePlugin::WebEngineHitTestCreatedCallback callback)
{
return mPlugin->CreateHitTestAsynchronously(x, y, mode, callback);
}
bool WebEngine::CanGoForward()
{
return mPlugin->CanGoForward();
}
void WebEngine::GoForward()
{
mPlugin->GoForward();
}
bool WebEngine::CanGoBack()
{
return mPlugin->CanGoBack();
}
void WebEngine::GoBack()
{
mPlugin->GoBack();
}
void WebEngine::EvaluateJavaScript(const std::string& script, Dali::WebEnginePlugin::JavaScriptMessageHandlerCallback resultHandler)
{
mPlugin->EvaluateJavaScript(script, resultHandler);
}
void WebEngine::AddJavaScriptMessageHandler(const std::string& exposedObjectName, Dali::WebEnginePlugin::JavaScriptMessageHandlerCallback handler)
{
mPlugin->AddJavaScriptMessageHandler(exposedObjectName, handler);
}
void WebEngine::ClearAllTilesResources()
{
mPlugin->ClearAllTilesResources();
}
void WebEngine::ClearHistory()
{
mPlugin->ClearHistory();
}
void WebEngine::SetSize(uint32_t width, uint32_t height)
{
mPlugin->SetSize(width, height);
}
void WebEngine::EnableMouseEvents(bool enabled)
{
mPlugin->EnableMouseEvents(enabled);
}
void WebEngine::EnableKeyEvents(bool enabled)
{
mPlugin->EnableKeyEvents(enabled);
}
bool WebEngine::SendTouchEvent(const Dali::TouchEvent& touch)
{
return mPlugin->SendTouchEvent(touch);
}
bool WebEngine::SendKeyEvent(const Dali::KeyEvent& event)
{
return mPlugin->SendKeyEvent(event);
}
void WebEngine::SetFocus(bool focused)
{
mPlugin->SetFocus(focused);
}
void WebEngine::SetDocumentBackgroundColor(Dali::Vector4 color)
{
mPlugin->SetDocumentBackgroundColor(color);
}
void WebEngine::ClearTilesWhenHidden(bool cleared)
{
mPlugin->ClearTilesWhenHidden(cleared);
}
void WebEngine::SetTileCoverAreaMultiplier(float multiplier)
{
mPlugin->SetTileCoverAreaMultiplier(multiplier);
}
void WebEngine::EnableCursorByClient(bool enabled)
{
mPlugin->EnableCursorByClient(enabled);
}
std::string WebEngine::GetSelectedText() const
{
return mPlugin->GetSelectedText();
}
void WebEngine::SetPageZoomFactor(float zoomFactor)
{
mPlugin->SetPageZoomFactor(zoomFactor);
}
float WebEngine::GetPageZoomFactor() const
{
return mPlugin->GetPageZoomFactor();
}
void WebEngine::SetTextZoomFactor(float zoomFactor)
{
mPlugin->SetTextZoomFactor(zoomFactor);
}
float WebEngine::GetTextZoomFactor() const
{
return mPlugin->GetTextZoomFactor();
}
float WebEngine::GetLoadProgressPercentage() const
{
return mPlugin->GetLoadProgressPercentage();
}
void WebEngine::SetScaleFactor(float scaleFactor, Dali::Vector2 point)
{
mPlugin->SetScaleFactor(scaleFactor, point);
}
float WebEngine::GetScaleFactor() const
{
return mPlugin->GetScaleFactor();
}
void WebEngine::ActivateAccessibility(bool activated)
{
mPlugin->ActivateAccessibility(activated);
}
bool WebEngine::SetVisibility(bool visible)
{
return mPlugin->SetVisibility(visible);
}
bool WebEngine::HighlightText(const std::string& text, Dali::WebEnginePlugin::FindOption options, uint32_t maxMatchCount)
{
return mPlugin->HighlightText(text, options, maxMatchCount);
}
void WebEngine::AddDynamicCertificatePath(const std::string& host, const std::string& certPath)
{
mPlugin->AddDynamicCertificatePath(host, certPath);
}
Dali::PixelData WebEngine::GetScreenshot(Dali::Rect<int32_t> viewArea, float scaleFactor)
{
return mPlugin->GetScreenshot(viewArea, scaleFactor);
}
bool WebEngine::GetScreenshotAsynchronously(Dali::Rect<int32_t> viewArea, float scaleFactor, Dali::WebEnginePlugin::ScreenshotCapturedCallback callback)
{
return mPlugin->GetScreenshotAsynchronously(viewArea, scaleFactor, callback);
}
bool WebEngine::CheckVideoPlayingAsynchronously(Dali::WebEnginePlugin::VideoPlayingCallback callback)
{
return mPlugin->CheckVideoPlayingAsynchronously(callback);
}
void WebEngine::RegisterGeolocationPermissionCallback(Dali::WebEnginePlugin::GeolocationPermissionCallback callback)
{
mPlugin->RegisterGeolocationPermissionCallback(callback);
}
void WebEngine::UpdateDisplayArea(Dali::Rect<int32_t> displayArea)
{
mPlugin->UpdateDisplayArea(displayArea);
}
void WebEngine::EnableVideoHole(bool enabled)
{
mPlugin->EnableVideoHole(enabled);
}
bool WebEngine::SendHoverEvent(const Dali::HoverEvent& event)
{
return mPlugin->SendHoverEvent(event);
}
bool WebEngine::SendWheelEvent(const Dali::WheelEvent& event)
{
return mPlugin->SendWheelEvent(event);
}
Dali::WebEnginePlugin::WebEngineFrameRenderedSignalType& WebEngine::FrameRenderedSignal()
{
return mPlugin->FrameRenderedSignal();
}
void WebEngine::RegisterPageLoadStartedCallback(Dali::WebEnginePlugin::WebEnginePageLoadCallback callback)
{
mPlugin->RegisterPageLoadStartedCallback(callback);
}
void WebEngine::RegisterPageLoadInProgressCallback(Dali::WebEnginePlugin::WebEnginePageLoadCallback callback)
{
mPlugin->RegisterPageLoadInProgressCallback(callback);
}
void WebEngine::RegisterPageLoadFinishedCallback(Dali::WebEnginePlugin::WebEnginePageLoadCallback callback)
{
mPlugin->RegisterPageLoadFinishedCallback(callback);
}
void WebEngine::RegisterPageLoadErrorCallback(Dali::WebEnginePlugin::WebEnginePageLoadErrorCallback callback)
{
mPlugin->RegisterPageLoadErrorCallback(callback);
}
void WebEngine::RegisterScrollEdgeReachedCallback(Dali::WebEnginePlugin::WebEngineScrollEdgeReachedCallback callback)
{
mPlugin->RegisterScrollEdgeReachedCallback(callback);
}
void WebEngine::RegisterUrlChangedCallback(Dali::WebEnginePlugin::WebEngineUrlChangedCallback callback)
{
mPlugin->RegisterUrlChangedCallback(callback);
}
void WebEngine::RegisterFormRepostDecidedCallback(Dali::WebEnginePlugin::WebEngineFormRepostDecidedCallback callback)
{
mPlugin->RegisterFormRepostDecidedCallback(callback);
}
void WebEngine::RegisterConsoleMessageReceivedCallback(Dali::WebEnginePlugin::WebEngineConsoleMessageReceivedCallback callback)
{
mPlugin->RegisterConsoleMessageReceivedCallback(callback);
}
void WebEngine::RegisterResponsePolicyDecidedCallback(Dali::WebEnginePlugin::WebEngineResponsePolicyDecidedCallback callback)
{
mPlugin->RegisterResponsePolicyDecidedCallback(callback);
}
void WebEngine::RegisterCertificateConfirmedCallback(Dali::WebEnginePlugin::WebEngineCertificateCallback callback)
{
mPlugin->RegisterCertificateConfirmedCallback(callback);
}
void WebEngine::RegisterSslCertificateChangedCallback(Dali::WebEnginePlugin::WebEngineCertificateCallback callback)
{
mPlugin->RegisterSslCertificateChangedCallback(callback);
}
void WebEngine::RegisterHttpAuthHandlerCallback(Dali::WebEnginePlugin::WebEngineHttpAuthHandlerCallback callback)
{
mPlugin->RegisterHttpAuthHandlerCallback(callback);
}
void WebEngine::RegisterContextMenuShownCallback(Dali::WebEnginePlugin::WebEngineContextMenuShownCallback callback)
{
mPlugin->RegisterContextMenuShownCallback(callback);
}
void WebEngine::RegisterContextMenuHiddenCallback(Dali::WebEnginePlugin::WebEngineContextMenuHiddenCallback callback)
{
mPlugin->RegisterContextMenuHiddenCallback(callback);
}
void WebEngine::GetPlainTextAsynchronously(Dali::WebEnginePlugin::PlainTextReceivedCallback callback)
{
mPlugin->GetPlainTextAsynchronously(callback);
}
} // namespace Adaptor
} // namespace Internal
} // namespace Dali
| 24.952744 | 172 | 0.776956 | [
"object"
] |
23af62881446a216763396403af04759e1023cd4 | 3,909 | hpp | C++ | src/pscs/src_gen/PSCS/Semantics/Loci/LociPackage.hpp | MDE4CPP/MDE4CPP | 9db9352dd3b1ae26a5f640e614ed3925499b93f1 | [
"MIT"
] | 12 | 2017-02-17T10:33:51.000Z | 2022-03-01T02:48:10.000Z | src/pscs/src_gen/PSCS/Semantics/Loci/LociPackage.hpp | ndongmo/MDE4CPP | 9db9352dd3b1ae26a5f640e614ed3925499b93f1 | [
"MIT"
] | 28 | 2017-10-17T20:23:52.000Z | 2021-03-04T16:07:13.000Z | src/pscs/src_gen/PSCS/Semantics/Loci/LociPackage.hpp | ndongmo/MDE4CPP | 9db9352dd3b1ae26a5f640e614ed3925499b93f1 | [
"MIT"
] | 22 | 2017-03-24T19:03:58.000Z | 2022-03-31T12:10:07.000Z | //********************************************************************
//*
//* Warning: This file was generated by ecore4CPP Generator
//*
//********************************************************************
#ifndef PSCS_SEMANTICS_LOCIPACKAGE_HPP
#define PSCS_SEMANTICS_LOCIPACKAGE_HPP
#include "ecore/EPackage.hpp"
namespace ecore
{
class EAnnotation;
class EClass;
class EDataType;
class EGenericType;
class EOperation;
class EParameter;
class EReference;
class EStringToStringMapEntry;
}
namespace PSCS::Semantics::Loci
{
class CS_ExecutionFactory;
class CS_Executor;
class CS_Locus;
}
namespace PSCS::Semantics::Loci
{
/*!
The Metamodel Package for the Loci metamodel. This package is used to enable the reflection of model elements. It contains all model elements
which were described in an ecore file.
*/
class LociPackage : virtual public ecore::EPackage
{
private:
LociPackage(LociPackage const&) = delete;
LociPackage& operator=(LociPackage const&) = delete;
protected:
LociPackage(){}
public:
//static variables
static const std::string eNAME;
static const std::string eNS_URI;
static const std::string eNS_PREFIX;
// Begin Class CS_ExecutionFactory
//Class and Feature IDs
static const unsigned long CS_EXECUTIONFACTORY_CLASS = 1845389668;
static const unsigned int CS_EXECUTIONFACTORY_CLASS_FEATURE_COUNT = 5;
static const unsigned int CS_EXECUTIONFACTORY_CLASS_OPERATION_COUNT = 14;
static const int CS_EXECUTIONFACTORY_ATTRIBUTE_APPLIEDPROFILES = 1404;
static const int CS_EXECUTIONFACTORY_OPERATION_GETSTEREOTYPEAPPLICATION_CLASS_ELEMENT = 1418;
static const int CS_EXECUTIONFACTORY_OPERATION_GETSTEREOTYPECLASS_ESTRING_ESTRING = 1417;
static const int CS_EXECUTIONFACTORY_OPERATION_INSTANTIATEVISITOR_ELEMENT = 1416;
//Class and Feature Getter
virtual std::shared_ptr<ecore::EClass> getCS_ExecutionFactory_Class() const = 0;
virtual std::shared_ptr<ecore::EReference> getCS_ExecutionFactory_Attribute_appliedProfiles() const = 0;
virtual std::shared_ptr<ecore::EOperation> getCS_ExecutionFactory_Operation_getStereotypeApplication_Class_Element() const = 0;
virtual std::shared_ptr<ecore::EOperation> getCS_ExecutionFactory_Operation_getStereotypeClass_EString_EString() const = 0;
virtual std::shared_ptr<ecore::EOperation> getCS_ExecutionFactory_Operation_instantiateVisitor_Element() const = 0;
// End Class CS_ExecutionFactory
// Begin Class CS_Executor
//Class and Feature IDs
static const unsigned long CS_EXECUTOR_CLASS = 1795074587;
static const unsigned int CS_EXECUTOR_CLASS_FEATURE_COUNT = 1;
static const unsigned int CS_EXECUTOR_CLASS_OPERATION_COUNT = 4;
static const int CS_EXECUTOR_OPERATION_START_CLASS_PARAMETERVALUE = 1504;
//Class and Feature Getter
virtual std::shared_ptr<ecore::EClass> getCS_Executor_Class() const = 0;
virtual std::shared_ptr<ecore::EOperation> getCS_Executor_Operation_start_Class_ParameterValue() const = 0;
// End Class CS_Executor
// Begin Class CS_Locus
//Class and Feature IDs
static const unsigned long CS_LOCUS_CLASS = 264779363;
static const unsigned int CS_LOCUS_CLASS_FEATURE_COUNT = 3;
static const unsigned int CS_LOCUS_CLASS_OPERATION_COUNT = 8;
static const int CS_LOCUS_OPERATION_INSTANTIATE_CLASS = 2010;
//Class and Feature Getter
virtual std::shared_ptr<ecore::EClass> getCS_Locus_Class() const = 0;
virtual std::shared_ptr<ecore::EOperation> getCS_Locus_Operation_instantiate_Class() const = 0;
// End Class CS_Locus
//Singleton Instance and Getter
private:
static std::shared_ptr<LociPackage> instance;
public:
static std::shared_ptr<LociPackage> eInstance();
};
}
#endif /* end of include guard: PSCS_SEMANTICS_LOCIPACKAGE_HPP */
| 30.539063 | 142 | 0.73625 | [
"model"
] |
23ba1619b5aff7814b74371ae194372908496afc | 1,730 | cpp | C++ | disjoint-sets-union/2-C.cpp | forestLoop/Learning-ITMO-Academy-Pilot-Course | b70ea387cb6a7c26871d99ecf7109fd8f0237c3e | [
"MIT"
] | 6 | 2021-07-04T08:47:48.000Z | 2022-01-12T09:34:20.000Z | disjoint-sets-union/2-C.cpp | forestLoop/Learning-ITMO-Academy-Pilot-Course | b70ea387cb6a7c26871d99ecf7109fd8f0237c3e | [
"MIT"
] | null | null | null | disjoint-sets-union/2-C.cpp | forestLoop/Learning-ITMO-Academy-Pilot-Course | b70ea387cb6a7c26871d99ecf7109fd8f0237c3e | [
"MIT"
] | 2 | 2021-11-24T12:18:58.000Z | 2022-02-06T00:18:51.000Z | // C. Restructuring Company
// https://codeforces.com/edu/course/2/lesson/7/2/practice/contest/289391/problem/C
#include <iostream>
#include <set>
#include <vector>
class Company {
public:
Company(int n)
: parent_(n, -1) {
std::set<int>::iterator it = unconnected_.end();
for (int i = 0; i < n; ++i) {
it = unconnected_.insert(it, i);
}
}
int Find(int x) {
if (parent_[x] < 0) {
return x;
}
return parent_[x] = Find(parent_[x]);
}
int UnionTwo(int x, int y) {
x = Find(x), y = Find(y);
if (x == y) {
return x;
}
if (parent_[x] > parent_[y]) {
std::swap(x, y);
}
parent_[x] += parent_[y];
parent_[y] = x;
return x;
}
void UnionRange(int x, int y) {
int pos = x;
while ((pos = *unconnected_.lower_bound(pos)) < y) {
unconnected_.erase(pos);
UnionTwo(pos, pos + 1);
}
}
private:
std::vector<int> parent_;
std::set<int> unconnected_;
};
int main() {
int n, q;
while (std::cin >> n >> q) {
Company company(n + 1);
int op_type, x, y;
while (q--) {
std::cin >> op_type >> x >> y;
if (op_type == 1) {
company.UnionTwo(x, y);
} else if (op_type == 2) {
company.UnionRange(x, y);
} else {
std::cout << (company.Find(x) == company.Find(y) ? "YES" : "NO") << '\n';
}
}
}
}
static const auto speedup = []() {
std::ios::sync_with_stdio(false);
std::cin.tie(nullptr);
std::cout.tie(nullptr);
return 0;
}();
| 23.066667 | 89 | 0.459538 | [
"vector"
] |
23bcfa15e62ea02995f8da38e306601ee0b650ba | 1,902 | cpp | C++ | 2D platformer/Game/Source/Checkpoint.cpp | avocadolau/Platformer2D | 40bed2c7b019434a65760288783b4b1d78f7a5d8 | [
"MIT"
] | null | null | null | 2D platformer/Game/Source/Checkpoint.cpp | avocadolau/Platformer2D | 40bed2c7b019434a65760288783b4b1d78f7a5d8 | [
"MIT"
] | null | null | null | 2D platformer/Game/Source/Checkpoint.cpp | avocadolau/Platformer2D | 40bed2c7b019434a65760288783b4b1d78f7a5d8 | [
"MIT"
] | null | null | null | #include "Checkpoint.h"
#include "App.h"
#include "Input.h"
#include "Textures.h"
#include "Audio.h"
#include "Render.h"
#include "Window.h"
#include "SceneGame.h"
#include "SceneWin.h"
#include "SceneLose.h"
#include "Collisions.h"
#include "Collider.h"
#include "Map.h"
#include "Animation.h"
#include "FadeToBlack.h"
#include "Defs.h"
#include "Log.h"
Checkpoint::Checkpoint() : Module()
{
name.Create("checkpoint");
active = false;
}
Checkpoint::~Checkpoint()
{
}
bool Checkpoint::Awake(pugi::xml_node& config)
{
LOG("Loading Player");
bool ret = true;
dim.x = 0;
dim.y = 0;
dim.w = config.child("sprite").attribute("width").as_int();
dim.h= config.child("sprite").attribute("height").as_int();
spritesPath = config.child("sprite").attribute("path").as_string();
pos.x = config.child("state").attribute("x").as_int();
pos.y = config.child("state").attribute("y").as_int();
activated = config.child("state").attribute("activated").as_bool();
return ret;
}
bool Checkpoint::Start()
{
active = false;
sprites = app->tex->Load(spritesPath.GetString());
CreateColliders();
return true;
}
bool Checkpoint::PreUpdate()
{
return true;
}
bool Checkpoint::Update(float dt)
{
return true;
}
bool Checkpoint::PostUpdate()
{
app->render->DrawTexture(sprites, pos.x, pos.y, &dim);
return true;
}
bool Checkpoint::CleanUp()
{
return true;
}
bool Checkpoint::LoadState(pugi::xml_node& node)
{
return true;
}
bool Checkpoint::SaveState(pugi::xml_node& node) const
{
return true;
}
bool Checkpoint::CreateColliders()
{
if (collider != NULL) app->collisions->RemoveCollider(collider);
collider = app->collisions->AddCollider(dim, Collider::Type::DETECTOR, this);
return true;
}
void Checkpoint::OnCollision(Collider* c1, Collider* c2)
{
if (activated) return;
if (c2->type == Collider::Type::PLAYER) {
activated = true;
app->SaveGameRequest();
}
}
| 16.25641 | 78 | 0.684543 | [
"render"
] |
23c4a4f8c6954827388fc3daf9498ffa3019f81f | 1,083 | cpp | C++ | src/Graphics/Text.cpp | jkbz64/Zadymka | 16c2bf66ce6c3bbff8eeeb3fad291b2939e4a5b7 | [
"MIT"
] | 2 | 2020-03-18T16:13:04.000Z | 2021-07-30T12:18:52.000Z | src/Graphics/Text.cpp | jkbz64/Zadymka | 16c2bf66ce6c3bbff8eeeb3fad291b2939e4a5b7 | [
"MIT"
] | null | null | null | src/Graphics/Text.cpp | jkbz64/Zadymka | 16c2bf66ce6c3bbff8eeeb3fad291b2939e4a5b7 | [
"MIT"
] | null | null | null | #include <Graphics/Text.hpp>
#include <Graphics/Glyph.hpp>
#include <Graphics/Font.hpp>
#include <Graphics/Renderer.hpp>
Text::Text() :
Drawable()
{
setColor(Color::Black);
setCharacterSize(48);
}
Text::Text(Font &font) :
Text()
{
m_font = &font;
}
const std::string& Text::string() const
{
return m_text;
}
const glm::vec2& Text::position() const
{
return m_translation;
}
unsigned int Text::characterSize() const
{
return m_characterSize;
}
const Color& Text::color() const
{
return m_color;
}
Font* Text::font() const
{
return m_font;
}
void Text::setPosition(const glm::vec2& pos)
{
translate(glm::vec2(pos.x, pos.y));
}
void Text::setString(const std::string& str)
{
m_text = str;
}
void Text::setColor(const Color& color)
{
m_color = color;
}
void Text::setFont(Font *font)
{
m_font = font;
}
void Text::setCharacterSize(unsigned int charSize)
{
m_characterSize = charSize;
scale(1.f, static_cast<float>(m_characterSize) / 48.f);
}
void Text::draw(Renderer *renderer)
{
renderer->render(*this);
} | 14.835616 | 59 | 0.65928 | [
"render"
] |
23c8fed558420b85e9cca1aef5a0caf681ec086c | 475 | cpp | C++ | CodeBlocks/Codeforces/Solved/Codeforces118A.cpp | ash1247/DocumentsWindows | 66f65b5170a1ba766cfae08b7104b63ab87331c2 | [
"MIT"
] | null | null | null | CodeBlocks/Codeforces/Solved/Codeforces118A.cpp | ash1247/DocumentsWindows | 66f65b5170a1ba766cfae08b7104b63ab87331c2 | [
"MIT"
] | null | null | null | CodeBlocks/Codeforces/Solved/Codeforces118A.cpp | ash1247/DocumentsWindows | 66f65b5170a1ba766cfae08b7104b63ab87331c2 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
int main(void)
{
string str;
char vowels[] = {'a', 'o', 'y', 'e', 'u', 'i'};
cin >> str;
transform(str.begin(), str.end(), str.begin(), ::tolower );
for(int j = 0; j <= strlen(vowels); j++)
{
str.erase(remove(str.begin(), str.end(), vowels[j] ), str.end() ) ;
}
for(int i = 0; i < str.length(); i++)
{
str.insert(i, ".");
i++;
}
cout << str << '\n';
}
| 16.37931 | 75 | 0.450526 | [
"transform"
] |
23ca55979e2bd597d512b21d1121dbc936bd6ead | 1,625 | cpp | C++ | src/epecur/TrackReconstructionHook.cpp | veprbl/libepecur | 83167ac6220e69887c03b556f1a7ffc518cbb227 | [
"Unlicense"
] | 1 | 2021-06-25T13:41:19.000Z | 2021-06-25T13:41:19.000Z | src/epecur/TrackReconstructionHook.cpp | veprbl/libepecur | 83167ac6220e69887c03b556f1a7ffc518cbb227 | [
"Unlicense"
] | null | null | null | src/epecur/TrackReconstructionHook.cpp | veprbl/libepecur | 83167ac6220e69887c03b556f1a7ffc518cbb227 | [
"Unlicense"
] | null | null | null | #include <cstdlib>
#include <cmath>
#include <boost/assert.hpp>
#include <boost/foreach.hpp>
#include "TrackReconstructionHook.hpp"
TrackReconstructionHook::TrackReconstructionHook(
Geometry &g,
StdHits::calibration_curve_t *c
)
: StdHits(g, c),
geom(g)
{
// nothing
}
void TrackReconstructionHook::handle_event_start()
{
StdHits::handle_event_start();
BOOST_FOREACH(auto gr_tup, last_tracks)
{
BOOST_FOREACH(auto axis_tup, gr_tup.second)
{
axis_tup.second.clear();
}
}
}
void TrackReconstructionHook::handle_event_end()
{
StdHits::handle_event_end();
vector< vector<wire_pos_t>* > block;
BOOST_FOREACH(auto &gr_tup, geom.group_chambers)
{
group_id_t group_id = gr_tup.first;
device_type_t device_type = geom.group_device_type[group_id];
double max_chisq = geom.group_max_chisq[group_id];
BOOST_FOREACH(auto &axis_tup, gr_tup.second)
{
device_axis_t axis = axis_tup.first;
const vector<chamber_id_t> &chambers = axis_tup.second;
block.clear();
BOOST_FOREACH(chamber_id_t chamber_id, chambers)
{
block.push_back(&last_event[chamber_id]);
}
vector<double> &normal_pos = geom.normal_pos[group_id][axis];
if ((device_type == DEV_TYPE_PROP) ||
((device_type == DEV_TYPE_DRIFT) && (calibration_curve == NULL)))
{
last_tracks[group_id][axis] = reconstruct_all_tracks<track_type_t::prop>(block, normal_pos, max_chisq);
}
else if (device_type == DEV_TYPE_DRIFT)
{
last_tracks[group_id][axis] = reconstruct_all_tracks<track_type_t::drift>(block, normal_pos, max_chisq);
}
else
{
throw "Invalid dev type";
}
}
}
}
| 21.959459 | 108 | 0.718154 | [
"geometry",
"vector"
] |
23caad4c357d392e19e268e1e0dccda731b30cb8 | 1,923 | cpp | C++ | aoapcbac2nd/example8-15_shuffle.cpp | aoibird/pc | b72c0b10117f95d45e2e7423614343b5936b260a | [
"MIT"
] | null | null | null | aoapcbac2nd/example8-15_shuffle.cpp | aoibird/pc | b72c0b10117f95d45e2e7423614343b5936b260a | [
"MIT"
] | null | null | null | aoapcbac2nd/example8-15_shuffle.cpp | aoibird/pc | b72c0b10117f95d45e2e7423614343b5936b260a | [
"MIT"
] | null | null | null | // UVa 12174
#include <cctype>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <vector>
#include <map>
#include <set>
using namespace std;
typedef long long ll;
typedef pair<int,int> PII;
const int MAXN = 100000 + 10;
int CNT[MAXN];
vector<int> V;
set<int> MUL;
map<int,bool> SAT;
int N, S;
void print_cnt()
{
printf("CNT = ");
for (int i = 0; i <= S; i++) { printf("%d%c", CNT[i], i==S?'\n':' '); }
}
void print_mul()
{
printf("MUL = ");
for (set<int>::iterator it = MUL.begin();
it != MUL.end(); it++) {
printf("%d ", *it);
}
printf("\n");
}
bool satisfy(int x)
{
for (int i = x; i < N; i += S) {
if (SAT[i] == false) return false;
}
return true;
}
void solve()
{
N = V.size();
// for (int i = 0; i < N; i++) { printf("%d%c", V[i], i==N-1?'\n':' '); }
for (int i = 0; i < S; i++) CNT[V[i]] += 1;
for (int i = S; i < N; i++) {
CNT[V[i-S]] -= 1;
CNT[V[i]] += 1;
if (V[i-S] != 0 && CNT[V[i-S]] == 1) MUL.erase(V[i-S]);
if (V[i] != 0 && CNT[V[i]] >= 2) MUL.insert(V[i]);
if (MUL.size() == 0) SAT[i] = true;
else SAT[i] = false;
// printf("[%d] %d ok? %d\n", i, V[i], SAT[i]);
// print_cnt();
// print_mul();
}
int cnt = 0;
for (int i = S; i < 2*S; i++) {
// printf("%d -> ok? %d\n", i, satisfy(i));
if (satisfy(i)) cnt++;
}
printf("%d\n", cnt);
}
int main()
{
int TC; scanf("%d", &TC);
for (int tc = 0; tc < TC; tc++) {
V.resize(0);
memset(CNT, 0, sizeof(CNT));
MUL.clear();
scanf("%d%d", &S, &N);
for (int i = 0; i < S; i++) { V.push_back(0); }
for (int i = 0; i < N; i++) { int a; scanf("%d", &a); V.push_back(a); }
for (int i = 0; i < S; i++) { V.push_back(0); }
solve();
}
}
| 21.606742 | 79 | 0.447218 | [
"vector"
] |
23d3293b1745b6cb711e08a967aa722990158fbf | 10,756 | cpp | C++ | Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/app/ListFragment.cpp | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | 7 | 2017-07-13T10:34:54.000Z | 2021-04-16T05:40:35.000Z | Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/app/ListFragment.cpp | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | null | null | null | Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/app/ListFragment.cpp | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | 9 | 2017-07-13T12:33:20.000Z | 2021-06-19T02:46:48.000Z | //=========================================================================
// Copyright (C) 2012 The Elastos Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//=========================================================================
#include "elastos/droid/app/ListFragment.h"
#include "elastos/droid/R.h"
#include "elastos/droid/view/animation/AnimationUtils.h"
#include "elastos/droid/os/CHandler.h"
#include <elastos/utility/logging/Slogger.h>
using Elastos::Utility::Logging::Slogger;
using Elastos::Droid::R;
using Elastos::Droid::Os::IBinder;
using Elastos::Droid::Os::CHandler;
using Elastos::Droid::View::IViewParent;
using Elastos::Droid::View::EIID_IViewParent;
using Elastos::Droid::View::Animation::IAnimation;
using Elastos::Droid::View::Animation::AnimationUtils;
using Elastos::Droid::Widget::IAdapter;
using Elastos::Droid::Widget::EIID_IAdapterViewOnItemClickListener;
namespace Elastos {
namespace Droid {
namespace App {
ECode ListFragment::MyRunnable::Run()
{
IViewParent::Probe(mHost->mList)->FocusableViewAvailable(IView::Probe(mHost->mList));
return NOERROR;
}
CAR_INTERFACE_IMPL(ListFragment::MyOnItemClickListener, Object, IAdapterViewOnItemClickListener)
ECode ListFragment::MyOnItemClickListener::OnItemClick(
/* [in] */ IAdapterView* parent,
/* [in] */ IView* view,
/* [in] */ Int32 position,
/* [in] */ Int64 id)
{
return mHost->OnListItemClick(IListView::Probe(parent), view, position, id);
}
CAR_INTERFACE_IMPL(ListFragment, Fragment, IListFragment)
ListFragment::ListFragment()
: mAdapter(NULL)
, mList(NULL)
, mEmptyView(NULL)
, mStandardEmptyView(NULL)
, mProgressContainer(NULL)
, mListContainer(NULL)
, mEmptyText(NULL)
, mListShown(FALSE)
, mRequestFocus(new MyRunnable(this))
, mOnClickListener(new MyOnItemClickListener(this))
{
CHandler::New((IHandler**)&mHandler);
}
ListFragment::~ListFragment()
{}
ECode ListFragment::constructor()
{
return Fragment::constructor();
}
ECode ListFragment::OnCreateView(
/* [in] */ ILayoutInflater* inflater,
/* [in] */ IViewGroup* container,
/* [in] */ IBundle* savedInstanceState,
/* [out] */ IView** view)
{
return inflater->Inflate(R::layout::list_content,
container, FALSE, view);
}
ECode ListFragment::OnViewCreated(
/* [in] */ IView* view,
/* [in] */ IBundle* savedInstanceState)
{
FAIL_RETURN(Fragment::OnViewCreated(view, savedInstanceState))
FAIL_RETURN(EnsureList())
return NOERROR;
}
ECode ListFragment::OnDestroyView()
{
mHandler->RemoveCallbacks(mRequestFocus);
mList = NULL;
mListShown = FALSE;
mEmptyView = mProgressContainer = mListContainer = NULL;
mStandardEmptyView = NULL;
Fragment::OnDestroyView();
return NOERROR;
}
ECode ListFragment::OnListItemClick(
/* [in] */ IListView* l,
/* [in] */ IView* v,
/* [in] */ Int32 position,
/* [in] */ Int64 id)
{
return NOERROR;
}
ECode ListFragment::SetListAdapter(
/* [in] */ IListAdapter* adapter)
{
Boolean hadAdapter = mAdapter != NULL;
mAdapter = adapter;
if (mList != NULL) {
IAdapterView::Probe(mList)->SetAdapter(IAdapter::Probe(adapter));
if (!mListShown && !hadAdapter) {
// The list was hidden, and previously didn't have an
// adapter. It is now time to show it.
AutoPtr<IView> view;
GetView((IView**)&view);
AutoPtr<IBinder> token;
view->GetWindowToken((IBinder**)&token);
FAIL_RETURN(SetListShown(TRUE, token != NULL))
}
}
return NOERROR;
}
ECode ListFragment::SetSelection(
/* [in] */ Int32 position)
{
FAIL_RETURN(EnsureList())
IAdapterView::Probe(mList)->SetSelection(position);
return NOERROR;
}
ECode ListFragment::GetSelectedItemPosition(
/* [out] */ Int32* position)
{
VALIDATE_NOT_NULL(position);
FAIL_RETURN(EnsureList())
IAdapterView::Probe(mList)->GetSelectedItemPosition(position);
return NOERROR;
}
ECode ListFragment::GetSelectedItemId(
/* [out] */ Int64* id)
{
VALIDATE_NOT_NULL(id);
FAIL_RETURN(EnsureList())
IAdapterView::Probe(mList)->GetSelectedItemId(id);
return NOERROR;
}
ECode ListFragment::GetListView(
/* [out] */ IListView** listview)
{
VALIDATE_NOT_NULL(listview);
FAIL_RETURN(EnsureList())
*listview = mList;
REFCOUNT_ADD(*listview);
return NOERROR;
}
ECode ListFragment::SetEmptyText(
/* [in] */ ICharSequence* text)
{
FAIL_RETURN(EnsureList())
if (mStandardEmptyView == NULL) {
// throw new IllegalStateException("Can't be used with a custom content view");
Slogger::E("ListFragment", "Can't be used with a custom content view");
return E_ILLEGAL_STATE_EXCEPTION;
}
mStandardEmptyView->SetText(text);
if (mEmptyText == NULL) {
IAdapterView::Probe(mList)->SetEmptyView(IView::Probe(mStandardEmptyView));
}
mEmptyText = text;
return NOERROR;
}
ECode ListFragment::SetListShown(
/* [in] */ Boolean shown)
{
return SetListShown(shown, TRUE);
}
ECode ListFragment::SetListShownNoAnimation(
/* [in] */ Boolean shown)
{
return SetListShown(shown, FALSE);
}
ECode ListFragment::SetListShown(
/* [in] */ Boolean shown,
/* [in] */ Boolean animate)
{
FAIL_RETURN(EnsureList())
if (mProgressContainer == NULL) {
// throw new IllegalStateException("Can't be used with a custom content view");
Slogger::E("ListFragment", "Can't be used with a custom content view");
return E_ILLEGAL_STATE_EXCEPTION;
}
if (mListShown == shown) {
return NOERROR;
}
mListShown = shown;
if (shown) {
if (animate) {
AutoPtr<IAnimation> aOut, aIn;
AnimationUtils::LoadAnimation(IContext::Probe(mActivity), R::anim::fade_out, (IAnimation**)&aOut);
AnimationUtils::LoadAnimation(IContext::Probe(mActivity), R::anim::fade_in, (IAnimation**)&aIn);
mProgressContainer->StartAnimation(aOut);
mListContainer->StartAnimation(aIn);
}
else {
mProgressContainer->ClearAnimation();
mListContainer->ClearAnimation();
}
mProgressContainer->SetVisibility(IView::GONE);
mListContainer->SetVisibility(IView::VISIBLE);
}
else {
if (animate) {
AutoPtr<IAnimation> aOut, aIn;
AnimationUtils::LoadAnimation(IContext::Probe(mActivity), R::anim::fade_out, (IAnimation**)&aOut);
AnimationUtils::LoadAnimation(IContext::Probe(mActivity), R::anim::fade_in, (IAnimation**)&aIn);
mProgressContainer->StartAnimation(aIn);
mListContainer->StartAnimation(aOut);
}
else {
mProgressContainer->ClearAnimation();
mListContainer->ClearAnimation();
}
mProgressContainer->SetVisibility(IView::VISIBLE);
mListContainer->SetVisibility(IView::GONE);
}
return NOERROR;
}
ECode ListFragment::GetListAdapter(
/* [out] */ IListAdapter** listadapter)
{
VALIDATE_NOT_NULL(listadapter);
*listadapter = mAdapter;
REFCOUNT_ADD(*listadapter);
return NOERROR;
}
ECode ListFragment::EnsureList()
{
if (mList != NULL) {
return NOERROR;
}
AutoPtr<IView> root;
GetView((IView**)&root);
if (root == NULL) {
// throw new IllegalStateException("Content view not yet created");
Slogger::E("ListFragment", "Content view not yet created");
return E_ILLEGAL_STATE_EXCEPTION;
}
IListView* listView = IListView::Probe(root);
if (listView) {
mList = listView;
}
else {
AutoPtr<IView> view;
root->FindViewById(R::id::internalEmpty, (IView**)&view);
mStandardEmptyView = ITextView::Probe(view);
if (mStandardEmptyView == NULL) {
mEmptyView = NULL;
root->FindViewById(R::id::empty, (IView**)&mEmptyView);
}
else {
IView::Probe(mStandardEmptyView)->SetVisibility(IView::GONE);
}
mProgressContainer = NULL;
mListContainer = NULL;
root->FindViewById(R::id::progressContainer, (IView**)&mProgressContainer);
root->FindViewById(R::id::listContainer, (IView**)&mListContainer);
AutoPtr<IView> rawListView;
root->FindViewById(R::id::list, (IView**)&rawListView);
if (IListView::Probe(rawListView) == NULL) {
// throw new RuntimeException(
// "Content has view with id attribute 'android.R.id.list' "
// + "that is not a ListView class");
Slogger::E("ListFragment", "Content has view with id attribute 'android.R.id.list' that is not a ListView class");
return E_ILLEGAL_STATE_EXCEPTION;
}
mList = IListView::Probe(rawListView);
if (mList == NULL) {
// throw new RuntimeException(
// "Your content must have a ListView whose id attribute is " +
// "'android.R.id.list'");
Slogger::E("ListFragment", "Your content must have a ListView whose id attribute is 'android.R.id.list'");
return E_ILLEGAL_STATE_EXCEPTION;
}
if (mEmptyView != NULL) {
IAdapterView::Probe(mList)->SetEmptyView(mEmptyView);
}
else if (mEmptyText != NULL) {
mStandardEmptyView->SetText(mEmptyText);
IAdapterView::Probe(mList)->SetEmptyView(IView::Probe(mStandardEmptyView));
}
}
mListShown = TRUE;
IAdapterView::Probe(mList)->SetOnItemClickListener(mOnClickListener);
if (mAdapter != NULL) {
AutoPtr<IListAdapter> adapter = mAdapter;
mAdapter = NULL;
SetListAdapter(adapter);
} else {
// We are starting without an adapter, so assume we won't
// have our data right away and start with the progress indicator.
if (mProgressContainer != NULL) {
FAIL_RETURN(SetListShown(FALSE, FALSE))
}
}
Boolean result;
mHandler->Post(mRequestFocus.Get(), &result);
return NOERROR;
}
} //namespace App
} //namespace Droid
} //namespace Elastos
| 30.997118 | 126 | 0.637598 | [
"object"
] |
23d69d91bc6681d15ab3f5398b857e373cbc18b6 | 1,727 | cpp | C++ | src/sconelib/sconelua/lua_script.cpp | alexxlzhou/scone-core | 4a071626e5ee7ba253e72a973d4d214fa6e30cf5 | [
"Apache-2.0"
] | 5 | 2021-04-30T14:30:20.000Z | 2022-03-27T09:58:24.000Z | src/sconelib/sconelua/lua_script.cpp | alexxlzhou/scone-core | 4a071626e5ee7ba253e72a973d4d214fa6e30cf5 | [
"Apache-2.0"
] | 4 | 2021-06-15T10:52:10.000Z | 2021-12-15T10:25:21.000Z | src/sconelib/sconelua/lua_script.cpp | alexxlzhou/scone-core | 4a071626e5ee7ba253e72a973d4d214fa6e30cf5 | [
"Apache-2.0"
] | 2 | 2021-05-02T13:38:19.000Z | 2021-07-22T19:37:07.000Z | #include "lua_script.h"
#include "xo/container/prop_node_tools.h"
#include "scone/core/Log.h"
#include "scone/model/Actuator.h"
#include "lua_api.h"
namespace scone
{
lua_script::lua_script( const path& script_file, const PropNode& pn, Params& par, Model& model ) :
script_file_( script_file )
{
lua_.open_libraries( sol::lib::base, sol::lib::math, sol::lib::package, sol::lib::string );
register_lua_wrappers( lua_ );
// find script file (folder can be different if playback)
auto folder = script_file_.has_parent_path() ? script_file_.parent_path() : path( "." );
// set path for lua modules to current script file folder
// #todo: add these modules to external resources too!
lua_[ "package" ][ "path" ] = ( folder / "?.lua" ).c_str();
// propagate all properties to scone namespace in lua script
for ( auto& prop : pn )
lua_[ "scone" ][ prop.first ] = prop.second.get<string>();
// load script
auto script = lua_.load_file( script_file_.str() );
if ( !script.valid() )
{
sol::error err = script;
SCONE_ERROR( "Error in " + script_file_.filename().str() + ": " + err.what() );
}
// run once to define functions
auto res = script();
if ( !res.valid() )
{
sol::error err = res;
SCONE_ERROR( "Error in " + script_file_.filename().str() + ": " + err.what() );
}
}
lua_script::~lua_script()
{}
sol::function lua_script::find_function( const String& name )
{
sol::function f = lua_[ name ];
SCONE_ERROR_IF( !f.valid(), "Error in " + script_file_.filename().str() + ": Could not find function " + xo::quoted( name ) );
return f;
}
sol::function lua_script::try_find_function( const String& name )
{
sol::function f = lua_[ name ];
return f;
}
}
| 28.783333 | 128 | 0.652577 | [
"model"
] |
23da0e9e33de14bbbab4e9979d7674db957354e1 | 1,416 | cpp | C++ | src/demo/vis_map_demo.cpp | jfangwpi/Interactive_planning_and_sensing | 00042c51c2fdc020b7b1c184286cf2b513ed9096 | [
"MIT"
] | null | null | null | src/demo/vis_map_demo.cpp | jfangwpi/Interactive_planning_and_sensing | 00042c51c2fdc020b7b1c184286cf2b513ed9096 | [
"MIT"
] | null | null | null | src/demo/vis_map_demo.cpp | jfangwpi/Interactive_planning_and_sensing | 00042c51c2fdc020b7b1c184286cf2b513ed9096 | [
"MIT"
] | null | null | null | /*
* task_map.cpp
*
* Created on: Feb 15, 2017
* Author: jfang
*/
/*** Read the map.ini and create the map ***/
// standard libaray
#include <stdio.h>
#include <vector>
#include <ctime>
#include <tuple>
#include <algorithm>
#include <bitset>
// opencv
#include "opencv2/opencv.hpp"
// self-defined library
#include "graph/graph.hpp"
#include "graph/algorithms/astar.hpp"
#include "map/square_grid.hpp"
#include "vis/graph_vis.hpp"
using namespace cv;
using namespace librav;
int main(int argc, char** argv )
{
/************************************************************************************************************/
/********************************* Initialize: Map *****************************************/
/************************************************************************************************************/
/*** 1. Create a empty square grid ***/
std::shared_ptr<SquareGrid> grid = GridGraph::CreateSquareGrid();
/*** 5. Construct a graph from the square grid ***/
std::shared_ptr<Graph_t<SquareCell *>> grid_graph = GridGraph::BuildGraphFromSquareGrid(grid,false, false);
/*** 9.Visualize the map and graph ***/
// Image Layouts: square grid -> graph -> path
GraphVis vis;
Mat vis_img;
vis.VisSquareGrid(*grid, vis_img);
vis.VisSquareGridGraph(*grid_graph, vis_img, vis_img, true);
imwrite("result_map.jpg",vis_img);
waitKey(0);
return 0;
} | 27.764706 | 111 | 0.540254 | [
"vector"
] |
23e2fb99c07e7d36c16cf8ae909ca9eb5503dc20 | 617 | hpp | C++ | cpp/include/ste_bits/Radiation.hpp | tomerten/steibs | 8d4e994020dd17475ba1371e9c6f365c916828a0 | [
"MIT"
] | null | null | null | cpp/include/ste_bits/Radiation.hpp | tomerten/steibs | 8d4e994020dd17475ba1371e9c6f365c916828a0 | [
"MIT"
] | null | null | null | cpp/include/ste_bits/Radiation.hpp | tomerten/steibs | 8d4e994020dd17475ba1371e9c6f365c916828a0 | [
"MIT"
] | null | null | null | #ifndef RADIATION_H
#define RADIATION_H
// #include <CL/cl.h>
#include <map>
#include <string>
#include <vector>
namespace ste_radiation {
std::map<std::string, double>
radiationIntegrals(std::map<std::string, std::vector<double>> &twiss);
std::map<std::string, double>
radiationEquilib(std::map<std::string, double> &twiss);
double RadiationLossesPerTurn(std::map<std::string, double> &twiss);
void RadUpdate(std::vector<std::vector<double>> &distribution,
std::map<std::string, double> &tw,
std::map<std::string, double> &radparam, int &seed);
} // namespace ste_radiation
#endif
| 26.826087 | 70 | 0.696921 | [
"vector"
] |
23e5e556e085a271a6fdd5d14bf3b9dc88af12df | 1,703 | cpp | C++ | OnlineJudge/LeetCode/Easy/35.search-insert-position.cpp | yangfly/Interview-Notes | db9214456db8833c0a618b44bbb1c4f8d5b3209e | [
"MIT"
] | 3 | 2019-02-19T07:23:30.000Z | 2020-05-11T03:16:57.000Z | OnlineJudge/LeetCode/Easy/35.search-insert-position.cpp | yangfly/Interview-Notes | db9214456db8833c0a618b44bbb1c4f8d5b3209e | [
"MIT"
] | null | null | null | OnlineJudge/LeetCode/Easy/35.search-insert-position.cpp | yangfly/Interview-Notes | db9214456db8833c0a618b44bbb1c4f8d5b3209e | [
"MIT"
] | 2 | 2019-02-19T07:23:33.000Z | 2020-04-20T16:44:04.000Z | /*
* [35] Search Insert Position
*
* https://leetcode.com/problems/search-insert-position/description/
*
* algorithms
* Easy (40.04%)
* Total Accepted: 240.1K
* Total Submissions: 599.6K
* Testcase Example: '[1,3,5,6]\n5'
*
* Given a sorted array and a target value, return the index if the target is
* found. If not, return the index where it would be if it were inserted in
* order.
*
* You may assume no duplicates in the array.
*
* Example 1:
*
* Input: [1,3,5,6], 5
* Output: 2
*
*
*
* Example 2:
*
* Input: [1,3,5,6], 2
* Output: 1
*
*
*
* Example 3:
*
* Input: [1,3,5,6], 7
* Output: 4
*
*
*
* Example 1:
*
* Input: [1,3,5,6], 0
* Output: 0
*
*
*/
#include "common.h"
// My Solution 244ms
// 遍历查找 O(n)
class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
for (std::size_t i = 0; i < nums.size(); i++) {
if (target <= nums[i]) {
return i;
}
}
return nums.size();
}
};
// Quickest Solution 3ms
// 二分查找 O(logn)
static const auto __________ = []()
{
ios::sync_with_stdio(false);
cin.tie(nullptr);
return nullptr;
}();
class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
if (nums.size() == 0) return 0;
int lo = 0;
int hi = nums.size() - 1;
while (lo < hi) {
int mid = (lo + hi) / 2;
if (target == nums[mid]) return mid;
if (target < nums[mid]) {
hi = mid - 1;
} else {
lo = mid +1;
}
}
if (nums[lo] >= target) return lo;
else return lo + 1;
}
};
| 18.922222 | 77 | 0.50734 | [
"vector"
] |
23eeeac0a66379e9de97edc13f1d36d2aafb99a6 | 626 | hpp | C++ | AAFInformer/StringUtils.hpp | clayne/AAFInformer | 933945b933a61c4fc2cd8ce1d11668f619a5aa89 | [
"MIT"
] | 3 | 2021-12-19T18:20:47.000Z | 2022-01-16T01:16:31.000Z | AAFInformer/StringUtils.hpp | clayne/AAFInformer | 933945b933a61c4fc2cd8ce1d11668f619a5aa89 | [
"MIT"
] | null | null | null | AAFInformer/StringUtils.hpp | clayne/AAFInformer | 933945b933a61c4fc2cd8ce1d11668f619a5aa89 | [
"MIT"
] | 1 | 2021-12-19T18:20:49.000Z | 2021-12-19T18:20:49.000Z | #pragma once
#include <cctype>
#include <algorithm>
struct SU
{
static std::string ToUpper(const std::string& s)
{
// All tags are in ASCII, so we don't care about locale during case conversion
std::string copy = s;
std::transform(copy.begin(), copy.end(), copy.begin(), [](unsigned char c) { return std::toupper(c); });
return copy;
}
static std::string ToUpper(const char* s)
{
// All tags are in ASCII, so we don't care about locale during case conversion
std::string copy = s;
std::transform(copy.begin(), copy.end(), copy.begin(), [](unsigned char c) { return std::toupper(c); });
return copy;
}
}; | 29.809524 | 106 | 0.667732 | [
"transform"
] |
23f186c1344665ace40ee992202a9ade6206b773 | 4,135 | hpp | C++ | source/entity/entity_define.hpp | Paul-Wortmann/Grume | 0ffdd8f98e0b7d7857cc6a3e0f971f9a74651d17 | [
"Intel"
] | 3 | 2021-12-19T12:00:34.000Z | 2021-12-30T08:36:58.000Z | source/entity/entity_define.hpp | Paul-Wortmann/Grume | 0ffdd8f98e0b7d7857cc6a3e0f971f9a74651d17 | [
"Intel"
] | 2 | 2021-11-02T05:30:53.000Z | 2021-11-30T00:11:16.000Z | source/entity/entity_define.hpp | Paul-Wortmann/Grume | 0ffdd8f98e0b7d7857cc6a3e0f971f9a74651d17 | [
"Intel"
] | null | null | null | /**
* Copyright (C) Paul Wortmann
* This file is part of "Grume"
*
* "Grume" is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 2 only.
*
* "Grume" is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with "Grume" If not, see <http://www.gnu.org/licenses/>.
*
* @author Paul Wortmann
* @email physhex@gmail.com
* @website www.physhexgames.com
* @license GPL V2
* @date 2011-11-11
*/
#ifndef ENTITY_HPP
#define ENTITY_HPP
#include "../core/includes.hpp"
#include "entity_ai.hpp"
#include "entity_character.hpp"
#include "entity_collision.hpp"
#include "entity_interaction.hpp"
#include "entity_material.hpp"
#include "entity_model.hpp"
#include "entity_movement.hpp"
#include "entity_physics.hpp"
#include "entity_state.hpp"
enum eEntityOwner: uint16
{
ownerNone = 0,
ownerUI = 1,
ownerMap = 2
};
enum eEntityType: uint16
{
entityTypeOther = 0,
entityTypeStatic = 1,
entityTypeObject = 2,
entityTypeNPCmob = 3,
entityTypeNPC = 4,
entityTypeWall = 5,
entityTypeFloor = 6
};
struct sEntity
{
// Linked list
sEntity* next = nullptr;
uint32 UID = 0;
// Infomation
std::string name = "";
bool enabled = true;
eEntityType type = eEntityType::entityTypeStatic;
eEntityOwner owner = eEntityOwner::ownerNone;
uint32 tile = 0; // Current tile
// Base
glm::vec3 position = glm::vec3(0.0f, 0.0f, 0.0f);
glm::vec3 scale = glm::vec3(1.0f, 1.0f, 1.0f);
glm::vec3 rotation = glm::vec3(0.0f, 0.0f, 0.0f);
glm::vec3 rotationOffset = glm::vec3(0.0f, 0.0f, 0.0f);
glm::ivec3 rotationAxis = glm::ivec3(0, 1, 0);
// Animation (per entity, not shared)
bool animationIndependent = false;
uint32 numBones = 0;
glm::mat4* boneTransform = nullptr;
uint32 currentAnimation = 0;
float64 previousAnimTime = 0.0;
float64 currentAnimTime = 0.0;
float64 stopAnimTime = 0.0;
float64 startAnimTime = 0.0;
bool repeatAnimation = false;
bool finishedAnimation = true;
// Graphics
sEntityModel* model = nullptr; // (Entity shared animation data)
glm::mat4 modelMatrix = glm::mat4(1);
sEntityMaterial* material = nullptr;
// Collision
sEntityCollision* collision = nullptr;
// State
uint32 stateCount = 0;
uint32 stateInitial = 0;
uint32 stateCurrent = 0;
sEntityState* state = nullptr;
bool terminate = false;
// AI
sEntityAI* ai = nullptr;
// Character - player
sEntityCharacter* character = nullptr;
// Interaction
sEntityInteraction* interaction = nullptr;
uint32 triggerTile = 0; // Trigger tile on interaction, 0 for none
// Pathing
sEntityMovement* movement = nullptr;
// Physics
sEntityPhysics* physics = nullptr;
// Screen shake on death
uint32 deathShakeChance = 100;
uint32 deathShakeDuration = 2000;
float32 deathShakeForce = 0.5f;
};
#endif //ENTITY_HPP
| 32.304688 | 92 | 0.538331 | [
"model"
] |
23f9d15a694bd6cb69c4f0782bc4514627bef431 | 4,295 | hpp | C++ | demo_cpu/frame.hpp | tobguent/small-mcftle | 834e24845ddc874807e681c8630f9750935df917 | [
"MIT"
] | 9 | 2016-06-29T12:31:35.000Z | 2022-03-02T23:43:29.000Z | demo_cpu/frame.hpp | tobguent/small-mcftle | 834e24845ddc874807e681c8630f9750935df917 | [
"MIT"
] | null | null | null | demo_cpu/frame.hpp | tobguent/small-mcftle | 834e24845ddc874807e681c8630f9750935df917 | [
"MIT"
] | 5 | 2016-11-29T21:51:00.000Z | 2020-10-08T11:58:27.000Z | #pragma once
#ifndef _FRAME_INCLUDE_ONCE
#define _FRAME_INCLUDE_ONCE
#include "math.hpp"
#include <vector>
#include <fstream>
class Frame
{
public:
// Constructor. Reserves the memory for the frame.
Frame(const Vec2i& screenResolution) : _ScreenResolution(screenResolution)
{
_AccumColor.resize(screenResolution.x*screenResolution.y, Vec3d(0,0,0));
_AccumCount.resize(screenResolution.x*screenResolution.y, 0);
}
// Adds a pixel measurement to the statistics.
void AddPixel(const Vec2i& pxCoord, const Vec3d& color)
{
int linearIndex = pxCoord.y * _ScreenResolution.x + pxCoord.x;
_AccumColor[linearIndex] += color;
_AccumCount[linearIndex] += 1;
}
// Exports the current frame to a pfm file.
void ExportPfm(const char *filename)
{
// create and replace the file
std::ofstream headerWriter(filename);
if (headerWriter.is_open())
{
// write the header
headerWriter << "PF" << std::endl;
headerWriter << _ScreenResolution.x << " " << _ScreenResolution.y << std::endl;
headerWriter.close();
}
// open the file in binary mode
std::ofstream rawWriter(filename, std::ios::binary | std::ios::app);
std::vector<float> data(_ScreenResolution.x * _ScreenResolution.y * 3);
for (int i = 0; i < _ScreenResolution.x * _ScreenResolution.y; ++i) {
Vec3d color = _AccumCount[i] == 0 ? Vec3d(1,1,1) : _AccumColor[i] / _AccumCount[i];
data[3*i+0] = (float)color.x();
data[3*i+1] = (float)color.y();
data[3*i+2] = (float)color.z();
}
// write the image line by line (reverse order)
int lSize = _ScreenResolution.x*sizeof(float)*3;
//for (int y = _ScreenResolution.y - 1; y >= 0; y--)
for (int y = 0; y < _ScreenResolution.y; ++y)
rawWriter.write((char*)data.data() + lSize*y, lSize);
rawWriter.close();
}
// Exports the current frame to a bmp file.
void ExportBmp(const char* filename, double contrast, double brightness, double gamma)
{
unsigned char file[14] = {
'B','M', // magic
0,0,0,0, // size in bytes
0,0, // app data
0,0, // app data
40+14,0,0,0 // start of data offset
};
unsigned char info[40] = {
40,0,0,0, // info hd size
0,0,0,0, // width
0,0,0,0, // heigth
1,0, // number color planes
24,0, // bits per pixel
0,0,0,0, // compression is none
0,0,0,0, // image bits size
0x13,0x0B,0,0, // horz resoluition in pixel / m
0x13,0x0B,0,0, // vert resolutions (0x03C3 = 96 dpi, 0x0B13 = 72 dpi)
0,0,0,0, // #colors in pallete
0,0,0,0, // #important colors
};
int w=_ScreenResolution.x;
int h=_ScreenResolution.y;
int padSize = (4-(w*3)%4)%4;
int sizeData = w*h*3 + h*padSize;
int sizeAll = sizeData + sizeof(file) + sizeof(info);
file[ 2] = (unsigned char)( sizeAll );
file[ 3] = (unsigned char)( sizeAll>> 8);
file[ 4] = (unsigned char)( sizeAll>>16);
file[ 5] = (unsigned char)( sizeAll>>24);
info[ 4] = (unsigned char)( w );
info[ 5] = (unsigned char)( w>> 8);
info[ 6] = (unsigned char)( w>>16);
info[ 7] = (unsigned char)( w>>24);
info[ 8] = (unsigned char)( h );
info[ 9] = (unsigned char)( h>> 8);
info[10] = (unsigned char)( h>>16);
info[11] = (unsigned char)( h>>24);
info[20] = (unsigned char)( sizeData );
info[21] = (unsigned char)( sizeData>> 8);
info[22] = (unsigned char)( sizeData>>16);
info[23] = (unsigned char)( sizeData>>24);
std::ofstream stream(filename, std::ios::binary | std::ios::out);
stream.write( (char*)file, sizeof(file) );
stream.write( (char*)info, sizeof(info) );
unsigned char pad[3] = {0,0,0};
for ( int y=0; y<h; y++ )
{
for ( int x=0; x<w; x++ )
{
Vec3d color = _AccumCount[y*w+x] == 0 ? Vec3d(1,1,1) : _AccumColor[y*w+x] / _AccumCount[y*w+x];
color = pow(max(0.f,(color-0.5)*contrast+0.5+brightness), 1.0/gamma);
unsigned char pixel[3];
pixel[0] = (unsigned char)(std::min(std::max(0.f, (float)color.z()), 1.f)*255);
pixel[1] = (unsigned char)(std::min(std::max(0.f, (float)color.y()), 1.f)*255);
pixel[2] = (unsigned char)(std::min(std::max(0.f, (float)color.x()), 1.f)*255);
stream.write( (char*)pixel, 3 );
}
stream.write( (char*)pad, padSize );
}
}
private:
std::vector<Vec3d> _AccumColor;
std::vector<double> _AccumCount;
Vec2i _ScreenResolution; // resolution of the viewport
};
#endif | 30.460993 | 99 | 0.627939 | [
"vector"
] |
6728e93e8f7c369e99d399b31b9a809e24d50c72 | 3,168 | hpp | C++ | include/codegen/include/UnityEngine/Events/InvokableCallList.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | 1 | 2021-11-12T09:29:31.000Z | 2021-11-12T09:29:31.000Z | include/codegen/include/UnityEngine/Events/InvokableCallList.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | null | null | null | include/codegen/include/UnityEngine/Events/InvokableCallList.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | 2 | 2021-10-03T02:14:20.000Z | 2021-11-12T09:29:36.000Z | // Autogenerated from CppHeaderCreator on 7/27/2020 3:10:30 PM
// Created by Sc2ad
// =========================================================================
#pragma once
#pragma pack(push, 8)
// Begin includes
#include "utils/typedefs.h"
// Including type: System.Object
#include "System/Object.hpp"
#include "utils/il2cpp-utils.hpp"
// Completed includes
// Begin forward declares
// Forward declaring namespace: System::Collections::Generic
namespace System::Collections::Generic {
// Forward declaring type: List`1<T>
template<typename T>
class List_1;
}
// Forward declaring namespace: UnityEngine::Events
namespace UnityEngine::Events {
// Forward declaring type: BaseInvokableCall
class BaseInvokableCall;
}
// Forward declaring namespace: System::Reflection
namespace System::Reflection {
// Forward declaring type: MethodInfo
class MethodInfo;
}
// Completed forward declares
// Type namespace: UnityEngine.Events
namespace UnityEngine::Events {
// Autogenerated type: UnityEngine.Events.InvokableCallList
class InvokableCallList : public ::Il2CppObject {
public:
// private readonly System.Collections.Generic.List`1<UnityEngine.Events.BaseInvokableCall> m_PersistentCalls
// Offset: 0x10
System::Collections::Generic::List_1<UnityEngine::Events::BaseInvokableCall*>* m_PersistentCalls;
// private readonly System.Collections.Generic.List`1<UnityEngine.Events.BaseInvokableCall> m_RuntimeCalls
// Offset: 0x18
System::Collections::Generic::List_1<UnityEngine::Events::BaseInvokableCall*>* m_RuntimeCalls;
// private readonly System.Collections.Generic.List`1<UnityEngine.Events.BaseInvokableCall> m_ExecutingCalls
// Offset: 0x20
System::Collections::Generic::List_1<UnityEngine::Events::BaseInvokableCall*>* m_ExecutingCalls;
// private System.Boolean m_NeedsUpdate
// Offset: 0x28
bool m_NeedsUpdate;
// public System.Void AddPersistentInvokableCall(UnityEngine.Events.BaseInvokableCall call)
// Offset: 0x12F35BC
void AddPersistentInvokableCall(UnityEngine::Events::BaseInvokableCall* call);
// public System.Void AddListener(UnityEngine.Events.BaseInvokableCall call)
// Offset: 0x12F3630
void AddListener(UnityEngine::Events::BaseInvokableCall* call);
// public System.Void RemoveListener(System.Object targetObj, System.Reflection.MethodInfo method)
// Offset: 0x12F36A4
void RemoveListener(::Il2CppObject* targetObj, System::Reflection::MethodInfo* method);
// public System.Void ClearPersistent()
// Offset: 0x12F381C
void ClearPersistent();
// public System.Collections.Generic.List`1<UnityEngine.Events.BaseInvokableCall> PrepareInvoke()
// Offset: 0x12F3880
System::Collections::Generic::List_1<UnityEngine::Events::BaseInvokableCall*>* PrepareInvoke();
// public System.Void .ctor()
// Offset: 0x12F391C
// Implemented from: System.Object
// Base method: System.Void Object::.ctor()
static InvokableCallList* New_ctor();
}; // UnityEngine.Events.InvokableCallList
}
DEFINE_IL2CPP_ARG_TYPE(UnityEngine::Events::InvokableCallList*, "UnityEngine.Events", "InvokableCallList");
#pragma pack(pop)
| 44.619718 | 113 | 0.744003 | [
"object"
] |
67301012212b6becb2241849ee6c3603207d17f2 | 602 | cc | C++ | 6_STLContainerUndIteratoren/Iterator2.cc | j3l4ck0ut/UdemyCpp | ed3b75cedbf9cad211a205195605cfd3c9280efc | [
"MIT"
] | null | null | null | 6_STLContainerUndIteratoren/Iterator2.cc | j3l4ck0ut/UdemyCpp | ed3b75cedbf9cad211a205195605cfd3c9280efc | [
"MIT"
] | null | null | null | 6_STLContainerUndIteratoren/Iterator2.cc | j3l4ck0ut/UdemyCpp | ed3b75cedbf9cad211a205195605cfd3c9280efc | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
#include <numeric>
#include <iterator>
#include <list>
int main()
{
std::vector<int> my_vector(5, 0);
std::iota(my_vector.begin(), my_vector.end(), 5);
std::list<int> my_list(my_vector.begin(), my_vector.end());
auto it = my_list.begin();
std::advance(it, 2);
// 5, 6, 7, 8, 9
std::cout << my_vector[2] << std::endl; // 7
std::cout << *it << std::endl; // 7
std::cout << std::distance(it, my_list.end()) << std::endl; // 3
std::cout << *std::prev(it) << std::endl; // 6
std::cout << *std::next(it) << std::endl; // 8
return 0;
} | 25.083333 | 65 | 0.574751 | [
"vector"
] |
6734c01961928f595b16fa2fae408702ee5c058e | 4,067 | cpp | C++ | oadrive/src/oadrive_missioncontrol/ManeuverListLive.cpp | fzi-forschungszentrum-informatik/aadc2016 | b00149f84f91be07d98f3be0ac79daebb732025b | [
"BSD-2-Clause"
] | 11 | 2016-04-30T14:55:20.000Z | 2020-06-04T21:13:31.000Z | oadrive/src/oadrive_missioncontrol/ManeuverListLive.cpp | fzi-forschungszentrum-informatik/aadc2016 | b00149f84f91be07d98f3be0ac79daebb732025b | [
"BSD-2-Clause"
] | null | null | null | oadrive/src/oadrive_missioncontrol/ManeuverListLive.cpp | fzi-forschungszentrum-informatik/aadc2016 | b00149f84f91be07d98f3be0ac79daebb732025b | [
"BSD-2-Clause"
] | 8 | 2016-04-30T14:58:18.000Z | 2019-12-27T10:37:53.000Z | // this is for emacs file handling -*- mode: c++; indent-tabs-mode: nil -*-
// -- BEGIN LICENSE BLOCK ----------------------------------------------
// Copyright (c) 2016, FZI Forschungszentrum Informatik
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// -- END LICENSE BLOCK ------------------------------------------------
//----------------------------------------------------------------------
/*!\file
*
* \author Vitali Kaiser <vitali.kaiser@live.de>
* \date 2016-02-27
*
*/
//----------------------------------------------------------------------
#include "ManeuverListLive.h"
#include <string>
#include <iostream>
#include <oadrive_util/Broker.h>
//next 3 lines are for logging
#include "oadrive_missioncontrol/mcLogging.h"
using icl_core::logging::endl;
using icl_core::logging::flush;
using namespace oadrive::util;
namespace oadrive
{
namespace missioncontrol
{
using namespace boost::assign;
static const std::string channelName = "oadrive/manlist";
map<string, enumManeuver> ManeuverListLive::maneuverMap = map_list_of ("left", MANEUVER_LEFT) ("right", MANEUVER_RIGHT) ("straight", MANEUVER_STRAIGHT) ("parallel_parking", MANEUVER_PARKING_PARALLEL) ("cross_parking", MANEUVER_PARKING_CROSS) ("pull_out_left", MANEUVER_PULLOUT_LEFT) ("pull_out_right", MANEUVER_PULLOUT_RIGHT);
ManeuverListLive::ManeuverListLive ()
{
m_currentMan = MANEUVER_RIGHT;
m_prevMan = MANEUVER_RIGHT;
m_manID = 0;
m_isFin = false;
mc = 0;
LOGGING_INFO( mcLogger, "ManeuverListLive constructed." << endl );
// Initialize the broker:
Broker::getInstance();
}
void ManeuverListLive::onMessage(const std::vector<char> &buf) {
std::string msg(buf.begin(), buf.end());
}
void ManeuverListLive::increase() {
m_manID++;
}
std::string ManeuverListLive::toString() {
return "";
}
unsigned int ManeuverListLive::getCurrentAbsManeuverID() {
return m_manID;
}
enumManeuver ManeuverListLive::getCurrentManeuver() {
// When asked for a new manevuer, simply retrieve the last received maneuver:
m_currentMan = Broker::getInstance()->getLastReceivedManeuver();
LOGGING_INFO( mcLogger, "Current maneuver in ManeuverListLive: " << m_currentMan << endl );
return m_currentMan;
}
enumManeuver ManeuverListLive::getPreviosManeuver() {
return m_prevMan;
}
bool ManeuverListLive::isFinished() {
return m_isFin;
}
bool ManeuverListLive::setManeuverId(int maneuverEntryID) {
//ignore that... we dont have ids.....
return true;
}
bool ManeuverListLive::isDummy() {
// we are the real thing ;)
return false;
}
} /* namespace missioncontrol */
} /* namespace oadrive */
| 35.365217 | 330 | 0.669781 | [
"vector"
] |
67493c99a76face94f979469956a3e4698cc8bf5 | 1,513 | cpp | C++ | Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/internal/telephony/CSmsHeaderHelper.cpp | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | 7 | 2017-07-13T10:34:54.000Z | 2021-04-16T05:40:35.000Z | Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/internal/telephony/CSmsHeaderHelper.cpp | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | null | null | null | Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/internal/telephony/CSmsHeaderHelper.cpp | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | 9 | 2017-07-13T12:33:20.000Z | 2021-06-19T02:46:48.000Z | //=========================================================================
// Copyright (C) 2012 The Elastos Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//=========================================================================
#include "elastos/droid/internal/telephony/CSmsHeaderHelper.h"
#include "elastos/droid/internal/telephony/SmsHeader.h"
namespace Elastos {
namespace Droid {
namespace Internal {
namespace Telephony {
CAR_INTERFACE_IMPL(CSmsHeaderHelper, Object, ISmsHeaderHelper)
CAR_SINGLETON_IMPL(CSmsHeaderHelper)
ECode CSmsHeaderHelper::FromByteArray(
/* [in] */ ArrayOf<Byte>* data,
/* [out] */ ISmsHeader** result)
{
return SmsHeader::FromByteArray(data, result);
}
ECode CSmsHeaderHelper::ToByteArray(
/* [in] */ ISmsHeader* smsHeader,
/* [out, callee] */ ArrayOf<Byte>** result)
{
return SmsHeader::ToByteArray(smsHeader, result);
}
} // namespace Telephony
} // namespace Internal
} // namespace Droid
} // namespace Elastos
| 32.191489 | 75 | 0.663582 | [
"object"
] |
674c2b2a106bedb5f373badf692430f39abd101f | 894 | cpp | C++ | ch14/ex14_38.cpp | Direct-Leo/CppPrimer | 9d3993c7604377abc5a925c9fe6342ad3a062983 | [
"CC0-1.0"
] | null | null | null | ch14/ex14_38.cpp | Direct-Leo/CppPrimer | 9d3993c7604377abc5a925c9fe6342ad3a062983 | [
"CC0-1.0"
] | null | null | null | ch14/ex14_38.cpp | Direct-Leo/CppPrimer | 9d3993c7604377abc5a925c9fe6342ad3a062983 | [
"CC0-1.0"
] | null | null | null | /*******************************************************
* @file ex14_38.cpp
* @author vleo
* @date 2021.12.14
* @remark a string check Class
*******************************************************/
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
#include <fstream>
class StringNumCheck{
public:
StringNumCheck(size_t len = 0) : len(len) {}
bool operator()(const std::string& s)
{
return s.length() == len ;
}
private:
size_t len;
};
int main()
{
std::ifstream fin("../data/ex14_38.txt");
int count[11] = {0} ;
std::string word ;
while (fin >> word)
{
StringNumCheck test(word.length());
if(test(word))
++count[word.length()];
}
for(auto it = std::begin(count) + 1; it != std::end(count); ++it)
{
std::cout << *it << std::endl;
}
return 0;
} | 19.866667 | 69 | 0.479866 | [
"vector"
] |
67583e329b896d61dc9193ea65a4928809cc4613 | 5,241 | hpp | C++ | sqf-value/method.hpp | arma3/sqf-value | 2032dcbbb5acba45eff33ab6502922f3e191289d | [
"MIT"
] | 1 | 2021-01-05T13:30:06.000Z | 2021-01-05T13:30:06.000Z | sqf-value/method.hpp | arma3/sqf-value | 2032dcbbb5acba45eff33ab6502922f3e191289d | [
"MIT"
] | 3 | 2021-01-03T23:56:06.000Z | 2021-03-19T00:02:40.000Z | sqf-value/method.hpp | arma3/sqf-value | 2032dcbbb5acba45eff33ab6502922f3e191289d | [
"MIT"
] | 1 | 2021-01-03T21:07:30.000Z | 2021-01-03T21:07:30.000Z | #pragma once
#include "value.hpp"
#include <vector>
#include <optional>
#include <variant>
#include <functional>
namespace sqf
{
namespace meta
{
template <typename ArgType>
struct is_optional : std::false_type {};
template <typename T>
struct is_optional<std::optional<T>> : std::true_type {};
template <typename ArgType>
inline constexpr bool is_optional_v = is_optional<ArgType>::value;
template <typename ArgType>
struct def_value { static ArgType value() { return {}; } };
template <typename ArgType>
struct get_type { using type = ArgType; };
template <typename ArgType>
struct get_type<std::optional<ArgType>> { using type = ArgType; };
}
struct method {
public:
template<typename TPass, typename TErr>
class ret
{
std::optional<TPass> m_passed;
std::optional<TErr> m_error;
public:
ret(std::optional<TPass> p, std::optional<TErr> e) : m_passed(p), m_error(e) {}
ret(TPass p) : m_passed(p), m_error({}) {}
bool is_err() const { return m_error.has_value(); }
bool is_ok() const { return m_passed.has_value(); }
TErr get_err() const { return m_error.value(); }
TPass get_ok() const { return m_passed.value(); }
static ret err(TErr e) { return { {}, e }; }
static ret ok(TPass p) { return { p, {} }; }
};
private:
std::function<bool(const std::vector<value>&)> m_can_call;
std::function<ret<value, value>(const std::vector<value>&)> m_call;
template <typename ... Args, std::size_t... IndexSequence>
static bool can_call_impl(const std::vector<value>& values, std::index_sequence<IndexSequence...> s) {
// values max args
return values.size() <= sizeof...(Args) &&
// for every Arg, either...
(... && (
// the value provides that argument and its the correct type, or...
(IndexSequence < values.size() && sqf::is<sqf::meta::get_type<Args>::type>(values[IndexSequence])) ||
// the value does not provide that argument and the arg is an optional
(IndexSequence >= values.size() && sqf::meta::is_optional_v<Args>)
));
}
template <typename Ret, typename ... Args, std::size_t... IndexSequence>
static ret<value, value> call_impl_ok(std::function<Ret(Args...)> f, const std::vector<value>& values, std::index_sequence<IndexSequence...>) {
auto res = // call the function with every type in the value set,
// padding with empty std::optionals otherwise
std::invoke(f,
(IndexSequence < values.size() ? sqf::get<sqf::meta::get_type<Args>::type>(values[IndexSequence])
: sqf::meta::def_value<Args>::value())...);
return ret<value, value>::ok(res);
}
template <typename Ret, typename ... Args, std::size_t... IndexSequence>
static ret<value, value> call_impl(std::function<Ret(Args...)> f, const std::vector<value>& values, std::index_sequence<IndexSequence...>) {
auto res = // call the function with every type in the value set,
// padding with empty std::optionals otherwise
std::invoke(f,
(IndexSequence < values.size() ? sqf::get<sqf::meta::get_type<Args>::type>(values[IndexSequence])
: sqf::meta::def_value<Args>::value())...);
if (res.is_ok()) { return ret<value, value>::ok(res.get_ok()); }
return ret<value, value>::err(res.get_err());
}
public:
template <typename Ret, typename ... Args>
method(std::function<Ret(Args...)> f) :
m_can_call([](const std::vector<value>& values) -> bool
{
return can_call_impl<Args...>(values, std::index_sequence_for<Args...>{});
}),
m_call([f](const std::vector<value>& values) -> ret<value, value>
{
return call_impl_ok<Ret, Args...>(f, values, std::index_sequence_for<Args...>{});
})
{
}
template <typename RetOk, typename RetErr, typename ... Args>
method(std::function<ret<RetOk, RetErr>(Args...)> f) :
m_can_call([](const std::vector<value>& values) -> bool
{
return can_call_impl<Args...>(values, std::index_sequence_for<Args...>{});
}),
m_call([f](const std::vector<value>& values) -> ret<value, value>
{
return call_impl<ret<RetOk, RetErr>, Args...>(f, values, std::index_sequence_for<Args...>{});
})
{
}
bool can_call(const std::vector<value>& values) const { return m_can_call(values); }
ret<value, value> call_generic(const std::vector<value>& values) const { return m_call(values); }
// to handle lambda
template <typename F>
method static create(F f) { return method{ std::function{f} }; }
};
} | 44.794872 | 151 | 0.555047 | [
"vector"
] |
6760568c05f51b530c1a60933478113a5c89e709 | 3,879 | hh | C++ | tests/applications/QuickSilver/QuickSilver_orig_prof/src_mod/NuclearData.hh | rutgers-apl/omp-racer | a8a32e186950997b8eee7864f766819129a5ee06 | [
"BSD-2-Clause"
] | 2 | 2020-09-17T15:18:49.000Z | 2021-03-06T10:21:23.000Z | tests/applications/QuickSilver/QuickSilver_orig_prof/src/NuclearData.hh | rutgers-apl/omp-racer | a8a32e186950997b8eee7864f766819129a5ee06 | [
"BSD-2-Clause"
] | 1 | 2020-09-08T18:36:24.000Z | 2020-09-17T15:18:27.000Z | tests/applications/QuickSilver/QuickSilver_orig_ser/src/NuclearData.hh | rutgers-apl/omp-racer | a8a32e186950997b8eee7864f766819129a5ee06 | [
"BSD-2-Clause"
] | 1 | 2021-01-19T15:28:15.000Z | 2021-01-19T15:28:15.000Z | #ifndef NUCLEAR_DATA_HH
#define NUCLEAR_DATA_HH
#include <cstdio>
#include <string>
#include "QS_Vector.hh"
#include <cstdlib>
#include <cmath>
#include <algorithm>
#include "qs_assert.hh"
#include "DeclareMacro.hh"
class Polynomial
{
public:
Polynomial(double aa, double bb, double cc, double dd, double ee)
:
_aa(aa), _bb(bb), _cc(cc), _dd(dd), _ee(ee){}
double operator()(double xx) const
{
return _ee + xx * (_dd + xx * (_cc + xx * (_bb + xx * (_aa))));
}
private:
double _aa, _bb, _cc, _dd, _ee;
};
// Lowest level class at the reaction level
class NuclearDataReaction
{
public:
// The types of reactions
enum Enum
{
Undefined = 0,
Scatter,
Absorption,
Fission
};
NuclearDataReaction(){};
NuclearDataReaction(Enum reactionType, double nuBar, const qs_vector<double>& energies,
const Polynomial& polynomial, double reationCrossSection);
HOST_DEVICE_CUDA
double getCrossSection(unsigned int group);
HOST_DEVICE_CUDA
void sampleCollision(double incidentEnergy, double material_mass, double* energyOut,
double* angleOut, int &nOut, uint64_t* seed, int max_production_size);
qs_vector<double> _crossSection; //!< tabular data for microscopic cross section
Enum _reactionType; //!< What type of reaction is this
double _nuBar; //!< If this is a fission, specify the nu bar
};
// This class holds an array of reactions for neutrons
class NuclearDataSpecies
{
public:
void addReaction(NuclearDataReaction::Enum type, double nuBar, qs_vector<double>& energies,
const Polynomial& polynomial, double reactionCrossSection);
qs_vector<NuclearDataReaction> _reactions;
};
// For this isotope, store the cross sections. In this case the species is just neutron.
class NuclearDataIsotope
{
public:
NuclearDataIsotope()
: _species(1,VAR_MEM){}
qs_vector<NuclearDataSpecies> _species;
};
// Top level class to handle all things related to nuclear data
class NuclearData
{
public:
NuclearData(int numGroups, double energyLow, double energyHigh);
int addIsotope(int nReactions,
const Polynomial& fissionFunction,
const Polynomial& scatterFunction,
const Polynomial& absorptionFunction,
double nuBar,
double totalCrossSection,
double fissionWeight, double scatterWeight, double absorptionWeight);
HOST_DEVICE_CUDA
int getEnergyGroup(double energy);
HOST_DEVICE_CUDA
int getNumberReactions(unsigned int isotopeIndex);
HOST_DEVICE_CUDA
double getTotalCrossSection(unsigned int isotopeIndex, unsigned int group);
HOST_DEVICE_CUDA
double getReactionCrossSection(unsigned int reactIndex, unsigned int isotopeIndex, unsigned int group);
int _numEnergyGroups;
// Store the cross sections and reactions by isotope, which stores
// it by species
qs_vector<NuclearDataIsotope> _isotopes;
// This is the overall energy layout. If we had more than just
// neutrons, this array would be a vector of vectors.
qs_vector<double> _energies;
};
#endif
// The input for the nuclear data comes from the material section
// The input looks may like
//
// material NAME
// nIsotope=XXX
// nReactions=XXX
// fissionCrossSection="XXX"
// scatterCrossSection="XXX"
// absorptionCrossSection="XXX"
// nuBar=XXX
// totalCrossSection=XXX
// fissionWeight=XXX
// scatterWeight=XXX
// absorptionWeight=XXX
//
// Material NAME2
// ...
//
// table NAME
// a=XXX
// b=XXX
// c=XXX
// d=XXX
// e=XXX
//
// table NAME2
//
// Each isotope inside a material will have identical cross sections.
// However, it will be treated as unique in the nuclear data.
// Cross sectionsare strings that refer to tables
| 25.86 | 106 | 0.690642 | [
"vector"
] |
6763dc358f350d8fa5676e660cb6feeb72d89ffb | 625 | cc | C++ | c11/day04/1.1thread_adv.cc | hankai17/test | 8f38d999a7c6a92eac94b4d9dc8e444619d2144f | [
"MIT"
] | 7 | 2017-07-16T15:09:26.000Z | 2021-09-01T02:13:15.000Z | c11/day04/1.1thread_adv.cc | hankai17/test | 8f38d999a7c6a92eac94b4d9dc8e444619d2144f | [
"MIT"
] | null | null | null | c11/day04/1.1thread_adv.cc | hankai17/test | 8f38d999a7c6a92eac94b4d9dc8e444619d2144f | [
"MIT"
] | 3 | 2017-09-13T09:54:49.000Z | 2019-03-18T01:29:15.000Z | #include<thread>
#include<iostream>
#include<vector>
std::vector<std::thread> g_list;
std::vector<std::shared_ptr<std::thread>> g_list2;
void func() {
std::cout<<"this is func \n";
return;
}
void create_thread() {
std::thread t(func);
g_list.push_back(std::move(t)); //如果直接push一个左值线程对象 就会调拷贝构造 会多出一个线程 这不是我们想要的
//把这个左值变成右值直接push进去 c11的thread里面肯定有move语义
//thread拷贝构造函数(被禁用)
g_list2.push_back(std::make_shared<std::thread>(func)); //vector的push只会发生拷贝构造
}
int main()
{
create_thread();
for(auto& thread : g_list) {
thread.join();
}
for(auto& thread : g_list2) {
thread->join();
}
return 0;
}
| 18.382353 | 78 | 0.6848 | [
"vector"
] |
67716fcb61e6c2f66df2fb4cea2513aa1b60ab69 | 10,457 | cpp | C++ | tools/mull-xctestrun/XCTestRunInvocation.cpp | kateinoigakukun/mull-xctest | e7be5afa9afb64bef97dde29417c016af2a50dcc | [
"MIT"
] | 43 | 2021-03-04T04:57:41.000Z | 2022-03-03T17:16:54.000Z | tools/mull-xctestrun/XCTestRunInvocation.cpp | kateinoigakukun/mull-xctest | e7be5afa9afb64bef97dde29417c016af2a50dcc | [
"MIT"
] | 2 | 2021-03-09T10:32:29.000Z | 2021-10-19T12:01:25.000Z | tools/mull-xctestrun/XCTestRunInvocation.cpp | kateinoigakukun/mull-xctest | e7be5afa9afb64bef97dde29417c016af2a50dcc | [
"MIT"
] | 1 | 2021-03-09T14:29:17.000Z | 2021-03-09T14:29:17.000Z | #include "XCTestRunInvocation.h"
#include "MullXCTest/MutantSerialization.h"
#include "MullXCTest/XCResultFile.h"
#include "MullXCTest/XCTestRunFile.h"
#include <llvm/Object/Binary.h>
#include <llvm/Object/MachO.h>
#include <llvm/Support/FileSystem.h>
#include <llvm/Support/Path.h>
#include <mull/MutationResult.h>
#include <mull/Parallelization/Parallelization.h>
#include <mull/Toolchain/Runner.h>
#include <reproc++/reproc.hpp>
#include <set>
#include <sstream>
using namespace llvm;
using namespace mull;
namespace mull_xctest {
namespace {
std::string GetBundleBinaryPath(std::string &bundlePath) {
llvm::SmallString<128> binaryPath(bundlePath);
auto filename = llvm::sys::path::filename(bundlePath);
auto basename = filename.rsplit(".").first;
llvm::sys::path::append(binaryPath, basename);
return binaryPath.str().str();
}
ExecutionResult RunProgram(Diagnostics &diagnostics, const std::string &program,
const std::vector<std::string> &arguments,
const std::vector<std::string> &environment,
long long int timeout, const std::string &logPath) {
using namespace std::string_literals;
std::vector<std::pair<std::string, std::string>> env;
env.reserve(environment.size());
for (auto &e : environment) {
env.emplace_back(e, "1");
}
reproc::options options;
options.env.extra = reproc::env(env);
if (!logPath.empty()) {
options.redirect.path = logPath.c_str();
} else {
options.redirect.err.type = reproc::redirect::type::pipe;
}
std::vector<std::string> allArguments{program};
std::copy(std::begin(arguments), std::end(arguments),
std::back_inserter(allArguments));
auto start = std::chrono::high_resolution_clock::now();
reproc::process process;
std::error_code ec = process.start(allArguments, options);
if (ec) {
std::stringstream errorMessage;
errorMessage << "Cannot run executable: " << ec.message() << '\n';
diagnostics.error(errorMessage.str());
}
int status;
std::tie(status, ec) = process.wait(reproc::milliseconds(timeout));
ExecutionStatus executionStatus = Failed;
if (ec == std::errc::timed_out) {
process.kill();
executionStatus = Timedout;
} else if (status == 0) {
executionStatus = Passed;
} else {
executionStatus = Failed;
}
auto elapsed = std::chrono::high_resolution_clock::now() - start;
ExecutionResult result;
result.runningTime =
std::chrono::duration_cast<std::chrono::milliseconds>(elapsed).count();
result.exitStatus = status;
result.status = executionStatus;
return result;
}
ExecutionResult
RunXcodeBuildTest(Diagnostics &diagnostics, const std::string &xctestrunFile,
const llvm::Optional<std::string> &resultBundlePath,
const std::vector<std::string> &extraArgs,
const std::vector<std::string> &environment,
long long int timeout, const std::string &logPath) {
std::vector<std::string> arguments;
arguments.push_back("test-without-building");
std::copy(extraArgs.begin(), extraArgs.end(), std::back_inserter(arguments));
arguments.push_back("-xctestrun");
arguments.push_back(xctestrunFile);
if (resultBundlePath) {
arguments.push_back("-resultBundlePath");
arguments.push_back(resultBundlePath.getValue());
}
if (timeout > 0) {
arguments.push_back("-test-timeouts-enabled");
arguments.push_back("YES");
arguments.push_back("-maximum-test-execution-time-allowance");
arguments.push_back(std::to_string(timeout / 1000));
}
return RunProgram(diagnostics, "/usr/bin/xcodebuild", arguments, environment,
timeout, logPath);
}
void GenerateSingleTargetXCRunFile(const std::string &srcRunFile,
const std::string &localRunFile,
const std::string &srcTestTarget) {
llvm::sys::fs::copy_file(srcRunFile, localRunFile);
XCTestRunFile runFile(localRunFile);
auto maybeTargets = runFile.getTargets();
if (!maybeTargets) {
llvm::report_fatal_error(llvm::toString(maybeTargets.takeError()));
}
for (auto target : *maybeTargets) {
if (target != srcTestTarget) {
runFile.deleteTestTarget(target);
}
}
}
using Mutants = const std::vector<std::unique_ptr<Mutant>>;
void GenerateXCRunFile(const std::string &srcRunFile,
const std::string &localRunFile,
const std::string &srcTestTarget,
const Mutants::const_iterator &mutants_begin,
const Mutants::const_iterator &mutants_end) {
llvm::sys::fs::copy_file(srcRunFile, localRunFile);
XCTestRunFile runFile(localRunFile);
for (auto it = mutants_begin; it != mutants_end; ++it) {
auto &mutant = *it;
std::string newTarget = srcTestTarget + "-" + mutant->getIdentifier();
runFile.duplicateTestTarget(srcTestTarget, newTarget);
runFile.addEnvironmentVariable(newTarget, mutant->getIdentifier(), "1");
runFile.setBlueprintName(newTarget, mutant->getIdentifier());
}
runFile.deleteTestTarget(srcTestTarget);
}
class MutantExecutionTask {
public:
using In = const std::vector<std::unique_ptr<Mutant>>;
using Out = std::vector<std::unique_ptr<MutationResult>>;
using iterator = In::const_iterator;
MutantExecutionTask(const int taskID, const Configuration &configuration,
Diagnostics &diagnostics, const std::string xctestrunFile,
const XCTestRunConfig &runConfig,
ExecutionResult &baseline)
: taskID(taskID), configuration(configuration), diagnostics(diagnostics),
xctestrunFile(xctestrunFile), runConfig(runConfig), baseline(baseline) {
}
void operator()(iterator begin, iterator end, Out &storage,
progress_counter &counter);
private:
const int taskID;
const Configuration &configuration;
const XCTestRunConfig &runConfig;
Diagnostics &diagnostics;
const std::string xctestrunFile;
ExecutionResult &baseline;
};
static std::string ResultBundlePath(std::string resultBundleDir,
std::string targetName, int taskID) {
llvm::SmallString<128> resultBundlePath(resultBundleDir);
llvm::sys::path::append(resultBundlePath, targetName + "-" +
std::to_string(taskID) +
".xcresult");
return resultBundlePath.str().str();
}
void MutantExecutionTask::operator()(iterator begin, iterator end, Out &storage,
progress_counter &counter) {
Runner runner(diagnostics);
const std::string localRunFile =
xctestrunFile + ".mull-xctrn-" + std::to_string(taskID) + ".xctestrun";
GenerateXCRunFile(xctestrunFile, localRunFile, runConfig.testTarget, begin,
end);
std::string resultBundlePath =
ResultBundlePath(runConfig.resultBundleDir, runConfig.testTarget, taskID);
ExecutionResult result;
llvm::SmallString<128> logPath(runConfig.logPath);
if (!logPath.empty())
llvm::sys::path::append(logPath, std::to_string(taskID) + ".log");
int count = std::distance(begin, end);
result = RunXcodeBuildTest(
diagnostics, localRunFile, resultBundlePath, runConfig.xcodebuildArgs, {},
baseline.runningTime * count * 10, logPath.str().str());
XCResultFile resultFile(resultBundlePath);
auto failureTargets = resultFile.getFailureTestTargets();
if (!failureTargets) {
diagnostics.debug("no failure targets");
}
for (auto it = begin; it != end; ++it, counter.increment()) {
ExecutionResult targetResult;
targetResult.exitStatus = result.status;
if (failureTargets && failureTargets->find(it->get()->getIdentifier()) !=
failureTargets->end()) {
targetResult.status = Failed;
} else {
targetResult.status = Passed;
}
storage.push_back(
std::make_unique<MutationResult>(targetResult, it->get()));
}
}
} // namespace
std::unique_ptr<Result> XCTestRunInvocation::run() {
auto mutants = extractMutantInfo();
if (mutants.empty()) {
return std::make_unique<Result>(
std::move(mutants), std::vector<std::unique_ptr<MutationResult>>{});
}
Runner runner(diagnostics);
std::string singleTargetRunFile =
runConfig.xctestrunFile.str() + ".mull-xctrn-base.xctestrun";
GenerateSingleTargetXCRunFile(runConfig.xctestrunFile.str(),
singleTargetRunFile, runConfig.testTarget);
ExecutionResult baseline;
singleTask.execute("Baseline run", [&]() {
llvm::SmallString<128> logPath(runConfig.logPath);
if (!logPath.empty())
llvm::sys::path::append(logPath, "baseline.log");
baseline = RunXcodeBuildTest(diagnostics, singleTargetRunFile, llvm::None,
runConfig.xcodebuildArgs, {}, config.timeout,
logPath.str().str());
});
std::vector<std::unique_ptr<MutationResult>> mutationResults;
std::vector<MutantExecutionTask> tasks;
tasks.reserve(config.parallelization.mutantExecutionWorkers);
for (int i = 0; i < config.parallelization.mutantExecutionWorkers; i++) {
tasks.emplace_back(i, config, diagnostics, singleTargetRunFile, runConfig,
baseline);
}
TaskExecutor<MutantExecutionTask> mutantRunner(diagnostics, "Running mutants",
mutants, mutationResults,
std::move(tasks));
mutantRunner.execute();
return std::make_unique<Result>(std::move(mutants),
std::move(mutationResults));
}
std::vector<std::unique_ptr<mull::Mutant>>
XCTestRunInvocation::extractMutantInfo() {
XCTestRunFile file(runConfig.xctestrunFile.str());
auto products = file.getDependentProductPaths(runConfig.testTarget);
if (!products) {
diagnostics.error(llvm::toString(products.takeError()));
return {};
}
std::vector<std::unique_ptr<mull::Mutant>> output;
for (auto product : *products) {
auto binaryPath = GetBundleBinaryPath(product);
auto result = ExtractMutantInfo(binaryPath, factory, diagnostics);
if (!result) {
continue;
}
std::move(result->begin(), result->end(), std::back_inserter(output));
}
return std::move(output);
}
}; // namespace mull_xctest
| 36.562937 | 80 | 0.664722 | [
"object",
"vector"
] |
6772cceece4f362d4cf5bf8cf3b73f9adf3a3aba | 40,725 | cpp | C++ | export/windows/cpp/obj/src/DefaultAssetLibrary.cpp | TinyPlanetStudios/Project-Crash-Land | 365f196be4212602d32251566f26b53fb70693f6 | [
"MIT"
] | null | null | null | export/windows/cpp/obj/src/DefaultAssetLibrary.cpp | TinyPlanetStudios/Project-Crash-Land | 365f196be4212602d32251566f26b53fb70693f6 | [
"MIT"
] | null | null | null | export/windows/cpp/obj/src/DefaultAssetLibrary.cpp | TinyPlanetStudios/Project-Crash-Land | 365f196be4212602d32251566f26b53fb70693f6 | [
"MIT"
] | null | null | null | // Generated by Haxe 3.3.0
#include <hxcpp.h>
#ifndef INCLUDED_Date
#include <Date.h>
#endif
#ifndef INCLUDED_DefaultAssetLibrary
#include <DefaultAssetLibrary.h>
#endif
#ifndef INCLUDED_Std
#include <Std.h>
#endif
#ifndef INCLUDED_Sys
#include <Sys.h>
#endif
#ifndef INCLUDED_Type
#include <Type.h>
#endif
#ifndef INCLUDED___ASSET__flixel_fonts_monsterrat_ttf
#include <__ASSET__flixel_fonts_monsterrat_ttf.h>
#endif
#ifndef INCLUDED___ASSET__flixel_fonts_nokiafc22_ttf
#include <__ASSET__flixel_fonts_nokiafc22_ttf.h>
#endif
#ifndef INCLUDED___ASSET__flixel_images_ui_button_png
#include <__ASSET__flixel_images_ui_button_png.h>
#endif
#ifndef INCLUDED___ASSET__flixel_sounds_beep_ogg
#include <__ASSET__flixel_sounds_beep_ogg.h>
#endif
#ifndef INCLUDED___ASSET__flixel_sounds_flixel_ogg
#include <__ASSET__flixel_sounds_flixel_ogg.h>
#endif
#ifndef INCLUDED_cpp_vm_Deque
#include <cpp/vm/Deque.h>
#endif
#ifndef INCLUDED_cpp_vm_Thread
#include <cpp/vm/Thread.h>
#endif
#ifndef INCLUDED_haxe_IMap
#include <haxe/IMap.h>
#endif
#ifndef INCLUDED_haxe_Log
#include <haxe/Log.h>
#endif
#ifndef INCLUDED_haxe_Timer
#include <haxe/Timer.h>
#endif
#ifndef INCLUDED_haxe_Unserializer
#include <haxe/Unserializer.h>
#endif
#ifndef INCLUDED_haxe_ds_StringMap
#include <haxe/ds/StringMap.h>
#endif
#ifndef INCLUDED_haxe_io_Bytes
#include <haxe/io/Bytes.h>
#endif
#ifndef INCLUDED_openfl__legacy_AssetLibrary
#include <openfl/_legacy/AssetLibrary.h>
#endif
#ifndef INCLUDED_openfl__legacy_AssetType
#include <openfl/_legacy/AssetType.h>
#endif
#ifndef INCLUDED_openfl__legacy_display_BitmapData
#include <openfl/_legacy/display/BitmapData.h>
#endif
#ifndef INCLUDED_openfl__legacy_display_IBitmapDrawable
#include <openfl/_legacy/display/IBitmapDrawable.h>
#endif
#ifndef INCLUDED_openfl__legacy_events_EventDispatcher
#include <openfl/_legacy/events/EventDispatcher.h>
#endif
#ifndef INCLUDED_openfl__legacy_events_IEventDispatcher
#include <openfl/_legacy/events/IEventDispatcher.h>
#endif
#ifndef INCLUDED_openfl__legacy_media_Sound
#include <openfl/_legacy/media/Sound.h>
#endif
#ifndef INCLUDED_openfl__legacy_net_URLRequest
#include <openfl/_legacy/net/URLRequest.h>
#endif
#ifndef INCLUDED_openfl__legacy_text_Font
#include <openfl/_legacy/text/Font.h>
#endif
#ifndef INCLUDED_openfl__legacy_text_FontStyle
#include <openfl/_legacy/text/FontStyle.h>
#endif
#ifndef INCLUDED_openfl__legacy_text_FontType
#include <openfl/_legacy/text/FontType.h>
#endif
#ifndef INCLUDED_openfl__legacy_utils_ByteArray
#include <openfl/_legacy/utils/ByteArray.h>
#endif
#ifndef INCLUDED_openfl__legacy_utils_IDataInput
#include <openfl/_legacy/utils/IDataInput.h>
#endif
#ifndef INCLUDED_openfl__legacy_utils_IDataOutput
#include <openfl/_legacy/utils/IDataOutput.h>
#endif
#ifndef INCLUDED_openfl__legacy_utils_IMemoryRange
#include <openfl/_legacy/utils/IMemoryRange.h>
#endif
#ifndef INCLUDED_openfl_media_SoundLoaderContext
#include <openfl/media/SoundLoaderContext.h>
#endif
#ifndef INCLUDED_sys_FileSystem
#include <sys/FileSystem.h>
#endif
void DefaultAssetLibrary_obj::__construct(){
HX_STACK_FRAME("DefaultAssetLibrary","new",0xbc37e41e,"DefaultAssetLibrary.new","DefaultAssetLibrary.hx",37,0x0fc48912)
HX_STACK_THIS(this)
HXLINE( 48) this->type = ::haxe::ds::StringMap_obj::__new();
HXLINE( 47) this->path = ::haxe::ds::StringMap_obj::__new();
HXLINE( 46) this->className = ::haxe::ds::StringMap_obj::__new();
HXLINE( 54) HX_VARI( ::DefaultAssetLibrary,_gthis) = hx::ObjectPtr<OBJ_>(this);
HXLINE( 56) super::__construct();
HXLINE( 116) ::openfl::_legacy::text::Font_obj::registerFont(hx::ClassOf< ::__ASSET__flixel_fonts_nokiafc22_ttf >());
HXLINE( 117) ::openfl::_legacy::text::Font_obj::registerFont(hx::ClassOf< ::__ASSET__flixel_fonts_monsterrat_ttf >());
HXLINE( 180) this->className->set(HX_("flixel/sounds/beep.ogg",c7,05,0e,d0),hx::ClassOf< ::__ASSET__flixel_sounds_beep_ogg >());
HXLINE( 181) this->type->set(HX_("flixel/sounds/beep.ogg",c7,05,0e,d0),::openfl::_legacy::AssetType_obj::SOUND_dyn());
HXLINE( 183) this->className->set(HX_("flixel/sounds/flixel.ogg",35,e0,ef,88),hx::ClassOf< ::__ASSET__flixel_sounds_flixel_ogg >());
HXLINE( 184) this->type->set(HX_("flixel/sounds/flixel.ogg",35,e0,ef,88),::openfl::_legacy::AssetType_obj::SOUND_dyn());
HXLINE( 186) this->className->set(HX_("flixel/fonts/nokiafc22.ttf",59,d0,25,83),hx::ClassOf< ::__ASSET__flixel_fonts_nokiafc22_ttf >());
HXLINE( 187) this->type->set(HX_("flixel/fonts/nokiafc22.ttf",59,d0,25,83),::openfl::_legacy::AssetType_obj::FONT_dyn());
HXLINE( 189) this->className->set(HX_("flixel/fonts/monsterrat.ttf",01,2e,a7,65),hx::ClassOf< ::__ASSET__flixel_fonts_monsterrat_ttf >());
HXLINE( 190) this->type->set(HX_("flixel/fonts/monsterrat.ttf",01,2e,a7,65),::openfl::_legacy::AssetType_obj::FONT_dyn());
HXLINE( 192) this->className->set(HX_("flixel/images/ui/button.png",44,ee,2f,34),hx::ClassOf< ::__ASSET__flixel_images_ui_button_png >());
HXLINE( 193) this->type->set(HX_("flixel/images/ui/button.png",44,ee,2f,34),::openfl::_legacy::AssetType_obj::IMAGE_dyn());
HXLINE( 196) {
HXLINE( 198) this->loadManifest();
HXLINE( 200) Int _hx_tmp = ::Sys_obj::args()->indexOf(HX_("-livereload",b2,45,9f,14),null());
HXDLIN( 200) if ((_hx_tmp > (int)-1)) {
HX_BEGIN_LOCAL_FUNC_S2(hx::LocalFunc,_hx_Closure_0, ::DefaultAssetLibrary,_gthis,::String,path) HXARGC(0)
void _hx_run(){
HX_STACK_FRAME("DefaultAssetLibrary","new",0xbc37e41e,"DefaultAssetLibrary.new","DefaultAssetLibrary.hx",206,0x0fc48912)
HXLINE( 208) HX_VARI( Float,modified) = ( ( ::Date)(::sys::FileSystem_obj::stat(path)->__Field(HX_("mtime",fa,06,aa,0f),hx::paccDynamic)) )->getTime();
HXLINE( 210) Bool _hx_tmp1 = (modified > _gthis->lastModified);
HXDLIN( 210) if (_hx_tmp1) {
HXLINE( 212) _gthis->lastModified = modified;
HXLINE( 213) _gthis->loadManifest();
HXLINE( 215) Bool _hx_tmp2 = hx::IsNotNull( _gthis->eventCallback );
HXDLIN( 215) if (_hx_tmp2) {
HXLINE( 217) _gthis->eventCallback(_gthis,HX_("change",70,91,72,b7));
}
}
}
HX_END_LOCAL_FUNC0((void))
HXLINE( 202) HX_VARI( ::String,path) = ::sys::FileSystem_obj::fullPath(HX_("manifest",af,fb,29,d0));
HXLINE( 203) this->lastModified = ( ( ::Date)(::sys::FileSystem_obj::stat(path)->__Field(HX_("mtime",fa,06,aa,0f),hx::paccDynamic)) )->getTime();
HXLINE( 205) this->timer = ::haxe::Timer_obj::__new((int)2000);
HXLINE( 206) this->timer->run = ::Dynamic(new _hx_Closure_0(_gthis,path));
}
}
}
Dynamic DefaultAssetLibrary_obj::__CreateEmpty() { return new DefaultAssetLibrary_obj; }
hx::ObjectPtr< DefaultAssetLibrary_obj > DefaultAssetLibrary_obj::__new()
{
hx::ObjectPtr< DefaultAssetLibrary_obj > _hx_result = new DefaultAssetLibrary_obj();
_hx_result->__construct();
return _hx_result;
}
Dynamic DefaultAssetLibrary_obj::__Create(hx::DynamicArray inArgs)
{
hx::ObjectPtr< DefaultAssetLibrary_obj > _hx_result = new DefaultAssetLibrary_obj();
_hx_result->__construct();
return _hx_result;
}
Bool DefaultAssetLibrary_obj::exists(::String id,::hx::EnumBase type){
HX_STACK_FRAME("DefaultAssetLibrary","exists",0x972074de,"DefaultAssetLibrary.exists","DefaultAssetLibrary.hx",238,0x0fc48912)
HX_STACK_THIS(this)
HX_STACK_ARG(id,"id")
HX_STACK_ARG(type,"type")
HXLINE( 240) HX_VARI( ::hx::EnumBase,assetType) = this->type->get(id).StaticCast< ::hx::EnumBase >();
HXLINE( 242) Bool _hx_tmp = hx::IsNotNull( assetType );
HXDLIN( 242) if (_hx_tmp) {
HXLINE( 244) Bool _hx_tmp1;
HXDLIN( 244) if (hx::IsNotEq( assetType,type )) {
HXLINE( 244) Bool _hx_tmp2;
HXDLIN( 244) if (hx::IsNotEq( type,::openfl::_legacy::AssetType_obj::SOUND_dyn() )) {
HXLINE( 244) _hx_tmp2 = hx::IsEq( type,::openfl::_legacy::AssetType_obj::MUSIC_dyn() );
}
else {
HXLINE( 244) _hx_tmp2 = true;
}
HXDLIN( 244) if (_hx_tmp2) {
HXLINE( 244) if (hx::IsNotEq( assetType,::openfl::_legacy::AssetType_obj::MUSIC_dyn() )) {
HXLINE( 244) _hx_tmp1 = hx::IsEq( assetType,::openfl::_legacy::AssetType_obj::SOUND_dyn() );
}
else {
HXLINE( 244) _hx_tmp1 = true;
}
}
else {
HXLINE( 244) _hx_tmp1 = false;
}
}
else {
HXLINE( 244) _hx_tmp1 = true;
}
HXDLIN( 244) if (_hx_tmp1) {
HXLINE( 246) return true;
}
HXLINE( 250) Bool _hx_tmp3;
HXDLIN( 250) Bool _hx_tmp4;
HXDLIN( 250) if (hx::IsNotEq( type,::openfl::_legacy::AssetType_obj::BINARY_dyn() )) {
HXLINE( 250) _hx_tmp4 = hx::IsNull( type );
}
else {
HXLINE( 250) _hx_tmp4 = true;
}
HXDLIN( 250) if (!(_hx_tmp4)) {
HXLINE( 250) if (hx::IsEq( assetType,::openfl::_legacy::AssetType_obj::BINARY_dyn() )) {
HXLINE( 250) _hx_tmp3 = hx::IsEq( type,::openfl::_legacy::AssetType_obj::TEXT_dyn() );
}
else {
HXLINE( 250) _hx_tmp3 = false;
}
}
else {
HXLINE( 250) _hx_tmp3 = true;
}
HXDLIN( 250) if (_hx_tmp3) {
HXLINE( 252) return true;
}
}
HXLINE( 258) return false;
}
::openfl::_legacy::display::BitmapData DefaultAssetLibrary_obj::getBitmapData(::String id){
HX_STACK_FRAME("DefaultAssetLibrary","getBitmapData",0xb8207f2d,"DefaultAssetLibrary.getBitmapData","DefaultAssetLibrary.hx",265,0x0fc48912)
HX_STACK_THIS(this)
HX_STACK_ARG(id,"id")
HXLINE( 265) Bool _hx_tmp = this->className->exists(id);
HXDLIN( 265) if (_hx_tmp) {
HXLINE( 267) return hx::TCast< ::openfl::_legacy::display::BitmapData >::cast(::Type_obj::createInstance(this->className->get(id),::cpp::VirtualArray_obj::__new(0)));
}
else {
HXLINE( 271) return ::openfl::_legacy::display::BitmapData_obj::load(( (::String)(this->path->get(id)) ),null());
}
HXLINE( 265) return null();
}
::openfl::_legacy::utils::ByteArray DefaultAssetLibrary_obj::getBytes(::String id){
HX_STACK_FRAME("DefaultAssetLibrary","getBytes",0x86b4b377,"DefaultAssetLibrary.getBytes","DefaultAssetLibrary.hx",280,0x0fc48912)
HX_STACK_THIS(this)
HX_STACK_ARG(id,"id")
HXLINE( 280) Bool _hx_tmp = this->className->exists(id);
HXDLIN( 280) if (_hx_tmp) {
HXLINE( 282) return hx::TCast< ::openfl::_legacy::utils::ByteArray >::cast(::Type_obj::createInstance(this->className->get(id),::cpp::VirtualArray_obj::__new(0)));
}
else {
HXLINE( 286) return ::openfl::_legacy::utils::ByteArray_obj::readFile(( (::String)(this->path->get(id)) ));
}
HXLINE( 280) return null();
}
::openfl::_legacy::text::Font DefaultAssetLibrary_obj::getFont(::String id){
HX_STACK_FRAME("DefaultAssetLibrary","getFont",0x974ed843,"DefaultAssetLibrary.getFont","DefaultAssetLibrary.hx",295,0x0fc48912)
HX_STACK_THIS(this)
HX_STACK_ARG(id,"id")
HXLINE( 295) Bool _hx_tmp = this->className->exists(id);
HXDLIN( 295) if (_hx_tmp) {
HXLINE( 297) HX_VARI( ::Dynamic,fontClass) = this->className->get(id);
HXLINE( 298) ::openfl::_legacy::text::Font_obj::registerFont(fontClass);
HXLINE( 299) return hx::TCast< ::openfl::_legacy::text::Font >::cast(::Type_obj::createInstance(fontClass,::cpp::VirtualArray_obj::__new(0)));
}
else {
HXLINE( 303) return ::openfl::_legacy::text::Font_obj::__new(( (::String)(this->path->get(id)) ),null(),null());
}
HXLINE( 295) return null();
}
::openfl::_legacy::media::Sound DefaultAssetLibrary_obj::getMusic(::String id){
HX_STACK_FRAME("DefaultAssetLibrary","getMusic",0xd9777bb1,"DefaultAssetLibrary.getMusic","DefaultAssetLibrary.hx",312,0x0fc48912)
HX_STACK_THIS(this)
HX_STACK_ARG(id,"id")
HXLINE( 312) Bool _hx_tmp = this->className->exists(id);
HXDLIN( 312) if (_hx_tmp) {
HXLINE( 314) return hx::TCast< ::openfl::_legacy::media::Sound >::cast(::Type_obj::createInstance(this->className->get(id),::cpp::VirtualArray_obj::__new(0)));
}
else {
HXLINE( 318) return ::openfl::_legacy::media::Sound_obj::__new( ::openfl::_legacy::net::URLRequest_obj::__new(( (::String)(this->path->get(id)) )),null(),true);
}
HXLINE( 312) return null();
}
::String DefaultAssetLibrary_obj::getPath(::String id){
HX_STACK_FRAME("DefaultAssetLibrary","getPath",0x9de06019,"DefaultAssetLibrary.getPath","DefaultAssetLibrary.hx",333,0x0fc48912)
HX_STACK_THIS(this)
HX_STACK_ARG(id,"id")
HXLINE( 333) return ( (::String)(this->path->get(id)) );
}
::openfl::_legacy::media::Sound DefaultAssetLibrary_obj::getSound(::String id){
HX_STACK_FRAME("DefaultAssetLibrary","getSound",0x49e937db,"DefaultAssetLibrary.getSound","DefaultAssetLibrary.hx",342,0x0fc48912)
HX_STACK_THIS(this)
HX_STACK_ARG(id,"id")
HXLINE( 342) Bool _hx_tmp = this->className->exists(id);
HXDLIN( 342) if (_hx_tmp) {
HXLINE( 344) return hx::TCast< ::openfl::_legacy::media::Sound >::cast(::Type_obj::createInstance(this->className->get(id),::cpp::VirtualArray_obj::__new(0)));
}
else {
HXLINE( 348) ::openfl::_legacy::net::URLRequest _hx_tmp1 = ::openfl::_legacy::net::URLRequest_obj::__new(( (::String)(this->path->get(id)) ));
HXDLIN( 348) Bool _hx_tmp2 = hx::IsEq( this->type->get(id).StaticCast< ::hx::EnumBase >(),::openfl::_legacy::AssetType_obj::MUSIC_dyn() );
HXDLIN( 348) return ::openfl::_legacy::media::Sound_obj::__new(_hx_tmp1,null(),_hx_tmp2);
}
HXLINE( 342) return null();
}
::String DefaultAssetLibrary_obj::getText(::String id){
HX_STACK_FRAME("DefaultAssetLibrary","getText",0xa0884721,"DefaultAssetLibrary.getText","DefaultAssetLibrary.hx",355,0x0fc48912)
HX_STACK_THIS(this)
HX_STACK_ARG(id,"id")
HXLINE( 357) HX_VARI( ::openfl::_legacy::utils::ByteArray,bytes) = this->getBytes(id);
HXLINE( 359) Bool _hx_tmp = hx::IsNull( bytes );
HXDLIN( 359) if (_hx_tmp) {
HXLINE( 361) return null();
}
else {
HXLINE( 365) return bytes->readUTFBytes(bytes->length);
}
HXLINE( 359) return null();
}
Bool DefaultAssetLibrary_obj::isLocal(::String id,::hx::EnumBase type){
HX_STACK_FRAME("DefaultAssetLibrary","isLocal",0x968237df,"DefaultAssetLibrary.isLocal","DefaultAssetLibrary.hx",374,0x0fc48912)
HX_STACK_THIS(this)
HX_STACK_ARG(id,"id")
HX_STACK_ARG(type,"type")
HXLINE( 374) return true;
}
::Array< ::String > DefaultAssetLibrary_obj::list(::hx::EnumBase type){
HX_STACK_FRAME("DefaultAssetLibrary","list",0xf3604ee0,"DefaultAssetLibrary.list","DefaultAssetLibrary.hx",379,0x0fc48912)
HX_STACK_THIS(this)
HX_STACK_ARG(type,"type")
HXLINE( 381) HX_VARI( ::Array< ::String >,items) = ::Array_obj< ::String >::__new(0);
HXLINE( 383) {
HXLINE( 383) HX_VARI( ::Dynamic,tmp) = this->type->keys();
HXDLIN( 383) while(true){
HXLINE( 383) Bool _hx_tmp = !(( (Bool)( ::Dynamic(tmp->__Field(HX_("hasNext",6d,a5,46,18),hx::paccDynamic))()) ));
HXDLIN( 383) if (_hx_tmp) {
HXLINE( 383) goto _hx_goto_0;
}
HXDLIN( 383) HX_VARI( ::String,id) = ( (::String)( ::Dynamic(tmp->__Field(HX_("next",f3,84,02,49),hx::paccDynamic))()) );
HXLINE( 385) Bool _hx_tmp1;
HXDLIN( 385) Bool _hx_tmp2 = hx::IsNotNull( type );
HXDLIN( 385) if (_hx_tmp2) {
HXLINE( 385) _hx_tmp1 = this->exists(id,type);
}
else {
HXLINE( 385) _hx_tmp1 = true;
}
HXDLIN( 385) if (_hx_tmp1) {
HXLINE( 387) items->push(id);
}
}
_hx_goto_0:;
}
HXLINE( 393) return items;
}
void DefaultAssetLibrary_obj::loadBitmapData(::String id, ::Dynamic handler){
HX_STACK_FRAME("DefaultAssetLibrary","loadBitmapData",0x9243e881,"DefaultAssetLibrary.loadBitmapData","DefaultAssetLibrary.hx",400,0x0fc48912)
HX_STACK_THIS(this)
HX_STACK_ARG(id,"id")
HX_STACK_ARG(handler,"handler")
HXLINE( 400) ::DefaultAssetLibrary_obj::workerIncomingQueue->add(HX_("WORK",d1,c9,bd,39));
HXDLIN( 400) ::DefaultAssetLibrary_obj::workerIncomingQueue->add(this->getBitmapData_dyn());
HXDLIN( 400) ::DefaultAssetLibrary_obj::workerIncomingQueue->add(id);
HXDLIN( 400) ::DefaultAssetLibrary_obj::workerIncomingQueue->add(handler);
HXDLIN( 400) ::DefaultAssetLibrary_obj::loading++;
}
void DefaultAssetLibrary_obj::loadBytes(::String id, ::Dynamic handler){
HX_STACK_FRAME("DefaultAssetLibrary","loadBytes",0x8c71caa3,"DefaultAssetLibrary.loadBytes","DefaultAssetLibrary.hx",407,0x0fc48912)
HX_STACK_THIS(this)
HX_STACK_ARG(id,"id")
HX_STACK_ARG(handler,"handler")
HXLINE( 407) ::DefaultAssetLibrary_obj::workerIncomingQueue->add(HX_("WORK",d1,c9,bd,39));
HXDLIN( 407) ::DefaultAssetLibrary_obj::workerIncomingQueue->add(this->getBytes_dyn());
HXDLIN( 407) ::DefaultAssetLibrary_obj::workerIncomingQueue->add(id);
HXDLIN( 407) ::DefaultAssetLibrary_obj::workerIncomingQueue->add(handler);
HXDLIN( 407) ::DefaultAssetLibrary_obj::loading++;
}
void DefaultAssetLibrary_obj::loadFont(::String id, ::Dynamic handler){
HX_STACK_FRAME("DefaultAssetLibrary","loadFont",0x1da5ca97,"DefaultAssetLibrary.loadFont","DefaultAssetLibrary.hx",414,0x0fc48912)
HX_STACK_THIS(this)
HX_STACK_ARG(id,"id")
HX_STACK_ARG(handler,"handler")
HXLINE( 414) ::DefaultAssetLibrary_obj::workerIncomingQueue->add(HX_("WORK",d1,c9,bd,39));
HXDLIN( 414) ::DefaultAssetLibrary_obj::workerIncomingQueue->add(this->getFont_dyn());
HXDLIN( 414) ::DefaultAssetLibrary_obj::workerIncomingQueue->add(id);
HXDLIN( 414) ::DefaultAssetLibrary_obj::workerIncomingQueue->add(handler);
HXDLIN( 414) ::DefaultAssetLibrary_obj::loading++;
}
void DefaultAssetLibrary_obj::loadManifest(){
HX_STACK_FRAME("DefaultAssetLibrary","loadManifest",0x6f596c77,"DefaultAssetLibrary.loadManifest","DefaultAssetLibrary.hx",421,0x0fc48912)
HX_STACK_THIS(this)
HXLINE( 421) try {
HX_STACK_CATCHABLE( ::Dynamic, 0);
HXLINE( 430) HX_VARI( ::openfl::_legacy::utils::ByteArray,bytes) = ::openfl::_legacy::utils::ByteArray_obj::readFile(HX_("manifest",af,fb,29,d0));
HXLINE( 433) Bool _hx_tmp = hx::IsNotNull( bytes );
HXDLIN( 433) if (_hx_tmp) {
HXLINE( 435) bytes->position = (int)0;
HXLINE( 437) Bool _hx_tmp1 = (bytes->length > (int)0);
HXDLIN( 437) if (_hx_tmp1) {
HXLINE( 439) HX_VARI( ::String,data) = bytes->readUTFBytes(bytes->length);
HXLINE( 441) Bool _hx_tmp2;
HXDLIN( 441) Bool _hx_tmp3 = hx::IsNotNull( data );
HXDLIN( 441) if (_hx_tmp3) {
HXLINE( 441) _hx_tmp2 = (data.length > (int)0);
}
else {
HXLINE( 441) _hx_tmp2 = false;
}
HXDLIN( 441) if (_hx_tmp2) {
HXLINE( 443) HX_VARI( ::cpp::VirtualArray,manifest) = ( (::cpp::VirtualArray)(::haxe::Unserializer_obj::run(data)) );
HXLINE( 445) {
HXLINE( 445) HX_VARI( Int,_g) = (int)0;
HXDLIN( 445) while((_g < manifest->get_length())){
HXLINE( 445) HX_VARI( ::Dynamic,asset) = manifest->__get(_g);
HXDLIN( 445) ++_g;
HXLINE( 447) ::String key = ( (::String)(asset->__Field(HX_("id",db,5b,00,00),hx::paccDynamic)) );
HXDLIN( 447) Bool _hx_tmp4 = this->className->exists(key);
HXDLIN( 447) if (!(_hx_tmp4)) {
HXLINE( 449) {
HXLINE( 449) ::String key1 = ( (::String)(asset->__Field(HX_("id",db,5b,00,00),hx::paccDynamic)) );
HXDLIN( 449) ::String value = ( (::String)(asset->__Field(HX_("path",a5,e5,51,4a),hx::paccDynamic)) );
HXDLIN( 449) this->path->set(key1,value);
}
HXLINE( 450) {
HXLINE( 450) ::String key2 = ( (::String)(asset->__Field(HX_("id",db,5b,00,00),hx::paccDynamic)) );
HXDLIN( 450) ::hx::EnumBase value1 = ::Type_obj::createEnum(hx::ClassOf< ::openfl::_legacy::AssetType >(), ::Dynamic(asset->__Field(HX_("type",ba,f2,08,4d),hx::paccDynamic)),null());
HXDLIN( 450) this->type->set(key2,value1);
}
}
}
}
}
}
}
else {
HXLINE( 462) ::haxe::Log_obj::trace(HX_("Warning: Could not load asset manifest (bytes was null)",83,9c,5b,2e),hx::SourceInfo(HX_("DefaultAssetLibrary.hx",12,89,c4,0f),462,HX_("DefaultAssetLibrary",2c,3d,78,3a),HX_("loadManifest",f5,e7,92,89)));
}
}
catch( ::Dynamic _hx_e){
if (_hx_e.IsClass< ::Dynamic >() ){
HX_STACK_BEGIN_CATCH
::Dynamic e = _hx_e;
HXLINE( 468) ::String _hx_tmp5 = ::Std_obj::string(e);
HXDLIN( 468) ::haxe::Log_obj::trace(((HX_("Warning: Could not load asset manifest (",73,7e,fd,21) + _hx_tmp5) + HX_(")",29,00,00,00)),hx::SourceInfo(HX_("DefaultAssetLibrary.hx",12,89,c4,0f),468,HX_("DefaultAssetLibrary",2c,3d,78,3a),HX_("loadManifest",f5,e7,92,89)));
}
else {
HX_STACK_DO_THROW(_hx_e);
}
}
}
HX_DEFINE_DYNAMIC_FUNC0(DefaultAssetLibrary_obj,loadManifest,(void))
void DefaultAssetLibrary_obj::loadMusic(::String id, ::Dynamic handler){
HX_STACK_FRAME("DefaultAssetLibrary","loadMusic",0xdf3492dd,"DefaultAssetLibrary.loadMusic","DefaultAssetLibrary.hx",477,0x0fc48912)
HX_STACK_THIS(this)
HX_STACK_ARG(id,"id")
HX_STACK_ARG(handler,"handler")
HXLINE( 477) ::DefaultAssetLibrary_obj::workerIncomingQueue->add(HX_("WORK",d1,c9,bd,39));
HXDLIN( 477) ::DefaultAssetLibrary_obj::workerIncomingQueue->add(this->getMusic_dyn());
HXDLIN( 477) ::DefaultAssetLibrary_obj::workerIncomingQueue->add(id);
HXDLIN( 477) ::DefaultAssetLibrary_obj::workerIncomingQueue->add(handler);
HXDLIN( 477) ::DefaultAssetLibrary_obj::loading++;
}
void DefaultAssetLibrary_obj::loadSound(::String id, ::Dynamic handler){
HX_STACK_FRAME("DefaultAssetLibrary","loadSound",0x4fa64f07,"DefaultAssetLibrary.loadSound","DefaultAssetLibrary.hx",484,0x0fc48912)
HX_STACK_THIS(this)
HX_STACK_ARG(id,"id")
HX_STACK_ARG(handler,"handler")
HXLINE( 484) ::DefaultAssetLibrary_obj::workerIncomingQueue->add(HX_("WORK",d1,c9,bd,39));
HXDLIN( 484) ::DefaultAssetLibrary_obj::workerIncomingQueue->add(this->getSound_dyn());
HXDLIN( 484) ::DefaultAssetLibrary_obj::workerIncomingQueue->add(id);
HXDLIN( 484) ::DefaultAssetLibrary_obj::workerIncomingQueue->add(handler);
HXDLIN( 484) ::DefaultAssetLibrary_obj::loading++;
}
void DefaultAssetLibrary_obj::loadText(::String id, ::Dynamic handler){
HX_BEGIN_LOCAL_FUNC_S1(hx::LocalFunc,_hx_Closure_0, ::Dynamic,handler) HXARGC(1)
void _hx_run( ::openfl::_legacy::utils::ByteArray bytes){
HX_STACK_FRAME("DefaultAssetLibrary","loadText",0x26df3975,"DefaultAssetLibrary.loadText","DefaultAssetLibrary.hx",493,0x0fc48912)
HX_STACK_ARG(bytes,"bytes")
HXLINE( 493) Bool _hx_tmp = hx::IsNull( bytes );
HXDLIN( 493) if (_hx_tmp) {
HXLINE( 495) handler(null());
}
else {
HXLINE( 499) ::String _hx_tmp1 = bytes->readUTFBytes(bytes->length);
HXDLIN( 499) handler(_hx_tmp1);
}
}
HX_END_LOCAL_FUNC1((void))
HX_STACK_FRAME("DefaultAssetLibrary","loadText",0x26df3975,"DefaultAssetLibrary.loadText","DefaultAssetLibrary.hx",489,0x0fc48912)
HX_STACK_THIS(this)
HX_STACK_ARG(id,"id")
HX_STACK_ARG(handler,"handler")
HXLINE( 491) HX_VARI( ::Dynamic,callback) = ::Dynamic(new _hx_Closure_0(handler));
HXLINE( 505) this->loadBytes(id,callback);
}
void DefaultAssetLibrary_obj::_hx___load( ::Dynamic getMethod,::String id, ::Dynamic handler){
HX_STACK_FRAME("DefaultAssetLibrary","__load",0xcdf05448,"DefaultAssetLibrary.__load","DefaultAssetLibrary.hx",538,0x0fc48912)
HX_STACK_THIS(this)
HX_STACK_ARG(getMethod,"getMethod")
HX_STACK_ARG(id,"id")
HX_STACK_ARG(handler,"handler")
HXLINE( 540) ::DefaultAssetLibrary_obj::workerIncomingQueue->add(HX_("WORK",d1,c9,bd,39));
HXLINE( 541) ::DefaultAssetLibrary_obj::workerIncomingQueue->add(getMethod);
HXLINE( 542) ::DefaultAssetLibrary_obj::workerIncomingQueue->add(id);
HXLINE( 543) ::DefaultAssetLibrary_obj::workerIncomingQueue->add(handler);
HXLINE( 545) ::DefaultAssetLibrary_obj::loading++;
}
HX_DEFINE_DYNAMIC_FUNC3(DefaultAssetLibrary_obj,_hx___load,(void))
Int DefaultAssetLibrary_obj::loaded;
Int DefaultAssetLibrary_obj::loading;
::cpp::vm::Deque DefaultAssetLibrary_obj::workerIncomingQueue;
::cpp::vm::Deque DefaultAssetLibrary_obj::workerResult;
::cpp::vm::Thread DefaultAssetLibrary_obj::workerThread;
void DefaultAssetLibrary_obj::_hx___doWork(){
HX_STACK_FRAME("DefaultAssetLibrary","__doWork",0x3075ad9e,"DefaultAssetLibrary.__doWork","DefaultAssetLibrary.hx",512,0x0fc48912)
HXLINE( 512) while(true){
HXLINE( 514) HX_VARI( ::Dynamic,message) = ::DefaultAssetLibrary_obj::workerIncomingQueue->pop(true);
HXLINE( 516) if (hx::IsEq( message,HX_("WORK",d1,c9,bd,39) )) {
HXLINE( 518) HX_VARI( ::Dynamic,getMethod) = ::DefaultAssetLibrary_obj::workerIncomingQueue->pop(true);
HXLINE( 519) HX_VARI( ::Dynamic,id) = ::DefaultAssetLibrary_obj::workerIncomingQueue->pop(true);
HXLINE( 520) HX_VARI( ::Dynamic,handler) = ::DefaultAssetLibrary_obj::workerIncomingQueue->pop(true);
HXLINE( 522) HX_VARI( ::Dynamic,data) = getMethod(id);
HXLINE( 523) ::DefaultAssetLibrary_obj::workerResult->add(HX_("RESULT",dd,14,07,bb));
HXLINE( 524) ::DefaultAssetLibrary_obj::workerResult->add(data);
HXLINE( 525) ::DefaultAssetLibrary_obj::workerResult->add(handler);
}
else {
HXLINE( 527) if (hx::IsEq( message,HX_("EXIT",1e,bf,de,2d) )) {
HXLINE( 529) goto _hx_goto_2;
}
}
}
_hx_goto_2:;
}
STATIC_HX_DEFINE_DYNAMIC_FUNC0(DefaultAssetLibrary_obj,_hx___doWork,(void))
void DefaultAssetLibrary_obj::_hx___poll(){
HX_STACK_FRAME("DefaultAssetLibrary","__poll",0xd0953861,"DefaultAssetLibrary.__poll","DefaultAssetLibrary.hx",552,0x0fc48912)
HXLINE( 552) Bool _hx_tmp = (::DefaultAssetLibrary_obj::loading > ::DefaultAssetLibrary_obj::loaded);
HXDLIN( 552) if (_hx_tmp) {
HXLINE( 554) Bool _hx_tmp1 = hx::IsNull( ::DefaultAssetLibrary_obj::workerThread );
HXDLIN( 554) if (_hx_tmp1) {
HXLINE( 556) ::DefaultAssetLibrary_obj::workerThread = ::cpp::vm::Thread_obj::create(::DefaultAssetLibrary_obj::_hx___doWork_dyn());
}
HXLINE( 560) HX_VARI( ::Dynamic,message) = ::DefaultAssetLibrary_obj::workerResult->pop(false);
HXLINE( 562) while(hx::IsEq( message,HX_("RESULT",dd,14,07,bb) )){
HXLINE( 564) ::DefaultAssetLibrary_obj::loaded++;
HXLINE( 566) HX_VARI( ::Dynamic,data) = ::DefaultAssetLibrary_obj::workerResult->pop(true);
HXLINE( 567) HX_VARI( ::Dynamic,handler) = ::DefaultAssetLibrary_obj::workerResult->pop(true);
HXLINE( 569) Bool _hx_tmp2 = hx::IsNotNull( handler );
HXDLIN( 569) if (_hx_tmp2) {
HXLINE( 571) handler(data);
}
HXLINE( 575) message = ::DefaultAssetLibrary_obj::workerResult->pop(false);
}
}
else {
HXLINE( 581) Bool _hx_tmp3 = hx::IsNotNull( ::DefaultAssetLibrary_obj::workerThread );
HXDLIN( 581) if (_hx_tmp3) {
HXLINE( 583) ::DefaultAssetLibrary_obj::workerIncomingQueue->add(HX_("EXIT",1e,bf,de,2d));
HXLINE( 584) ::DefaultAssetLibrary_obj::workerThread = null();
}
}
}
STATIC_HX_DEFINE_DYNAMIC_FUNC0(DefaultAssetLibrary_obj,_hx___poll,(void))
DefaultAssetLibrary_obj::DefaultAssetLibrary_obj()
{
}
void DefaultAssetLibrary_obj::__Mark(HX_MARK_PARAMS)
{
HX_MARK_BEGIN_CLASS(DefaultAssetLibrary);
HX_MARK_MEMBER_NAME(className,"className");
HX_MARK_MEMBER_NAME(path,"path");
HX_MARK_MEMBER_NAME(type,"type");
HX_MARK_MEMBER_NAME(lastModified,"lastModified");
HX_MARK_MEMBER_NAME(timer,"timer");
::openfl::_legacy::AssetLibrary_obj::__Mark(HX_MARK_ARG);
HX_MARK_END_CLASS();
}
void DefaultAssetLibrary_obj::__Visit(HX_VISIT_PARAMS)
{
HX_VISIT_MEMBER_NAME(className,"className");
HX_VISIT_MEMBER_NAME(path,"path");
HX_VISIT_MEMBER_NAME(type,"type");
HX_VISIT_MEMBER_NAME(lastModified,"lastModified");
HX_VISIT_MEMBER_NAME(timer,"timer");
::openfl::_legacy::AssetLibrary_obj::__Visit(HX_VISIT_ARG);
}
hx::Val DefaultAssetLibrary_obj::__Field(const ::String &inName,hx::PropertyAccess inCallProp)
{
switch(inName.length) {
case 4:
if (HX_FIELD_EQ(inName,"path") ) { return hx::Val( path); }
if (HX_FIELD_EQ(inName,"type") ) { return hx::Val( type); }
if (HX_FIELD_EQ(inName,"list") ) { return hx::Val( list_dyn()); }
break;
case 5:
if (HX_FIELD_EQ(inName,"timer") ) { return hx::Val( timer); }
break;
case 6:
if (HX_FIELD_EQ(inName,"exists") ) { return hx::Val( exists_dyn()); }
if (HX_FIELD_EQ(inName,"__load") ) { return hx::Val( _hx___load_dyn()); }
break;
case 7:
if (HX_FIELD_EQ(inName,"getFont") ) { return hx::Val( getFont_dyn()); }
if (HX_FIELD_EQ(inName,"getPath") ) { return hx::Val( getPath_dyn()); }
if (HX_FIELD_EQ(inName,"getText") ) { return hx::Val( getText_dyn()); }
if (HX_FIELD_EQ(inName,"isLocal") ) { return hx::Val( isLocal_dyn()); }
break;
case 8:
if (HX_FIELD_EQ(inName,"getBytes") ) { return hx::Val( getBytes_dyn()); }
if (HX_FIELD_EQ(inName,"getMusic") ) { return hx::Val( getMusic_dyn()); }
if (HX_FIELD_EQ(inName,"getSound") ) { return hx::Val( getSound_dyn()); }
if (HX_FIELD_EQ(inName,"loadFont") ) { return hx::Val( loadFont_dyn()); }
if (HX_FIELD_EQ(inName,"loadText") ) { return hx::Val( loadText_dyn()); }
break;
case 9:
if (HX_FIELD_EQ(inName,"className") ) { return hx::Val( className); }
if (HX_FIELD_EQ(inName,"loadBytes") ) { return hx::Val( loadBytes_dyn()); }
if (HX_FIELD_EQ(inName,"loadMusic") ) { return hx::Val( loadMusic_dyn()); }
if (HX_FIELD_EQ(inName,"loadSound") ) { return hx::Val( loadSound_dyn()); }
break;
case 12:
if (HX_FIELD_EQ(inName,"lastModified") ) { return hx::Val( lastModified); }
if (HX_FIELD_EQ(inName,"loadManifest") ) { return hx::Val( loadManifest_dyn()); }
break;
case 13:
if (HX_FIELD_EQ(inName,"getBitmapData") ) { return hx::Val( getBitmapData_dyn()); }
break;
case 14:
if (HX_FIELD_EQ(inName,"loadBitmapData") ) { return hx::Val( loadBitmapData_dyn()); }
}
return super::__Field(inName,inCallProp);
}
bool DefaultAssetLibrary_obj::__GetStatic(const ::String &inName, Dynamic &outValue, hx::PropertyAccess inCallProp)
{
switch(inName.length) {
case 6:
if (HX_FIELD_EQ(inName,"loaded") ) { outValue = loaded; return true; }
if (HX_FIELD_EQ(inName,"__poll") ) { outValue = _hx___poll_dyn(); return true; }
break;
case 7:
if (HX_FIELD_EQ(inName,"loading") ) { outValue = loading; return true; }
break;
case 8:
if (HX_FIELD_EQ(inName,"__doWork") ) { outValue = _hx___doWork_dyn(); return true; }
break;
case 12:
if (HX_FIELD_EQ(inName,"workerResult") ) { outValue = workerResult; return true; }
if (HX_FIELD_EQ(inName,"workerThread") ) { outValue = workerThread; return true; }
break;
case 19:
if (HX_FIELD_EQ(inName,"workerIncomingQueue") ) { outValue = workerIncomingQueue; return true; }
}
return false;
}
hx::Val DefaultAssetLibrary_obj::__SetField(const ::String &inName,const hx::Val &inValue,hx::PropertyAccess inCallProp)
{
switch(inName.length) {
case 4:
if (HX_FIELD_EQ(inName,"path") ) { path=inValue.Cast< ::haxe::ds::StringMap >(); return inValue; }
if (HX_FIELD_EQ(inName,"type") ) { type=inValue.Cast< ::haxe::ds::StringMap >(); return inValue; }
break;
case 5:
if (HX_FIELD_EQ(inName,"timer") ) { timer=inValue.Cast< ::haxe::Timer >(); return inValue; }
break;
case 9:
if (HX_FIELD_EQ(inName,"className") ) { className=inValue.Cast< ::haxe::ds::StringMap >(); return inValue; }
break;
case 12:
if (HX_FIELD_EQ(inName,"lastModified") ) { lastModified=inValue.Cast< Float >(); return inValue; }
}
return super::__SetField(inName,inValue,inCallProp);
}
bool DefaultAssetLibrary_obj::__SetStatic(const ::String &inName,Dynamic &ioValue,hx::PropertyAccess inCallProp)
{
switch(inName.length) {
case 6:
if (HX_FIELD_EQ(inName,"loaded") ) { loaded=ioValue.Cast< Int >(); return true; }
break;
case 7:
if (HX_FIELD_EQ(inName,"loading") ) { loading=ioValue.Cast< Int >(); return true; }
break;
case 12:
if (HX_FIELD_EQ(inName,"workerResult") ) { workerResult=ioValue.Cast< ::cpp::vm::Deque >(); return true; }
if (HX_FIELD_EQ(inName,"workerThread") ) { workerThread=ioValue.Cast< ::cpp::vm::Thread >(); return true; }
break;
case 19:
if (HX_FIELD_EQ(inName,"workerIncomingQueue") ) { workerIncomingQueue=ioValue.Cast< ::cpp::vm::Deque >(); return true; }
}
return false;
}
void DefaultAssetLibrary_obj::__GetFields(Array< ::String> &outFields)
{
outFields->push(HX_HCSTRING("className","\xa3","\x92","\x3d","\xdc"));
outFields->push(HX_HCSTRING("path","\xa5","\xe5","\x51","\x4a"));
outFields->push(HX_HCSTRING("type","\xba","\xf2","\x08","\x4d"));
outFields->push(HX_HCSTRING("lastModified","\xbf","\xe7","\x59","\x78"));
outFields->push(HX_HCSTRING("timer","\xc5","\xbf","\x35","\x10"));
super::__GetFields(outFields);
};
#if HXCPP_SCRIPTABLE
static hx::StorageInfo DefaultAssetLibrary_obj_sMemberStorageInfo[] = {
{hx::fsObject /*::haxe::ds::StringMap*/ ,(int)offsetof(DefaultAssetLibrary_obj,className),HX_HCSTRING("className","\xa3","\x92","\x3d","\xdc")},
{hx::fsObject /*::haxe::ds::StringMap*/ ,(int)offsetof(DefaultAssetLibrary_obj,path),HX_HCSTRING("path","\xa5","\xe5","\x51","\x4a")},
{hx::fsObject /*::haxe::ds::StringMap*/ ,(int)offsetof(DefaultAssetLibrary_obj,type),HX_HCSTRING("type","\xba","\xf2","\x08","\x4d")},
{hx::fsFloat,(int)offsetof(DefaultAssetLibrary_obj,lastModified),HX_HCSTRING("lastModified","\xbf","\xe7","\x59","\x78")},
{hx::fsObject /*::haxe::Timer*/ ,(int)offsetof(DefaultAssetLibrary_obj,timer),HX_HCSTRING("timer","\xc5","\xbf","\x35","\x10")},
{ hx::fsUnknown, 0, null()}
};
static hx::StaticInfo DefaultAssetLibrary_obj_sStaticStorageInfo[] = {
{hx::fsInt,(void *) &DefaultAssetLibrary_obj::loaded,HX_HCSTRING("loaded","\x05","\x48","\x6f","\x58")},
{hx::fsInt,(void *) &DefaultAssetLibrary_obj::loading,HX_HCSTRING("loading","\x7c","\xce","\xf2","\x08")},
{hx::fsObject /*::cpp::vm::Deque*/ ,(void *) &DefaultAssetLibrary_obj::workerIncomingQueue,HX_HCSTRING("workerIncomingQueue","\x6d","\xe3","\x92","\xfb")},
{hx::fsObject /*::cpp::vm::Deque*/ ,(void *) &DefaultAssetLibrary_obj::workerResult,HX_HCSTRING("workerResult","\xfb","\x7f","\x0b","\x8f")},
{hx::fsObject /*::cpp::vm::Thread*/ ,(void *) &DefaultAssetLibrary_obj::workerThread,HX_HCSTRING("workerThread","\xe8","\x91","\x40","\x15")},
{ hx::fsUnknown, 0, null()}
};
#endif
static ::String DefaultAssetLibrary_obj_sMemberFields[] = {
HX_HCSTRING("className","\xa3","\x92","\x3d","\xdc"),
HX_HCSTRING("path","\xa5","\xe5","\x51","\x4a"),
HX_HCSTRING("type","\xba","\xf2","\x08","\x4d"),
HX_HCSTRING("lastModified","\xbf","\xe7","\x59","\x78"),
HX_HCSTRING("timer","\xc5","\xbf","\x35","\x10"),
HX_HCSTRING("exists","\xdc","\x1d","\xe0","\xbf"),
HX_HCSTRING("getBitmapData","\xef","\x11","\x33","\x90"),
HX_HCSTRING("getBytes","\xf5","\x17","\x6f","\x1d"),
HX_HCSTRING("getFont","\x85","\x0d","\x43","\x16"),
HX_HCSTRING("getMusic","\x2f","\xe0","\x31","\x70"),
HX_HCSTRING("getPath","\x5b","\x95","\xd4","\x1c"),
HX_HCSTRING("getSound","\x59","\x9c","\xa3","\xe0"),
HX_HCSTRING("getText","\x63","\x7c","\x7c","\x1f"),
HX_HCSTRING("isLocal","\x21","\x6d","\x76","\x15"),
HX_HCSTRING("list","\x5e","\x1c","\xb3","\x47"),
HX_HCSTRING("loadBitmapData","\x7f","\xbf","\x71","\xca"),
HX_HCSTRING("loadBytes","\x65","\x54","\xcf","\xd8"),
HX_HCSTRING("loadFont","\x15","\x2f","\x60","\xb4"),
HX_HCSTRING("loadManifest","\xf5","\xe7","\x92","\x89"),
HX_HCSTRING("loadMusic","\x9f","\x1c","\x92","\x2b"),
HX_HCSTRING("loadSound","\xc9","\xd8","\x03","\x9c"),
HX_HCSTRING("loadText","\xf3","\x9d","\x99","\xbd"),
HX_HCSTRING("__load","\x46","\xfd","\xaf","\xf6"),
::String(null()) };
static void DefaultAssetLibrary_obj_sMarkStatics(HX_MARK_PARAMS) {
HX_MARK_MEMBER_NAME(DefaultAssetLibrary_obj::__mClass,"__mClass");
HX_MARK_MEMBER_NAME(DefaultAssetLibrary_obj::loaded,"loaded");
HX_MARK_MEMBER_NAME(DefaultAssetLibrary_obj::loading,"loading");
HX_MARK_MEMBER_NAME(DefaultAssetLibrary_obj::workerIncomingQueue,"workerIncomingQueue");
HX_MARK_MEMBER_NAME(DefaultAssetLibrary_obj::workerResult,"workerResult");
HX_MARK_MEMBER_NAME(DefaultAssetLibrary_obj::workerThread,"workerThread");
};
#ifdef HXCPP_VISIT_ALLOCS
static void DefaultAssetLibrary_obj_sVisitStatics(HX_VISIT_PARAMS) {
HX_VISIT_MEMBER_NAME(DefaultAssetLibrary_obj::__mClass,"__mClass");
HX_VISIT_MEMBER_NAME(DefaultAssetLibrary_obj::loaded,"loaded");
HX_VISIT_MEMBER_NAME(DefaultAssetLibrary_obj::loading,"loading");
HX_VISIT_MEMBER_NAME(DefaultAssetLibrary_obj::workerIncomingQueue,"workerIncomingQueue");
HX_VISIT_MEMBER_NAME(DefaultAssetLibrary_obj::workerResult,"workerResult");
HX_VISIT_MEMBER_NAME(DefaultAssetLibrary_obj::workerThread,"workerThread");
};
#endif
hx::Class DefaultAssetLibrary_obj::__mClass;
static ::String DefaultAssetLibrary_obj_sStaticFields[] = {
HX_HCSTRING("loaded","\x05","\x48","\x6f","\x58"),
HX_HCSTRING("loading","\x7c","\xce","\xf2","\x08"),
HX_HCSTRING("workerIncomingQueue","\x6d","\xe3","\x92","\xfb"),
HX_HCSTRING("workerResult","\xfb","\x7f","\x0b","\x8f"),
HX_HCSTRING("workerThread","\xe8","\x91","\x40","\x15"),
HX_HCSTRING("__doWork","\x1c","\x12","\x30","\xc7"),
HX_HCSTRING("__poll","\x5f","\xe1","\x54","\xf9"),
::String(null())
};
void DefaultAssetLibrary_obj::__register()
{
hx::Static(__mClass) = new hx::Class_obj();
__mClass->mName = HX_HCSTRING("DefaultAssetLibrary","\x2c","\x3d","\x78","\x3a");
__mClass->mSuper = &super::__SGetClass();
__mClass->mConstructEmpty = &__CreateEmpty;
__mClass->mConstructArgs = &__Create;
__mClass->mGetStaticField = &DefaultAssetLibrary_obj::__GetStatic;
__mClass->mSetStaticField = &DefaultAssetLibrary_obj::__SetStatic;
__mClass->mMarkFunc = DefaultAssetLibrary_obj_sMarkStatics;
__mClass->mStatics = hx::Class_obj::dupFunctions(DefaultAssetLibrary_obj_sStaticFields);
__mClass->mMembers = hx::Class_obj::dupFunctions(DefaultAssetLibrary_obj_sMemberFields);
__mClass->mCanCast = hx::TCanCast< DefaultAssetLibrary_obj >;
#ifdef HXCPP_VISIT_ALLOCS
__mClass->mVisitFunc = DefaultAssetLibrary_obj_sVisitStatics;
#endif
#ifdef HXCPP_SCRIPTABLE
__mClass->mMemberStorageInfo = DefaultAssetLibrary_obj_sMemberStorageInfo;
#endif
#ifdef HXCPP_SCRIPTABLE
__mClass->mStaticStorageInfo = DefaultAssetLibrary_obj_sStaticStorageInfo;
#endif
hx::_hx_RegisterClass(__mClass->mName, __mClass);
}
void DefaultAssetLibrary_obj::__boot()
{
{
HX_STACK_FRAME("DefaultAssetLibrary","boot",0xecc8b6b4,"DefaultAssetLibrary.boot","DefaultAssetLibrary.hx",40,0x0fc48912)
HXLINE( 40) loaded = (int)0;
}
{
HX_STACK_FRAME("DefaultAssetLibrary","boot",0xecc8b6b4,"DefaultAssetLibrary.boot","DefaultAssetLibrary.hx",41,0x0fc48912)
HXLINE( 41) loading = (int)0;
}
{
HX_STACK_FRAME("DefaultAssetLibrary","boot",0xecc8b6b4,"DefaultAssetLibrary.boot","DefaultAssetLibrary.hx",42,0x0fc48912)
HXLINE( 42) workerIncomingQueue = ::cpp::vm::Deque_obj::__new();
}
{
HX_STACK_FRAME("DefaultAssetLibrary","boot",0xecc8b6b4,"DefaultAssetLibrary.boot","DefaultAssetLibrary.hx",43,0x0fc48912)
HXLINE( 43) workerResult = ::cpp::vm::Deque_obj::__new();
}
}
| 45.861486 | 271 | 0.676587 | [
"3d"
] |
677e7a75c57900250c2c1b18b2361141273a0e02 | 3,822 | cpp | C++ | source/attributedvertexclouds-blockworld/BlockWorldRendering.cpp | cginternals/attributedvertexclouds | 5173948c6b381528738d128803dc2b22ac555a0f | [
"MIT"
] | 3 | 2017-07-23T21:31:54.000Z | 2018-11-25T02:53:58.000Z | source/attributedvertexclouds-blockworld/BlockWorldRendering.cpp | cginternals/attributedvertexclouds | 5173948c6b381528738d128803dc2b22ac555a0f | [
"MIT"
] | 1 | 2017-08-04T12:03:24.000Z | 2018-02-17T16:44:17.000Z | source/attributedvertexclouds-blockworld/BlockWorldRendering.cpp | cginternals/attributedvertexclouds | 5173948c6b381528738d128803dc2b22ac555a0f | [
"MIT"
] | 1 | 2019-12-13T17:53:14.000Z | 2019-12-13T17:53:14.000Z |
#include "BlockWorldRendering.h"
#include <iostream>
#include <chrono>
#include <algorithm>
#include <glm/gtc/random.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <glbinding/gl/gl.h>
#include "common.h"
#include "BlockWorldVertexCloud.h"
#include "BlockWorldTriangles.h"
#include "BlockWorldTriangleStrip.h"
#include "BlockWorldInstancing.h"
using namespace gl;
BlockWorldRendering::BlockWorldRendering()
: Rendering("BlockWorld")
, m_terrainTexture(0)
, m_blockThreshold(7)
{
}
BlockWorldRendering::~BlockWorldRendering()
{
}
void BlockWorldRendering::onInitialize()
{
addImplementation(new BlockWorldTriangles);
addImplementation(new BlockWorldTriangleStrip);
addImplementation(new BlockWorldInstancing);
addImplementation(new BlockWorldVertexCloud);
glGenTextures(1, &m_terrainTexture);
glBindTexture(GL_TEXTURE_2D_ARRAY, m_terrainTexture);
glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MIN_FILTER, static_cast<GLint>(GL_LINEAR_MIPMAP_LINEAR));
glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MAG_FILTER, static_cast<GLint>(GL_LINEAR));
glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_WRAP_S, static_cast<GLint>(GL_MIRRORED_REPEAT));
glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_WRAP_T, static_cast<GLint>(GL_MIRRORED_REPEAT));
auto terrainData = rawFromFile("data/textures/terrain.512.2048.rgba.ub.raw");
glTexImage3D(GL_TEXTURE_2D_ARRAY, 0, static_cast<GLint>(GL_RGBA8), 512, 512, 4, 0, GL_RGBA, GL_UNSIGNED_BYTE, terrainData.data());
glGenerateMipmap(GL_TEXTURE_2D_ARRAY);
glBindTexture(GL_TEXTURE_2D_ARRAY, 0);
}
void BlockWorldRendering::onDeinitialize()
{
glDeleteTextures(1, &m_terrainTexture);
}
void BlockWorldRendering::onCreateGeometry()
{
const auto blockGridSize = m_gridSize;
const auto blockCount = static_cast<std::size_t>(blockGridSize * blockGridSize * blockGridSize);
const auto worldScale = glm::vec3(1.0f) / glm::vec3(blockGridSize, blockGridSize, blockGridSize);
for (auto implementation : m_implementations)
{
implementation->resize(blockCount);
static_cast<BlockWorldImplementation*>(implementation)->setBlockSize(worldScale.x);
}
std::array<std::vector<float>, 1> noise;
for (auto i = size_t(0); i < noise.size(); ++i)
{
noise[i] = loadNoise("/noise-"+std::to_string(blockGridSize)+"-"+std::to_string(i)+".raw");
}
#pragma omp parallel for
for (size_t i = 0; i < blockCount; ++i)
{
const auto position = glm::ivec3(i % blockGridSize, (i / blockGridSize) % blockGridSize, i / blockGridSize / blockGridSize) - glm::ivec3(blockGridSize / 2, blockGridSize / 2, blockGridSize / 2);
Block b;
b.position = position;
b.type = static_cast<int>(glm::round(16.0f * noise[0][i]));
for (auto implementation : m_implementations)
{
static_cast<BlockWorldImplementation*>(implementation)->setBlock(i, b);
}
}
}
void BlockWorldRendering::onPrepareRendering()
{
GLuint program = m_current->program();
const auto terrainSamplerLocation = glGetUniformLocation(program, "terrain");
const auto blockThresholdLocation = glGetUniformLocation(program, "blockThreshold");
glUseProgram(program);
glUniform1i(terrainSamplerLocation, 0);
glUniform1i(blockThresholdLocation, m_blockThreshold);
glUseProgram(0);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D_ARRAY, m_terrainTexture);
}
void BlockWorldRendering::onFinalizeRendering()
{
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D_ARRAY, 0);
}
void BlockWorldRendering::increaseBlockThreshold()
{
m_blockThreshold = glm::min(m_blockThreshold+1, 14);
}
void BlockWorldRendering::decreaseBlockThreshold()
{
m_blockThreshold = glm::max(m_blockThreshold-1, 0);
}
| 30.094488 | 202 | 0.73888 | [
"vector"
] |
678010ffa792b54f45f0d77c77bc0ca6d14e95d4 | 6,266 | cxx | C++ | main/svx/source/sdr/primitive2d/sdrcaptionprimitive2d.cxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 679 | 2015-01-06T06:34:58.000Z | 2022-03-30T01:06:03.000Z | main/svx/source/sdr/primitive2d/sdrcaptionprimitive2d.cxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 102 | 2017-11-07T08:51:31.000Z | 2022-03-17T12:13:49.000Z | main/svx/source/sdr/primitive2d/sdrcaptionprimitive2d.cxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 331 | 2015-01-06T11:40:55.000Z | 2022-03-14T04:07:51.000Z | /**************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*************************************************************/
#include "precompiled_svx.hxx"
#include <svx/sdr/primitive2d/sdrcaptionprimitive2d.hxx>
#include <basegfx/polygon/b2dpolygontools.hxx>
#include <svx/sdr/primitive2d/sdrdecompositiontools.hxx>
#include <drawinglayer/primitive2d/groupprimitive2d.hxx>
#include <svx/sdr/primitive2d/svx_primitivetypes2d.hxx>
#include <drawinglayer/primitive2d/sdrdecompositiontools2d.hxx>
//////////////////////////////////////////////////////////////////////////////
using namespace com::sun::star;
//////////////////////////////////////////////////////////////////////////////
namespace drawinglayer
{
namespace primitive2d
{
Primitive2DSequence SdrCaptionPrimitive2D::create2DDecomposition(const geometry::ViewInformation2D& /*aViewInformation*/) const
{
Primitive2DSequence aRetval;
// create unit outline polygon
const basegfx::B2DPolygon aUnitOutline(basegfx::tools::createPolygonFromRect(
basegfx::B2DRange(0.0, 0.0, 1.0, 1.0),
getCornerRadiusX(),
getCornerRadiusY()));
// add fill
if(getSdrLFSTAttribute().getFill().isDefault())
{
// create invisible fill for HitTest
appendPrimitive2DReferenceToPrimitive2DSequence(aRetval,
createHiddenGeometryPrimitives2D(
true,
basegfx::B2DPolyPolygon(aUnitOutline),
getTransform()));
}
else
{
basegfx::B2DPolyPolygon aTransformed(aUnitOutline);
aTransformed.transform(getTransform());
appendPrimitive2DReferenceToPrimitive2DSequence(aRetval,
createPolyPolygonFillPrimitive(
aTransformed,
getSdrLFSTAttribute().getFill(),
getSdrLFSTAttribute().getFillFloatTransGradient()));
}
// add line
if(getSdrLFSTAttribute().getLine().isDefault())
{
// create invisible line for HitTest/BoundRect
appendPrimitive2DReferenceToPrimitive2DSequence(aRetval,
createHiddenGeometryPrimitives2D(
false,
basegfx::B2DPolyPolygon(aUnitOutline),
getTransform()));
appendPrimitive2DReferenceToPrimitive2DSequence(aRetval,
createHiddenGeometryPrimitives2D(
false,
basegfx::B2DPolyPolygon(getTail()),
getTransform()));
}
else
{
basegfx::B2DPolygon aTransformed(aUnitOutline);
aTransformed.transform(getTransform());
appendPrimitive2DReferenceToPrimitive2DSequence(aRetval,
createPolygonLinePrimitive(
aTransformed,
getSdrLFSTAttribute().getLine(),
attribute::SdrLineStartEndAttribute()));
aTransformed = getTail();
aTransformed.transform(getTransform());
appendPrimitive2DReferenceToPrimitive2DSequence(aRetval,
createPolygonLinePrimitive(
aTransformed,
getSdrLFSTAttribute().getLine(),
getSdrLFSTAttribute().getLineStartEnd()));
}
// add text
if(!getSdrLFSTAttribute().getText().isDefault())
{
appendPrimitive2DReferenceToPrimitive2DSequence(aRetval,
createTextPrimitive(
basegfx::B2DPolyPolygon(aUnitOutline),
getTransform(),
getSdrLFSTAttribute().getText(),
getSdrLFSTAttribute().getLine(),
false,
false,
false));
}
// add shadow
if(!getSdrLFSTAttribute().getShadow().isDefault())
{
aRetval = createEmbeddedShadowPrimitive(aRetval, getSdrLFSTAttribute().getShadow());
}
return aRetval;
}
SdrCaptionPrimitive2D::SdrCaptionPrimitive2D(
const basegfx::B2DHomMatrix& rTransform,
const attribute::SdrLineFillShadowTextAttribute& rSdrLFSTAttribute,
const basegfx::B2DPolygon& rTail,
double fCornerRadiusX,
double fCornerRadiusY)
: BufferedDecompositionPrimitive2D(),
maTransform(rTransform),
maSdrLFSTAttribute(rSdrLFSTAttribute),
maTail(rTail),
mfCornerRadiusX(fCornerRadiusX),
mfCornerRadiusY(fCornerRadiusY)
{
// transform maTail to unit polygon
if(getTail().count())
{
basegfx::B2DHomMatrix aInverse(getTransform());
aInverse.invert();
maTail.transform(aInverse);
}
}
bool SdrCaptionPrimitive2D::operator==(const BasePrimitive2D& rPrimitive) const
{
if(BufferedDecompositionPrimitive2D::operator==(rPrimitive))
{
const SdrCaptionPrimitive2D& rCompare = (SdrCaptionPrimitive2D&)rPrimitive;
return (getCornerRadiusX() == rCompare.getCornerRadiusX()
&& getCornerRadiusY() == rCompare.getCornerRadiusY()
&& getTail() == rCompare.getTail()
&& getTransform() == rCompare.getTransform()
&& getSdrLFSTAttribute() == rCompare.getSdrLFSTAttribute());
}
return false;
}
// provide unique ID
ImplPrimitrive2DIDBlock(SdrCaptionPrimitive2D, PRIMITIVE2D_ID_SDRCAPTIONPRIMITIVE2D)
} // end of namespace primitive2d
} // end of namespace drawinglayer
//////////////////////////////////////////////////////////////////////////////
// eof
| 35.005587 | 129 | 0.618736 | [
"geometry",
"transform"
] |
67823ad7d472d1ca25ab1f66cf59053a446ff77e | 406 | cpp | C++ | Majority Element II.cpp | jatinmalav/leetcoding-problems | 420bf572f2db378c203adaf771e0d7e60f2f3579 | [
"Unlicense"
] | 5 | 2020-10-06T13:10:04.000Z | 2021-06-07T02:07:59.000Z | Majority Element II.cpp | jatinmalav/leetcoding-problems | 420bf572f2db378c203adaf771e0d7e60f2f3579 | [
"Unlicense"
] | 5 | 2020-10-05T17:23:57.000Z | 2020-10-10T12:56:15.000Z | Majority Element II.cpp | jatinmalav/leetcoding-problems | 420bf572f2db378c203adaf771e0d7e60f2f3579 | [
"Unlicense"
] | 43 | 2020-10-05T17:31:56.000Z | 2020-10-29T23:47:53.000Z | //https://leetcode.com/problems/majority-element-ii/
class Solution {
public:
vector<int> majorityElement(vector<int>& nums) {
unordered_map<int,int>mp;
vector<int>v;
for(int i=0;i<nums.size();i++)
{
mp[nums[i]]++;
}
for(auto x:mp)
{
if(x.second> nums.size()/3) v.push_back(x.first);
}
return v;
}
};
| 21.368421 | 61 | 0.502463 | [
"vector"
] |
6788ee1f9988ac0f81f6ae04d1bd66a164783591 | 3,472 | cc | C++ | module/svg/src/svg/svg_root.cc | RuiwenTang/Skity | 2f98d8bda9946a9055d955fae878fef43c4eee57 | [
"MIT"
] | 65 | 2021-08-05T09:52:49.000Z | 2022-03-29T14:45:20.000Z | module/svg/src/svg/svg_root.cc | RuiwenTang/Skity | 2f98d8bda9946a9055d955fae878fef43c4eee57 | [
"MIT"
] | 1 | 2022-03-24T09:35:06.000Z | 2022-03-25T06:38:20.000Z | module/svg/src/svg/svg_root.cc | RuiwenTang/Skity | 2f98d8bda9946a9055d955fae878fef43c4eee57 | [
"MIT"
] | 9 | 2021-08-08T07:30:13.000Z | 2022-03-29T14:45:25.000Z |
#include "src/svg/svg_root.hpp"
#include <glm/gtc/matrix_transform.hpp>
#include <skity/render/canvas.hpp>
#include "src/svg/svg_render_context.hpp"
namespace skity {
bool SVGRoot::OnPrepareToRender(SVGRenderContext* ctx) const {
auto viewPortRect =
ctx->GetLengthContext().ResolveRect(fX, fY, fWidth, fHeight);
auto contentMatrix = glm::translate(
glm::identity<Matrix>(), {viewPortRect.x(), viewPortRect.y(), 0.f});
auto viewPort = Vec2{viewPortRect.width(), viewPortRect.height()};
if (fViewBox.IsValid()) {
const Rect& viewBox = *fViewBox;
// An empty viewBox disables rendering.
if (viewBox.isEmpty()) {
return false;
}
// a viewBox overrides the intrinsic viewport
contentMatrix = contentMatrix * ComputeViewBoxMatrix(viewBox, viewPortRect,
fPreserveAspectRatio);
}
if (contentMatrix != glm::identity<Matrix>()) {
ctx->SaveOnce();
ctx->GetCanvas()->concat(contentMatrix);
}
if (viewPort != ctx->GetLengthContext().ViewPort()) {
ctx->WritableLengthContext()->SetViewPort(viewPort);
}
return SVGContainer::OnPrepareToRender(ctx);
}
void SVGRoot::OnSetAttribute(SVGAttribute attr, const SVGValue& value) {
switch (attr) {
case SVGAttribute::kX:
if (const auto* x = value.As<SVGLengthValue>()) {
this->SetX(static_cast<const SVGLength&>(*x));
}
break;
case SVGAttribute::kY:
if (const auto* y = value.As<SVGLengthValue>()) {
this->SetY(static_cast<const SVGLength&>(*y));
}
break;
case SVGAttribute::kWidth:
if (const auto* w = value.As<SVGLengthValue>()) {
this->SetWidth(static_cast<const SVGLength&>(*w));
}
break;
case SVGAttribute::kHeight:
if (const auto* h = value.As<SVGLengthValue>()) {
this->SetHeight(static_cast<const SVGLength&>(*h));
}
break;
case SVGAttribute::kViewBox:
if (const auto* vb = value.As<SVGViewBoxValue>()) {
this->SetViewBox(static_cast<const SVGViewBoxType&>(*vb));
}
break;
case SVGAttribute::kPreserveAspectRatio:
if (const auto* par = value.As<SVGPreserveAspectRatioValue>()) {
this->SetPreserveAspectRatio(
static_cast<const SVGPreserveAspectRatio&>(*par));
}
break;
default:
SVGContainer::OnSetAttribute(attr, value);
break;
}
}
// https://www.w3.org/TR/SVG11/coords.html#IntrinsicSizing
Vec2 SVGRoot::IntrinsicSize(const SVGLengthContext& ctx) const {
// percentage values do not provide an intrinsic size.
if (fWidth.unit() == SVGLength::Unit::kPercentage ||
fHeight.unit() == SVGLength::Unit::kPercentage) {
return Vec2{0, 0};
}
return Vec2{ctx.Resolve(fWidth, SVGLengthContext::LengthType::kHorizontal),
ctx.Resolve(fHeight, SVGLengthContext::LengthType::kVertical)};
}
const char* SVGRoot::TagName() const { return "svg"; }
bool SVGRoot::ParseAndSetAttribute(const char* name, const char* value) {
// unused ignore attribute
if (std::strcmp(name, "version") == 0) {
return true;
} else if (std::strcmp(name, "xmlns") == 0) {
return true;
}
return SVGNode::ParseAndSetAttribute(name, value) ||
this->SetWidth(
SVGAttributeParser::Parse<SVGLength>("width", name, value)) ||
this->SetHeight(
SVGAttributeParser::Parse<SVGLength>("height", name, value));
}
} // namespace skity
| 31.279279 | 79 | 0.645449 | [
"render"
] |
678cd3abc3d0aa29a1a18ba555881f3c63056ce9 | 471 | cpp | C++ | compilecpp.cpp | numfo/tryme | 596b48160cc1c2377bee05675570f62df4f37d9d | [
"MIT"
] | null | null | null | compilecpp.cpp | numfo/tryme | 596b48160cc1c2377bee05675570f62df4f37d9d | [
"MIT"
] | null | null | null | compilecpp.cpp | numfo/tryme | 596b48160cc1c2377bee05675570f62df4f37d9d | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
#include <string>
using namespace std;
int main(){
cout <<"It works"<<endl;
string name{"Doe Bog"};
//int count{10};
auto age(10);
cout <<"I am"<<age<<"years old"<<endl;
int ages = 7;
bool birth = age >19?true:false;
cout<<"can give birth: " <<birth<<endl;
for(int i = 0; i <10;i++){
cout<<"Yes we can"<<endl;
}
}
template<class T,class k>
k sums(T a,T b){
return a+b;
} | 16.821429 | 43 | 0.547771 | [
"vector"
] |
678d256faccba2cedf34cf92c3275b4e8e9a84a7 | 8,474 | hpp | C++ | data_analytics/L2/demos/text/log_analyzer/ref_result/ref_result.hpp | vmayoral/Vitis_Libraries | 2323dc5036041e18242718287aee4ce66ba071ef | [
"Apache-2.0"
] | 1 | 2021-09-11T01:05:01.000Z | 2021-09-11T01:05:01.000Z | data_analytics/L2/demos/text/log_analyzer/ref_result/ref_result.hpp | vmayoral/Vitis_Libraries | 2323dc5036041e18242718287aee4ce66ba071ef | [
"Apache-2.0"
] | null | null | null | data_analytics/L2/demos/text/log_analyzer/ref_result/ref_result.hpp | vmayoral/Vitis_Libraries | 2323dc5036041e18242718287aee4ce66ba071ef | [
"Apache-2.0"
] | 1 | 2021-04-28T05:58:38.000Z | 2021-04-28T05:58:38.000Z | /*
* Copyright 2020 Xilinx, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "grok.hpp"
#include "geoip2.hpp"
#include <fstream>
#include <vector>
#include "x_utils.hpp"
#include "rapidjson/writer.h"
#include "rapidjson/stringbuffer.h"
using namespace x_utils;
const std::string geoip2FN[] = {
"postal_code", "latitude", "longitude", "accuracy_radius", "continent_code",
"continent_name", "country_iso_code", "country_name", "subdivision_1_iso_code", "subdivision_1_name",
"city_name", "metro_code", "time_zone"};
const int idFN[] = {0x7, 0x12, 0x13, 0x11, 0x1, 0x0, 0x3, 0x2, 0x5, 0x4, 0x6, 0x10, 0x8};
int refCalcu(std::string msg_path,
std::string pattern,
std::string geoip_path,
uint8_t* test_result = NULL,
std::string json_path = "") {
int nerr = 0;
// init
const int subNum = 13;
std::string fieldName[] = {
"remote", "host", "user", "time", "method", "path", "code", "size", "referer", "agent", "http_x_forwarded_for"};
regex_t* reg;
OnigRegion* region;
region = onig_region_new();
OnigErrorInfo einfo;
OnigEncoding use_encs[1];
use_encs[0] = ONIG_ENCODING_ASCII;
onig_initialize(use_encs, sizeof(use_encs) / sizeof(use_encs[0]));
UChar* pattern_c = (UChar*)pattern.c_str();
int r = onig_new(®, pattern_c, pattern_c + strlen((char*)pattern_c), ONIG_OPTION_DEFAULT, ONIG_ENCODING_ASCII,
ONIG_SYNTAX_DEFAULT, &einfo);
if (r != ONIG_NORMAL) {
char s[ONIG_MAX_ERROR_MESSAGE_LEN];
onig_error_code_to_str((UChar*)s, r, &einfo);
fprintf(stderr, "ERROR: %s\n", s);
return -1;
}
std::string ip_address = "192.168.2.1";
MMDB_s mmdb;
int status = MMDB_open(geoip_path.c_str(), MMDB_MODE_MMAP, &mmdb);
if (MMDB_SUCCESS != status) {
fprintf(stderr, "\n Can't open %s - %s\n", geoip_path.c_str(), MMDB_strerror(status));
if (MMDB_IO_ERROR == status) {
fprintf(stderr, " IO error: %s\n", strerror(errno));
}
exit(1);
}
int exit_code = 0;
MMDB_entry_data_s entry_data;
MMDB_entry_data_list_s* entry_data_list = NULL;
char buffer[20];
int gai_error, mmdb_error;
uint16_t resInt;
double resDlb;
uint32_t* offsets = (uint32_t*)malloc(sizeof(uint32_t) * subNum);
// core
struct timeval start_time, end_time;
gettimeofday(&start_time, 0);
// read file
// std::cout << "read file: " << msg_path << "\n";
std::string lineStr;
int msg_num = 0;
std::vector<std::string> msgs;
std::ifstream inFile(msg_path, std::ios::in);
while (getline(inFile, lineStr)) {
msgs.push_back(lineStr);
msg_num++;
}
// std::cout << "msg_num = " << msg_num << std::endl;
uint64_t char_cnt = 8;
uint64_t char_cnt_last = 8;
int mismatch_flag = 0, mismatch_cnt = 0;
int geoip_err_flag = 0;
std::string outjsons = "";
uint64_t input_size = 0;
std::cout << "msg num=" << msg_num << std::endl;
for (int m = 0; m < msg_num; m++) {
std::string msg = msgs[m];
if (msg.size() == 0 || msg.size() > 4090) continue;
input_size += msg.size();
mismatch_flag = 0;
geoip_err_flag = 0;
char onejson[10240];
rapidjson::StringBuffer s;
rapidjson::Writer<rapidjson::StringBuffer> writer(s);
writer.StartObject();
offsets[0] = 0;
regexTop(subNum, reg, region, (UChar*)msg.c_str(), offsets);
if (offsets[0] > 0 && offsets[0] <= subNum) {
for (int j = 2; j < subNum; j++) {
uint32_t tmp = offsets[j];
uint32_t begin = tmp % N16;
uint32_t end = tmp / N16;
if (j == 2) ip_address = msg.substr(begin, end - begin);
writer.Key(fieldName[j - 2].c_str());
writer.String(msg.substr(begin, end - begin).c_str());
}
MMDB_lookup_result_s result = MMDB_lookup_string(&mmdb, ip_address.c_str(), &gai_error, &mmdb_error);
if ((0 != gai_error) || (MMDB_SUCCESS != mmdb_error) || (!result.found_entry)) {
// std::cout << "ip_address=" << ip_address << ",\n msg=" << msg << std::endl;
writer.Key("tag");
writer.String("geoip_failure");
geoip_err_flag = 1;
}
if (geoip_err_flag == 0 && result.found_entry) {
writer.Key("geoip");
writer.StartObject();
for (int i = 0; i < 13; i++) {
int id_fn = idFN[i];
if (id_fn >> 4) {
if (0 == getDecValue(entry_data, result, id_fn & 0xF, resInt, resDlb)) {
writer.Key(geoip2FN[i].c_str());
if ((id_fn & 0xF) < 2) {
writer.Uint(resInt);
} else {
writer.Double(resDlb);
}
}
} else {
if (0 == getStrValue(entry_data, result, id_fn & 0xF, buffer)) {
writer.Key(geoip2FN[i].c_str());
writer.String(buffer);
}
}
}
writer.EndObject();
}
} else {
writer.Key("tag");
writer.String("grok_failure");
}
writer.EndObject();
#ifndef BS_TEST
std::string tmp = s.GetString();
tmp += "\n";
uint8_t* tmp_dec = (uint8_t*)tmp.data();
for (int i = 0; i < tmp.length(); i++) {
if (test_result[char_cnt] != tmp_dec[i]) {
while (tmp_dec[i] == '\\') i++;
if (test_result[char_cnt] != tmp_dec[i]) {
mismatch_flag = 1;
mismatch_cnt++;
std::cout << "\n\nm = " << m << ", mismatch_cnt=" << mismatch_cnt
<< ", ratio=" << mismatch_cnt * 100.0 / m << std::endl;
std::cout << "ERROR: test[" << char_cnt << "]=" << test_result[char_cnt] << ", golden[" << m << "]["
<< i << "]=" << tmp_dec[i] << std::endl;
nerr++;
break;
}
}
char_cnt++;
}
if (mismatch_flag) {
for (int i = 0; i < 10239; i++) {
if (test_result[char_cnt_last + i] != '\n') {
onejson[i] = test_result[char_cnt_last + i];
} else {
onejson[i] = test_result[char_cnt_last + i];
onejson[i + 1] = '\0';
char_cnt_last += i + 1;
break;
}
}
char_cnt = char_cnt_last;
std::cout << "out json line is \n" << onejson << std::endl;
std::cout << "ref json line is \n" << s.GetString() << std::endl;
} else {
char_cnt_last = char_cnt;
}
#else
// std::cout << s.GetString() << std::endl;
outjsons += s.GetString();
outjsons += "\n";
#endif
}
#ifdef BS_TEST
gettimeofday(&end_time, 0);
std::cout << "Execution time " << tvdiff(start_time, end_time) / 1000.0 << " ms" << std::endl;
std::cout << "Input Size " << input_size / 1000000.0 << "MB, Throughput "
<< input_size / (tvdiff(start_time, end_time) / 1.0) << " MB/s\n";
std::fstream f(json_path.c_str(), std::ios::out);
f << outjsons;
// std::cout << outjsons;
f.close();
MMDB_free_entry_data_list(entry_data_list);
MMDB_close(&mmdb);
exit(exit_code);
onig_region_free(region, 1 /* 1:free self, 0:free contents only */);
onig_free(reg);
onig_end();
#endif
return nerr;
}
| 37.662222 | 120 | 0.519707 | [
"vector"
] |
678df47481f53ddf092f99f7fdc1464807ad70ba | 2,200 | cpp | C++ | cpp/Mobil Phone/Mobil Phone.cpp | xuzishan/Algorithm-learning-through-Problems | 4aee347af6fd7fd935838e1cbea57c197e88705c | [
"MIT"
] | 27 | 2016-11-04T09:18:25.000Z | 2022-02-12T12:34:01.000Z | cpp/Mobil Phone/Mobil Phone.cpp | Der1128/Algorithm-learning-through-Problems | 4aee347af6fd7fd935838e1cbea57c197e88705c | [
"MIT"
] | 1 | 2016-11-05T02:30:24.000Z | 2016-11-16T10:21:09.000Z | cpp/Mobil Phone/Mobil Phone.cpp | Der1128/Algorithm-learning-through-Problems | 4aee347af6fd7fd935838e1cbea57c197e88705c | [
"MIT"
] | 20 | 2016-11-04T10:26:02.000Z | 2021-09-25T05:41:21.000Z | //
// Mobil Phone.cpp
// laboratory
//
// Created by 徐子珊 on 15/12/22.
// Copyright © 2015年 xu_zishan. All rights reserved.
//
#include <fstream>
#include <iostream>
#include <vector>
#include <string>
using namespace std;
#include "../filepath.h"
struct command {
int c, x, y, z, w;
command(int a, int b=0, int c=0, int d=0, int e=0){
this->c=a;
this->x=b;
this->y=c;
this->z=d;
this->w=e;
}
};
vector<int> mobilPhone(const vector<command>& cmds){
const int n=int(cmds.size());
const int S=int(cmds[0].x);
vector<vector<int>> tempere(S, vector<int>(S));
vector<int> result;
for (int k=1; k<n; k++) {
const int cmd=cmds[k].c;
if (cmd==1) {
const int x=cmds[k].x, y=cmds[k].y, a=cmds[k].z;
tempere[x][y]+=a;
if (tempere[x][y]<0)
tempere[x][y]=0;
}else{
const int L=cmds[k].x, B=cmds[k].y, R=cmds[k].z, T=cmds[k].w;
int count=0;
for (int i=L; i<=R; i++)
for (int j=B; j<=T; j++)
count+=tempere[i][j];
result.push_back(count);
}
}
return result;
}
int main(){
ifstream inputdata(basePath+"Mobil Phone/inputdata.txt");
ofstream outputdata(basePath+"Mobil Phone/outputdata.txt");
vector<command> cmds;
int cmd;
inputdata>>cmd;
while (cmd != 3){
switch (cmd) {
case 0:
int S;
inputdata>>S;
cmds.push_back(command(cmd, S));
break;
case 1:
int X, Y, A;
inputdata>>X>>Y>>A;
cmds.push_back(command(cmd, X, Y, A));
break;
case 2:
int L, B, R, T;
inputdata>>L>>B>>R>>T;
cmds.push_back(command(cmd, L, B, R, T));
default:
break;
}
inputdata>>cmd;
}
vector<int> result=mobilPhone(cmds);
for (int i=0; i< result.size(); i++) {
cout<<result[i]<<endl;
outputdata<<result[i]<<endl;
}
inputdata.close();
outputdata.close();
return 0;
} | 26.506024 | 73 | 0.475909 | [
"vector"
] |
096ef37e987e101a19d309329455a9cf1894e032 | 8,717 | hpp | C++ | core/sceneManager/network/3rdParty/raknet/DependentExtensions/cat/gfx/Vector.hpp | wterkaj/ApertusVR | 424ec5515ae08780542f33cc4841a8f9a96337b3 | [
"MIT"
] | 158 | 2016-11-17T19:37:51.000Z | 2022-03-21T19:57:55.000Z | core/sceneManager/network/3rdParty/raknet/DependentExtensions/cat/gfx/Vector.hpp | wterkaj/ApertusVR | 424ec5515ae08780542f33cc4841a8f9a96337b3 | [
"MIT"
] | 94 | 2016-11-18T09:55:57.000Z | 2021-01-14T08:50:40.000Z | core/sceneManager/network/3rdParty/raknet/DependentExtensions/cat/gfx/Vector.hpp | wterkaj/ApertusVR | 424ec5515ae08780542f33cc4841a8f9a96337b3 | [
"MIT"
] | 60 | 2015-02-17T00:12:11.000Z | 2021-08-21T22:16:58.000Z | /*
Copyright (c) 2009 Christopher A. Taylor. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of LibCat nor the names of its contributors may be used
to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef CAT_VECTOR_HPP
#define CAT_VECTOR_HPP
#include <cat/gfx/Scalar.hpp>
namespace cat {
#define FOR_EACH_DIMENSION(index) for (int index = 0; index < DIM; ++index)
// Generic vector class for linear algebra
template<int DIM, typename Scalar, typename Double> class Vector
{
protected:
// Protected internal storage of vector components
Scalar _elements[DIM];
public:
// Short-hand for the current vector type
typedef Vector<DIM, Scalar, Double> mytype;
// Uninitialized vector is not cleared
Vector() {}
// Component-wise initializing constructors
Vector(Scalar x, Scalar y)
{
_elements[0] = x;
_elements[1] = y;
}
Vector(Scalar x, Scalar y, Scalar z)
{
_elements[0] = x;
_elements[1] = y;
_elements[2] = z;
}
Vector(Scalar x, Scalar y, Scalar z, Scalar w)
{
_elements[0] = x;
_elements[1] = y;
_elements[2] = z;
_elements[3] = w;
}
// Make the vector a copy of a given vector
mytype ©(const mytype &u)
{
memcpy(_elements, u._elements, sizeof(_elements));
return *this;
}
// Copy constructor
Vector(const mytype &u)
{
copy(u);
}
// Assignment operator
mytype &operator=(const mytype &u)
{
return copy(u);
}
// Magnitude calculation
Double magnitude() const
{
Double element, sum = 0;
FOR_EACH_DIMENSION(ii)
{
element = _elements[ii];
sum += element * element;
}
return static_cast<Double>( sqrt(sum) );
}
// Fast normalization for 32-bit floating point elements in-place
mytype &normalize_fast_f32()
{
f32 element = _elements[0];
f32 sum = element * element;
for (int ii = 1; ii < DIM; ++ii)
{
element = _elements[ii];
sum += element * element;
}
// If sum is not close to 1, then perform normalization:
if (sum > 1.005f || sum < 0.995f)
{
f32 inv = InvSqrt(sum);
FOR_EACH_DIMENSION(ii) _elements[ii] *= inv;
}
return *this;
}
// Normalization in-place
mytype &normalize()
{
Double m = magnitude();
Double inv = static_cast<Double>( 1 ) / m;
FOR_EACH_DIMENSION(ii) _elements[ii] *= inv;
return *this;
}
// Zero elements
void zero()
{
OBJCLR(_elements);
}
// Is zero?
bool isZero()
{
FOR_EACH_DIMENSION(ii)
if (_elements[ii] != static_cast<Scalar>( 0 ))
return false;
return true;
}
// For consistency with Matrix class, use the () operator instead of [] to index it
inline Scalar &operator()(int ii) { return _elements[ii]; }
inline Scalar &x() { return _elements[0]; }
inline Scalar &y() { return _elements[1]; }
inline Scalar &z() { return _elements[2]; }
inline Scalar &w() { return _elements[3]; }
// Const version for accessors
inline const Scalar &operator()(int ii) const { return _elements[ii]; }
inline const Scalar &x() const { return _elements[0]; }
inline const Scalar &y() const { return _elements[1]; }
inline const Scalar &z() const { return _elements[2]; }
inline const Scalar &w() const { return _elements[3]; }
// Negation
mytype operator-() const
{
mytype x;
FOR_EACH_DIMENSION(ii) x._elements[ii] = -_elements[ii];
return x;
}
// Negation in-place
mytype &negate()
{
FOR_EACH_DIMENSION(ii) _elements[ii] = -_elements[ii];
return *this;
}
// Addition
mytype operator+(const mytype &u) const
{
mytype x;
FOR_EACH_DIMENSION(ii) x._elements[ii] = _elements[ii] + u._elements[ii];
return x;
}
// Addition in-place
mytype &operator+=(const mytype &u)
{
FOR_EACH_DIMENSION(ii) _elements[ii] += u._elements[ii];
return *this;
}
// Add a scalar to each element in-place
mytype &addToEachElement(Scalar u)
{
FOR_EACH_DIMENSION(ii) _elements[ii] += u;
return *this;
}
// Subtraction
mytype operator-(const mytype &u) const
{
mytype x;
FOR_EACH_DIMENSION(ii) x._elements[ii] = _elements[ii] - u._elements[ii];
return x;
}
// Subtraction in-place
mytype &operator-=(const mytype &u)
{
FOR_EACH_DIMENSION(ii) _elements[ii] -= u._elements[ii];
return *this;
}
// Subtract a scalar from each element in-place
mytype &subtractFromEachElement(Scalar u)
{
FOR_EACH_DIMENSION(ii) _elements[ii] -= u;
return *this;
}
// Scalar multiplication
mytype operator*(Scalar u) const
{
mytype x;
FOR_EACH_DIMENSION(ii) x._elements[ii] = u * _elements[ii];
return x;
}
// Scalar multiplication in-place
mytype &operator*=(Scalar u)
{
FOR_EACH_DIMENSION(ii) _elements[ii] *= u;
return *this;
}
// Component-wise multiply in-place
mytype &componentMultiply(const mytype &u)
{
FOR_EACH_DIMENSION(ii) _elements[ii] *= u._elements[ii];
return *this;
}
// Scalar division
mytype operator/(Scalar u) const
{
mytype x;
Scalar inv_u = static_cast<Scalar>( 1 ) / static_cast<Scalar>( u );
FOR_EACH_DIMENSION(ii) x._elements[ii] = _elements[ii] * inv_u;
return x;
}
// Scalar division in-place
mytype &operator/=(Scalar u)
{
Scalar inv_u = static_cast<Scalar>( 1 ) / static_cast<Scalar>( u );
FOR_EACH_DIMENSION(ii) _elements[ii] *= inv_u;
return *this;
}
// Component-wise divide in-place
mytype &componentDivide(const mytype &u)
{
FOR_EACH_DIMENSION(ii) _elements[ii] /= u._elements[ii];
return *this;
}
// Dot product
Double dotProduct(const mytype &u) const
{
Double sum = 0;
FOR_EACH_DIMENSION(ii)
sum += static_cast<Double>( _elements[ii] )
* static_cast<Double>( u._elements[ii] );
return sum;
}
public:
// Only for 2-element vectors:
// Generate a 2D rotation vector in-place
void generateRotation2D(f32 angle)
{
x() = cos(angle);
y() = sin(angle);
}
// Add rotation vector in-place
mytype &addRotation2D(const mytype &r)
{
Double ax = x(), ay = y();
Double rx = r.x(), ry = r.y();
x() = static_cast<Scalar>( ax*rx - ay*ry ); // cos(a+r) = cos(a)*cos(r) - sin(a)*sin(r)
y() = static_cast<Scalar>( ay*rx + ax*ry ); // sin(a+r) = sin(a)*cos(r) + cos(a)*sin(r)
return *this;
}
// Subtract rotation vector in-place
mytype &subtractRotation2D(const mytype &r)
{
Double ax = x(), ay = y();
Double rx = r.x(), ry = r.y();
x() = static_cast<Scalar>( ax*rx + ay*ry ); // cos(a-r) = cos(a)*cos(r) + sin(a)*sin(r)
y() = static_cast<Scalar>( ay*rx - ax*ry ); // sin(a-r) = sin(a)*cos(r) - cos(a)*sin(r)
return *this;
}
// Cross product: Result is a scalar
f32 crossProduct2D(const mytype &u)
{
return x() * u.y() - y() * u.x();
}
public:
// Only for 3-element vectors:
// Cross product: Result is a 3D vector
mytype crossProduct3D(const mytype &u)
{
mytype result;
result.x() = y() * u.z() - z() * u.y();
result.y() = z() * u.x() - x() * u.z();
result.z() = x() * u.y() - y() * u.x();
return result;
}
};
// Short-hand for common usages:
typedef Vector<2, u32, u32> Vector2u;
typedef Vector<3, u32, u32> Vector3u;
typedef Vector<4, u32, u32> Vector4u;
typedef Vector<2, s32, s32> Vector2s;
typedef Vector<3, s32, s32> Vector3s;
typedef Vector<4, s32, s32> Vector4s;
typedef Vector<2, f32, f64> Vector2f;
typedef Vector<3, f32, f64> Vector3f;
typedef Vector<4, f32, f64> Vector4f;
typedef Vector<2, f64, f64> Vector2d;
typedef Vector<3, f64, f64> Vector3d;
typedef Vector<4, f64, f64> Vector4d;
#undef FOR_EACH_DIMENSION
} // namespace cat
#endif // CAT_VECTOR_HPP
| 22.351282 | 89 | 0.676494 | [
"vector",
"3d"
] |
09765172776eaa815a364bc12d729d83bf59a92e | 2,969 | cpp | C++ | packages/PyFrensie/src/PyFrensie_PythonTypeTraits.cpp | bam241/FRENSIE | e1760cd792928699c84f2bdce70ff54228e88094 | [
"BSD-3-Clause"
] | 10 | 2019-11-14T19:58:30.000Z | 2021-04-04T17:44:09.000Z | packages/PyFrensie/src/PyFrensie_PythonTypeTraits.cpp | bam241/FRENSIE | e1760cd792928699c84f2bdce70ff54228e88094 | [
"BSD-3-Clause"
] | 43 | 2020-03-03T19:59:20.000Z | 2021-09-08T03:36:08.000Z | packages/PyFrensie/src/PyFrensie_PythonTypeTraits.cpp | bam241/FRENSIE | e1760cd792928699c84f2bdce70ff54228e88094 | [
"BSD-3-Clause"
] | 6 | 2020-02-12T17:37:07.000Z | 2020-09-08T18:59:51.000Z | //---------------------------------------------------------------------------//
//!
//! \file PyFrensie_PythonTypeTraits.cpp
//! \author Alex Robinson
//! \brief The Python type traits helper function definitions
//!
//---------------------------------------------------------------------------//
// FRENSIE Includes
#include "PyFrensie_PythonTypeTraits.hpp"
namespace PyFrensie{
namespace Details{
// Get the type code string (useful for exception messages)
const char* typecodeString(int typecode)
{
static const char* type_names[25] = {"bool",
"byte",
"unsigned byte",
"short",
"unsigned short",
"int",
"unsigned int",
"long",
"unsigned long",
"long long",
"unsigned long long",
"float",
"double",
"long double",
"complex float",
"complex double",
"complex long double",
"object",
"string",
"unicode",
"void",
"ntypes",
"notype",
"char",
"unknown"};
return typecode < 24 ? type_names[typecode] : type_names[24];
}
// Get the PyObject type string (useful for exception messages)_
const char* pytypeString( PyObject* py_obj )
{
if (py_obj == NULL ) return "C NULL value";
if (py_obj == Py_None ) return "Python None" ;
if (PyCallable_Check(py_obj)) return "callable" ;
if (PyString_Check( py_obj)) return "string" ;
if (PyInt_Check( py_obj)) return "int" ;
if (PyFloat_Check( py_obj)) return "float" ;
if (PyDict_Check( py_obj)) return "dict" ;
if (PyList_Check( py_obj)) return "list" ;
if (PyTuple_Check( py_obj)) return "tuple" ;
if (PyFile_Check( py_obj)) return "file" ;
if (PyModule_Check( py_obj)) return "module" ;
if (PyInstance_Check(py_obj)) return "instance" ;
}
} // end Details namespace
} // end PyFrensie namespace
//---------------------------------------------------------------------------//
// PyFrensie_PythonTypeTraits.cpp
//---------------------------------------------------------------------------//
| 41.236111 | 79 | 0.363422 | [
"object"
] |
0977134fbd2333c995c44b67ea5f0b99bf5c7553 | 25,814 | cpp | C++ | qt-creator-opensource-src-4.6.1/src/plugins/bookmarks/bookmarkmanager.cpp | kevinlq/Qt-Creator-Opensource-Study | b8cadff1f33f25a5d4ef33ed93f661b788b1ba0f | [
"MIT"
] | 5 | 2018-12-22T14:49:13.000Z | 2022-01-13T07:21:46.000Z | qt-creator-opensource-src-4.6.1/src/plugins/bookmarks/bookmarkmanager.cpp | kevinlq/Qt-Creator-Opensource-Study | b8cadff1f33f25a5d4ef33ed93f661b788b1ba0f | [
"MIT"
] | null | null | null | qt-creator-opensource-src-4.6.1/src/plugins/bookmarks/bookmarkmanager.cpp | kevinlq/Qt-Creator-Opensource-Study | b8cadff1f33f25a5d4ef33ed93f661b788b1ba0f | [
"MIT"
] | 8 | 2018-07-17T03:55:48.000Z | 2021-12-22T06:37:53.000Z | /****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 as published by the Free Software
** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
**
****************************************************************************/
#include "bookmarkmanager.h"
#include "bookmark.h"
#include "bookmarksplugin.h"
#include "bookmarks_global.h"
#include <coreplugin/editormanager/editormanager.h>
#include <coreplugin/icore.h>
#include <coreplugin/idocument.h>
#include <coreplugin/actionmanager/actionmanager.h>
#include <coreplugin/actionmanager/command.h>
#include <projectexplorer/projectexplorer.h>
#include <projectexplorer/session.h>
#include <texteditor/texteditor.h>
#include <utils/algorithm.h>
#include <utils/icon.h>
#include <utils/qtcassert.h>
#include <utils/checkablemessagebox.h>
#include <utils/theme/theme.h>
#include <utils/dropsupport.h>
#include <utils/utilsicons.h>
#include <QAction>
#include <QContextMenuEvent>
#include <QDebug>
#include <QDialog>
#include <QDialogButtonBox>
#include <QDir>
#include <QFileInfo>
#include <QFormLayout>
#include <QLineEdit>
#include <QMenu>
#include <QPainter>
#include <QSpinBox>
Q_DECLARE_METATYPE(Bookmarks::Internal::Bookmark*)
using namespace ProjectExplorer;
using namespace Core;
using namespace Utils;
namespace Bookmarks {
namespace Internal {
BookmarkDelegate::BookmarkDelegate(QObject *parent)
: QStyledItemDelegate(parent)
{
}
QSize BookmarkDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const
{
QStyleOptionViewItem opt = option;
initStyleOption(&opt, index);
QFontMetrics fm(option.font);
QSize s;
s.setWidth(option.rect.width());
s.setHeight(fm.height() * 2 + 10);
return s;
}
void BookmarkDelegate::generateGradientPixmap(int width, int height, const QColor &color, bool selected) const
{
QColor c = color;
c.setAlpha(0);
QPixmap pixmap(width+1, height);
pixmap.fill(c);
QPainter painter(&pixmap);
painter.setPen(Qt::NoPen);
QLinearGradient lg;
lg.setCoordinateMode(QGradient::ObjectBoundingMode);
lg.setFinalStop(1,0);
lg.setColorAt(0, c);
lg.setColorAt(0.4, color);
painter.setBrush(lg);
painter.drawRect(0, 0, width+1, height);
if (selected)
m_selectedPixmap = pixmap;
else
m_normalPixmap = pixmap;
}
void BookmarkDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
QStyleOptionViewItem opt = option;
initStyleOption(&opt, index);
painter->save();
QFontMetrics fm(opt.font);
static int lwidth = fm.width(QLatin1String("8888")) + 18;
QColor backgroundColor;
QColor textColor;
bool selected = opt.state & QStyle::State_Selected;
if (selected) {
painter->setBrush(opt.palette.highlight().color());
backgroundColor = opt.palette.highlight().color();
if (!m_selectedPixmap)
generateGradientPixmap(lwidth, fm.height()+1, backgroundColor, selected);
} else {
painter->setBrush(opt.palette.background().color());
backgroundColor = opt.palette.background().color();
if (!m_normalPixmap)
generateGradientPixmap(lwidth, fm.height(), backgroundColor, selected);
}
painter->setPen(Qt::NoPen);
painter->drawRect(opt.rect);
// Set Text Color
if (opt.state & QStyle::State_Selected)
textColor = opt.palette.highlightedText().color();
else
textColor = opt.palette.text().color();
painter->setPen(textColor);
// TopLeft
QString topLeft = index.data(BookmarkManager::Filename).toString();
painter->drawText(6, 2 + opt.rect.top() + fm.ascent(), topLeft);
QString topRight = index.data(BookmarkManager::LineNumber).toString();
// Check whether we need to be fancy and paint some background
int fwidth = fm.width(topLeft);
if (fwidth + lwidth > opt.rect.width()) {
int left = opt.rect.right() - lwidth;
painter->drawPixmap(left, opt.rect.top(), selected ? m_selectedPixmap : m_normalPixmap);
}
// topRight
painter->drawText(opt.rect.right() - fm.width(topRight) - 6 , 2 + opt.rect.top() + fm.ascent(), topRight);
// Directory
QColor mix;
mix.setRgbF(0.7 * textColor.redF() + 0.3 * backgroundColor.redF(),
0.7 * textColor.greenF() + 0.3 * backgroundColor.greenF(),
0.7 * textColor.blueF() + 0.3 * backgroundColor.blueF());
painter->setPen(mix);
//
// QString directory = index.data(BookmarkManager::Directory).toString();
// int availableSpace = opt.rect.width() - 12;
// if (fm.width(directory) > availableSpace) {
// // We need a shorter directory
// availableSpace -= fm.width("...");
//
// int pos = directory.size();
// int idx;
// forever {
// idx = directory.lastIndexOf("/", pos-1);
// if (idx == -1) {
// // Can't happen, this means the string did fit after all?
// break;
// }
// int width = fm.width(directory.mid(idx, pos-idx));
// if (width > availableSpace) {
// directory = "..." + directory.mid(pos);
// break;
// } else {
// pos = idx;
// availableSpace -= width;
// }
// }
// }
//
// painter->drawText(3, opt.rect.top() + fm.ascent() + fm.height() + 6, directory);
QString lineText = index.data(BookmarkManager::Note).toString().trimmed();
if (lineText.isEmpty())
lineText = index.data(BookmarkManager::LineText).toString();
painter->drawText(6, opt.rect.top() + fm.ascent() + fm.height() + 6, lineText);
// Separator lines
const QRectF innerRect = QRectF(opt.rect).adjusted(0.5, 0.5, -0.5, -0.5);
painter->setPen(QColor::fromRgb(150,150,150));
painter->drawLine(innerRect.bottomLeft(), innerRect.bottomRight());
painter->restore();
}
BookmarkView::BookmarkView(BookmarkManager *manager) :
m_bookmarkContext(new IContext(this)),
m_manager(manager)
{
setWindowTitle(tr("Bookmarks"));
m_bookmarkContext->setWidget(this);
m_bookmarkContext->setContext(Context(Constants::BOOKMARKS_CONTEXT));
ICore::addContextObject(m_bookmarkContext);
ListView::setModel(manager);
setItemDelegate(new BookmarkDelegate(this));
setFrameStyle(QFrame::NoFrame);
setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
setAttribute(Qt::WA_MacShowFocusRect, false);
setSelectionModel(manager->selectionModel());
setSelectionMode(QAbstractItemView::SingleSelection);
setSelectionBehavior(QAbstractItemView::SelectRows);
setDragEnabled(true);
setDragDropMode(QAbstractItemView::DragOnly);
connect(this, &QAbstractItemView::clicked, this, &BookmarkView::gotoBookmark);
connect(this, &QAbstractItemView::activated, this, &BookmarkView::gotoBookmark);
}
BookmarkView::~BookmarkView()
{
ICore::removeContextObject(m_bookmarkContext);
}
void BookmarkView::contextMenuEvent(QContextMenuEvent *event)
{
QMenu menu;
QAction *moveUp = menu.addAction(tr("Move Up"));
QAction *moveDown = menu.addAction(tr("Move Down"));
QAction *edit = menu.addAction(tr("&Edit"));
menu.addSeparator();
QAction *remove = menu.addAction(tr("&Remove"));
menu.addSeparator();
QAction *removeAll = menu.addAction(tr("Remove All"));
m_contextMenuIndex = indexAt(event->pos());
if (!m_contextMenuIndex.isValid()) {
moveUp->setEnabled(false);
moveDown->setEnabled(false);
remove->setEnabled(false);
edit->setEnabled(false);
}
if (model()->rowCount() == 0)
removeAll->setEnabled(false);
connect(moveUp, &QAction::triggered, m_manager, &BookmarkManager::moveUp);
connect(moveDown, &QAction::triggered, m_manager, &BookmarkManager::moveDown);
connect(remove, &QAction::triggered, this, &BookmarkView::removeFromContextMenu);
connect(removeAll, &QAction::triggered, this, &BookmarkView::removeAll);
connect(edit, &QAction::triggered, m_manager, &BookmarkManager::edit);
menu.exec(mapToGlobal(event->pos()));
}
void BookmarkView::removeFromContextMenu()
{
removeBookmark(m_contextMenuIndex);
}
void BookmarkView::removeBookmark(const QModelIndex& index)
{
Bookmark *bm = m_manager->bookmarkForIndex(index);
m_manager->deleteBookmark(bm);
}
void BookmarkView::keyPressEvent(QKeyEvent *event)
{
if (event->key() == Qt::Key_Delete) {
removeBookmark(currentIndex());
event->accept();
return;
}
ListView::keyPressEvent(event);
}
void BookmarkView::removeAll()
{
if (CheckableMessageBox::doNotAskAgainQuestion(this,
tr("Remove All Bookmarks"),
tr("Are you sure you want to remove all bookmarks from all files in the current session?"),
ICore::settings(),
QLatin1String("RemoveAllBookmarks")) != QDialogButtonBox::Yes)
return;
// The performance of this function could be greatly improved.
while (m_manager->rowCount()) {
QModelIndex index = m_manager->index(0, 0);
removeBookmark(index);
}
}
void BookmarkView::gotoBookmark(const QModelIndex &index)
{
Bookmark *bk = m_manager->bookmarkForIndex(index);
if (!m_manager->gotoBookmark(bk))
m_manager->deleteBookmark(bk);
}
////
// BookmarkManager
////
BookmarkManager::BookmarkManager() :
m_selectionModel(new QItemSelectionModel(this, this))
{
connect(ICore::instance(), &ICore::contextChanged,
this, &BookmarkManager::updateActionStatus);
connect(SessionManager::instance(), &SessionManager::sessionLoaded,
this, &BookmarkManager::loadBookmarks);
updateActionStatus();
}
BookmarkManager::~BookmarkManager()
{
qDeleteAll(m_bookmarksList);
}
QItemSelectionModel *BookmarkManager::selectionModel() const
{
return m_selectionModel;
}
bool BookmarkManager::hasBookmarkInPosition(const Utils::FileName &fileName, int lineNumber)
{
return findBookmark(fileName, lineNumber);
}
QModelIndex BookmarkManager::index(int row, int column, const QModelIndex &parent) const
{
if (parent.isValid())
return QModelIndex();
else
return createIndex(row, column);
}
QModelIndex BookmarkManager::parent(const QModelIndex &) const
{
return QModelIndex();
}
int BookmarkManager::rowCount(const QModelIndex &parent) const
{
if (parent.isValid())
return 0;
else
return m_bookmarksList.count();
}
int BookmarkManager::columnCount(const QModelIndex &parent) const
{
if (parent.isValid())
return 0;
return 3;
}
QVariant BookmarkManager::data(const QModelIndex &index, int role) const
{
if (!index.isValid() || index.column() !=0 || index.row() < 0 || index.row() >= m_bookmarksList.count())
return QVariant();
Bookmark *bookMark = m_bookmarksList.at(index.row());
if (role == BookmarkManager::Filename)
return FileName::fromString(bookMark->fileName()).fileName();
if (role == BookmarkManager::LineNumber)
return bookMark->lineNumber();
if (role == BookmarkManager::Directory)
return QFileInfo(bookMark->fileName()).path();
if (role == BookmarkManager::LineText)
return bookMark->lineText();
if (role == BookmarkManager::Note)
return bookMark->note();
if (role == Qt::ToolTipRole)
return QDir::toNativeSeparators(bookMark->fileName());
return QVariant();
}
Qt::ItemFlags BookmarkManager::flags(const QModelIndex &index) const
{
if (!index.isValid() || index.column() !=0 || index.row() < 0 || index.row() >= m_bookmarksList.count())
return Qt::NoItemFlags;
return Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsDragEnabled;
}
Qt::DropActions BookmarkManager::supportedDragActions() const
{
return Qt::MoveAction;
}
QStringList BookmarkManager::mimeTypes() const
{
return DropSupport::mimeTypesForFilePaths();
}
QMimeData *BookmarkManager::mimeData(const QModelIndexList &indexes) const
{
auto data = new DropMimeData;
foreach (const QModelIndex &index, indexes) {
if (!index.isValid() || index.column() != 0 || index.row() < 0 || index.row() >= m_bookmarksList.count())
continue;
Bookmark *bookMark = m_bookmarksList.at(index.row());
data->addFile(bookMark->fileName(), bookMark->lineNumber());
}
return data;
}
void BookmarkManager::toggleBookmark(const FileName &fileName, int lineNumber)
{
if (lineNumber <= 0 || fileName.isEmpty())
return;
// Remove any existing bookmark on this line
if (Bookmark *mark = findBookmark(fileName, lineNumber)) {
// TODO check if the bookmark is really on the same markable Interface
deleteBookmark(mark);
return;
}
// Add a new bookmark if no bookmark existed on this line
Bookmark *mark = new Bookmark(lineNumber, this);
mark->updateFileName(fileName.toString());
addBookmark(mark);
}
void BookmarkManager::updateBookmark(Bookmark *bookmark)
{
const int idx = m_bookmarksList.indexOf(bookmark);
if (idx == -1)
return;
emit dataChanged(index(idx, 0, QModelIndex()), index(idx, 2, QModelIndex()));
saveBookmarks();
}
void BookmarkManager::updateBookmarkFileName(Bookmark *bookmark, const QString &oldFileName)
{
if (oldFileName == bookmark->fileName())
return;
m_bookmarksMap[Utils::FileName::fromString(oldFileName)].removeAll(bookmark);
m_bookmarksMap[Utils::FileName::fromString(bookmark->fileName())].append(bookmark);
updateBookmark(bookmark);
}
void BookmarkManager::removeAllBookmarks()
{
if (m_bookmarksList.isEmpty())
return;
beginRemoveRows(QModelIndex(), 0, m_bookmarksList.size() - 1);
qDeleteAll(m_bookmarksList);
m_bookmarksMap.clear();
m_bookmarksList.clear();
endRemoveRows();
}
void BookmarkManager::deleteBookmark(Bookmark *bookmark)
{
int idx = m_bookmarksList.indexOf(bookmark);
beginRemoveRows(QModelIndex(), idx, idx);
m_bookmarksMap[Utils::FileName::fromString(bookmark->fileName())].removeAll(bookmark);
delete bookmark;
m_bookmarksList.removeAt(idx);
endRemoveRows();
if (selectionModel()->currentIndex().isValid())
selectionModel()->setCurrentIndex(selectionModel()->currentIndex(), QItemSelectionModel::Select | QItemSelectionModel::Clear);
updateActionStatus();
saveBookmarks();
}
Bookmark *BookmarkManager::bookmarkForIndex(const QModelIndex &index) const
{
if (!index.isValid() || index.row() >= m_bookmarksList.size())
return 0;
return m_bookmarksList.at(index.row());
}
bool BookmarkManager::gotoBookmark(const Bookmark *bookmark) const
{
if (IEditor *editor = EditorManager::openEditorAt(bookmark->fileName(), bookmark->lineNumber()))
return editor->currentLine() == bookmark->lineNumber();
return false;
}
void BookmarkManager::nextInDocument()
{
documentPrevNext(true);
}
void BookmarkManager::prevInDocument()
{
documentPrevNext(false);
}
void BookmarkManager::documentPrevNext(bool next)
{
IEditor *editor = EditorManager::currentEditor();
const int editorLine = editor->currentLine();
if (editorLine <= 0)
return;
const FileName filePath = editor->document()->filePath();
if (!m_bookmarksMap.contains(filePath))
return;
int firstLine = -1;
int lastLine = -1;
int prevLine = -1;
int nextLine = -1;
const QVector<Bookmark *> marks = m_bookmarksMap[filePath];
for (int i = 0; i < marks.count(); ++i) {
int markLine = marks.at(i)->lineNumber();
if (firstLine == -1 || firstLine > markLine)
firstLine = markLine;
if (lastLine < markLine)
lastLine = markLine;
if (markLine < editorLine && prevLine < markLine)
prevLine = markLine;
if (markLine > editorLine &&
(nextLine == -1 || nextLine > markLine))
nextLine = markLine;
}
EditorManager::addCurrentPositionToNavigationHistory();
if (next) {
if (nextLine == -1)
editor->gotoLine(firstLine);
else
editor->gotoLine(nextLine);
} else {
if (prevLine == -1)
editor->gotoLine(lastLine);
else
editor->gotoLine(prevLine);
}
}
void BookmarkManager::next()
{
QModelIndex current = selectionModel()->currentIndex();
if (!current.isValid())
return;
int row = current.row();
++row;
while (true) {
if (row == m_bookmarksList.size())
row = 0;
Bookmark *bk = m_bookmarksList.at(row);
if (gotoBookmark(bk)) {
QModelIndex newIndex = current.sibling(row, current.column());
selectionModel()->setCurrentIndex(newIndex, QItemSelectionModel::Select | QItemSelectionModel::Clear);
return;
}
deleteBookmark(bk);
if (m_bookmarksList.isEmpty()) // No bookmarks anymore ...
return;
}
}
void BookmarkManager::prev()
{
QModelIndex current = selectionModel()->currentIndex();
if (!current.isValid())
return;
int row = current.row();
while (true) {
if (row == 0)
row = m_bookmarksList.size();
--row;
Bookmark *bk = m_bookmarksList.at(row);
if (gotoBookmark(bk)) {
QModelIndex newIndex = current.sibling(row, current.column());
selectionModel()->setCurrentIndex(newIndex, QItemSelectionModel::Select | QItemSelectionModel::Clear);
return;
}
deleteBookmark(bk);
if (m_bookmarksList.isEmpty())
return;
}
}
BookmarkManager::State BookmarkManager::state() const
{
if (m_bookmarksList.empty())
return NoBookMarks;
IEditor *editor = EditorManager::currentEditor();
if (!editor)
return HasBookMarks;
return m_bookmarksMap.value(editor->document()->filePath()).isEmpty() ? HasBookMarks
: HasBookmarksInDocument;
}
void BookmarkManager::updateActionStatus()
{
IEditor *editor = EditorManager::currentEditor();
const bool enableToggle = editor && !editor->document()->isTemporary();
updateActions(enableToggle, state());
}
void BookmarkManager::moveUp()
{
QModelIndex current = selectionModel()->currentIndex();
int row = current.row();
if (row == 0)
row = m_bookmarksList.size();
--row;
// swap current.row() and row
Bookmark *b = m_bookmarksList.at(row);
m_bookmarksList[row] = m_bookmarksList.at(current.row());
m_bookmarksList[current.row()] = b;
QModelIndex topLeft = current.sibling(row, 0);
QModelIndex bottomRight = current.sibling(current.row(), 2);
emit dataChanged(topLeft, bottomRight);
selectionModel()->setCurrentIndex(current.sibling(row, 0), QItemSelectionModel::Select | QItemSelectionModel::Clear);
saveBookmarks();
}
void BookmarkManager::moveDown()
{
QModelIndex current = selectionModel()->currentIndex();
int row = current.row();
++row;
if (row == m_bookmarksList.size())
row = 0;
// swap current.row() and row
Bookmark *b = m_bookmarksList.at(row);
m_bookmarksList[row] = m_bookmarksList.at(current.row());
m_bookmarksList[current.row()] = b;
QModelIndex topLeft = current.sibling(current.row(), 0);
QModelIndex bottomRight = current.sibling(row, 2);
emit dataChanged(topLeft, bottomRight);
selectionModel()->setCurrentIndex(current.sibling(row, 0), QItemSelectionModel::Select | QItemSelectionModel::Clear);
saveBookmarks();
}
void BookmarkManager::editByFileAndLine(const FileName &fileName, int lineNumber)
{
Bookmark *b = findBookmark(fileName, lineNumber);
QModelIndex current = selectionModel()->currentIndex();
selectionModel()->setCurrentIndex(current.sibling(m_bookmarksList.indexOf(b), 0),
QItemSelectionModel::Select | QItemSelectionModel::Clear);
edit();
}
void BookmarkManager::edit()
{
QModelIndex current = selectionModel()->currentIndex();
Bookmark *b = m_bookmarksList.at(current.row());
QDialog dlg;
dlg.setWindowTitle(tr("Edit Bookmark"));
auto layout = new QFormLayout(&dlg);
auto noteEdit = new QLineEdit(b->note());
noteEdit->setMinimumWidth(300);
auto lineNumberSpinbox = new QSpinBox;
lineNumberSpinbox->setRange(1, INT_MAX);
lineNumberSpinbox->setValue(b->lineNumber());
lineNumberSpinbox->setMaximumWidth(100);
auto buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel);
connect(buttonBox, &QDialogButtonBox::accepted, &dlg, &QDialog::accept);
connect(buttonBox, &QDialogButtonBox::rejected, &dlg, &QDialog::reject);
layout->addRow(tr("Note text:"), noteEdit);
layout->addRow(tr("Line number:"), lineNumberSpinbox);
layout->addWidget(buttonBox);
if (dlg.exec() == QDialog::Accepted) {
b->move(lineNumberSpinbox->value());
b->updateNote(noteEdit->text().replace(QLatin1Char('\t'), QLatin1Char(' ')));
emit dataChanged(current, current);
saveBookmarks();
}
}
/* Returns the bookmark at the given file and line number, or 0 if no such bookmark exists. */
Bookmark *BookmarkManager::findBookmark(const FileName &filePath, int lineNumber)
{
return Utils::findOrDefault(m_bookmarksMap.value(filePath),
Utils::equal(&Bookmark::lineNumber, lineNumber));
}
/* Adds a bookmark to the internal data structures. The 'userset' parameter
* determines whether action status should be updated and whether the bookmarks
* should be saved to the session settings.
*/
void BookmarkManager::addBookmark(Bookmark *bookmark, bool userset)
{
beginInsertRows(QModelIndex(), m_bookmarksList.size(), m_bookmarksList.size());
m_bookmarksMap[FileName::fromString(bookmark->fileName())].append(bookmark);
m_bookmarksList.append(bookmark);
endInsertRows();
if (userset) {
updateActionStatus();
saveBookmarks();
}
selectionModel()->setCurrentIndex(index(m_bookmarksList.size()-1 , 0, QModelIndex()), QItemSelectionModel::Select | QItemSelectionModel::Clear);
}
/* Adds a new bookmark based on information parsed from the string. */
void BookmarkManager::addBookmark(const QString &s)
{
// index3 is a frontier beetween note text and other bookmarks data
int index3 = s.lastIndexOf(QLatin1Char('\t'));
if (index3 < 0)
index3 = s.size();
int index2 = s.lastIndexOf(QLatin1Char(':'), index3 - 1);
int index1 = s.indexOf(QLatin1Char(':'));
if (index3 != -1 || index2 != -1 || index1 != -1) {
const QString &filePath = s.mid(index1+1, index2-index1-1);
const QString ¬e = s.mid(index3 + 1);
const int lineNumber = s.midRef(index2 + 1, index3 - index2 - 1).toInt();
if (!filePath.isEmpty() && !findBookmark(FileName::fromString(filePath), lineNumber)) {
Bookmark *b = new Bookmark(lineNumber, this);
b->updateFileName(filePath);
b->setNote(note);
addBookmark(b, false);
}
} else {
qDebug() << "BookmarkManager::addBookmark() Invalid bookmark string:" << s;
}
}
/* Puts the bookmark in a string for storing it in the settings. */
QString BookmarkManager::bookmarkToString(const Bookmark *b)
{
const QLatin1Char colon(':');
// Using \t as delimiter because any another symbol can be a part of note.
const QLatin1Char noteDelimiter('\t');
return colon + b->fileName() +
colon + QString::number(b->lineNumber()) +
noteDelimiter + b->note();
}
/* Saves the bookmarks to the session settings. */
void BookmarkManager::saveBookmarks()
{
QStringList list;
foreach (const Bookmark *bookmark, m_bookmarksList)
list << bookmarkToString(bookmark);
SessionManager::setValue(QLatin1String("Bookmarks"), list);
}
/* Loads the bookmarks from the session settings. */
void BookmarkManager::loadBookmarks()
{
removeAllBookmarks();
const QStringList &list = SessionManager::value(QLatin1String("Bookmarks")).toStringList();
foreach (const QString &bookmarkString, list)
addBookmark(bookmarkString);
updateActionStatus();
}
// BookmarkViewFactory
BookmarkViewFactory::BookmarkViewFactory(BookmarkManager *bm)
: m_manager(bm)
{
setDisplayName(BookmarkView::tr("Bookmarks"));
setPriority(300);
setId("Bookmarks");
setActivationSequence(QKeySequence(UseMacShortcuts ? tr("Alt+Meta+M") : tr("Alt+M")));
}
NavigationView BookmarkViewFactory::createWidget()
{
return NavigationView(new BookmarkView(m_manager));
}
} // namespace Internal
} // namespace Bookmarks
| 31.79064 | 148 | 0.666305 | [
"model"
] |
097742c9d0f8b50bed779e745054705bf3920837 | 13,539 | hpp | C++ | hctrl/src/types/storage/circular_buffer.hpp | rikardonm/hctrl | 1bf70c0d2ae2a99852dcb80c27beb4501958d54b | [
"MIT"
] | null | null | null | hctrl/src/types/storage/circular_buffer.hpp | rikardonm/hctrl | 1bf70c0d2ae2a99852dcb80c27beb4501958d54b | [
"MIT"
] | 4 | 2022-03-16T19:24:37.000Z | 2022-03-16T21:37:35.000Z | hctrl/src/types/storage/circular_buffer.hpp | rikardonm/hctrl | 1bf70c0d2ae2a99852dcb80c27beb4501958d54b | [
"MIT"
] | null | null | null | #pragma once
#include <cstdint>
#include <cstring>
#include <cstdlib>
#include <tuple>
template<size_t SIZE>
class ScanCursor
{
public:
using _Base = ScanCursor<SIZE>;
/**
* @brief Construct a new Scan Cursor object
*
* @param cursor
*/
ScanCursor(size_t cursor)
: _cursor(cursor)
{
};
/**
* @brief
*
* @param length
*/
void AdvanceCursor(size_t length = 1)
{
const auto to_go = (SIZE - _cursor);
if (to_go > length)
{
/* Has space, just advance */
_cursor += length;
}
else
{
/* Wrap around */
_cursor = length - to_go;
}
}
_Base& operator+=(const size_t value)
{
AdvanceCursor(value);
return *this;
}
_Base& operator++()
{
AdvanceCursor(1);
return *this;
}
/**
* @brief
*
* @param length
*/
void RecedeCursor(size_t length = 1)
{
if (length > _cursor)
{
_cursor = SIZE - (length - _cursor);
}
else
{
_cursor -= length;
}
}
_Base& operator-=(const size_t value)
{
RecedeCursor(value);
return *this;
}
_Base& operator--()
{
RecedeCursor(1);
return *this;
}
bool operator==(const _Base& other) const
{
return _cursor == other._cursor;
}
bool operator!=(const _Base& other) const
{
return not (*this == other);
}
_Base& operator=(const _Base& other)
{
if (other != *this)
{
_cursor = other._cursor;
}
return *this;
}
/**
* @brief Calculates distance from current object cursor to another trailing cursor.
*
* @param trailer
* @return size_t
*/
size_t TrailingDistance(const _Base& trailer) const
{
if (_cursor >= trailer._cursor)
{
return _cursor - trailer._cursor;
}
else
{
return (SIZE - trailer._cursor) + _cursor;
}
}
/**
* @brief Calculates distance from current object to another leading cursor.
*
* @param leader
* @return size_t
*/
size_t LeadingDistance(const _Base& leader) const
{
if (_cursor <= leader._cursor)
{
return leader._cursor - _cursor;
}
else
{
return (SIZE - _cursor) + leader._cursor;
}
}
/**
* @brief
*
* @return size_t
*/
size_t Index() const
{
return _cursor;
}
private:
size_t _cursor;
};
/**
* @brief
*
* @tparam SIZE
*/
template<size_t SIZE>
class BoundedCursor : public ScanCursor<SIZE>
{
public:
/**
* @brief Construct a new Bounded Cursor object
*
* @param lower
* @param upper
*/
BoundedCursor(const ScanCursor<SIZE>& lower, const ScanCursor<SIZE>& upper)
: ScanCursor<SIZE>(lower.Index()), _lower(lower), _upper(upper)
{
}
/**
* @brief
*
* @return true
* @return false
*/
bool IsValid() const
{
return _upper.TrailingDistance(_lower) > this->TrailingDistance(_lower);
}
/**
* @brief
*
* @return size_t
*/
size_t LowerDistance()
{
return this->TrailingDistance(_lower);
}
/**
* @brief
*
* @return size_t
*/
size_t UpperDistance()
{
return this->LeadingDistance(_upper);
}
protected:
const ScanCursor<SIZE>& _lower;
const ScanCursor<SIZE>& _upper;
};
/**
* @brief Template for a circular buffer implementation with scan/edit cursor
*
*
* Data is pushed (stored) and read back (pop) from from left (lower address) to right (higher address),
* wrapping around the SIZE boundary.
*
*
* State 1: write cursor is in front of read cursor; data is contiguous
* Used cells: (Write Next) - (Read Next)
* Free cells: SIZE - Used
* Is Cursor valid: if cursor value falls in range:
* [Read Next, Write Next)
*
*
* /---- SIZE
* Write /
* Next = 6 |
* | |
* Cursor/ | |
* Index: 0 1 2 3 4 5 6 | 7 8 9
* _____ _____ _____ _____ _____ _____ __+__ _____ _____
* | | | | | | | | | |
* | | X | X | X | X | X | | | |
* |_____|_____|_____|_____|_____|_____|_____|_____|_____|
* +
* |
* |
* |
* Read
* Next = 1
*
*
*
* State 2: write cursor is behind of read cursor; data wraps around buffer boundary
* Used cells: SIZE - (Read Next) + (Write Next)
* Free cells: SIZE - Used
* Is Cursor valid: if cursor falls into either range:
* [Read Next, SIZE)
* [0, Write Next)
*
*
* /---- SIZE
* Write /
* Next = 2 |
* | |
* Cursor/ | |
* Index: 0 1 2 | 3 4 5 6 7 8 9
* _____ _____ __+__ _____ _____ _____ _____ _____ _____
* | | | | | | | | | |
* | X | X | | | | | X | X | X |
* |_____|_____|_____|_____|_____|_____|_____|_____|_____|
* +
* |
* |
* |
* Read
* Next = 6
*
*
*
* @tparam T Type of elements to store
* @tparam SIZE Maximum amount of elements capable of storing at any given moment
* @tparam CLEAN Fill buffer cells with default value at every removal or discard operation
*/
template<typename T, size_t SIZE, bool CLEAN>
class CircularBuffer
{
public:
using _Base = CircularBuffer<T, SIZE, CLEAN>;
CircularBuffer(bool clean = false)
: _write_cursor(0), _read_cursor(0)
{
if (CLEAN or clean)
{
for(auto& x : _buffer)
{
x = {};
}
}
}
bool Push(const T value)
{
if (Free() >= 1)
{
_Push(value);
return true;
}
return false;
}
_Base& operator<<(const T value)
{
Push(value);
return *this;
}
template<size_t ASIZE>
bool Push(const T (&array)[ASIZE])
{
if (Free() >= ASIZE)
{
for(const auto& value : array)
{
_Push(value);
}
return true;
}
return false;
}
template<size_t ASIZE>
_Base& operator<<(const T (&array)[ASIZE])
{
Push(array);
return *this;
}
template<size_t ASIZE, bool ACLEAN>
bool Push(CircularBuffer<T, ASIZE, ACLEAN>& other, size_t length)
{
if (length > Free())
{
return false;
}
for (auto i = 0; i < length; ++i)
{
_Push(other._Pop(ACLEAN));
}
return true;
}
template<size_t ASIZE, bool ACLEAN>
bool Push(CircularBuffer<T, ASIZE, ACLEAN>& other)
{
return Push(other, other.Used());
}
template<size_t ASIZE, bool ACLEAN>
_Base& operator<<(CircularBuffer<T, ASIZE, ACLEAN>& other)
{
Push(other);
return *this;
}
bool RevertPush(size_t length = 1, bool clean = false)
{
if (Used() < length)
{
return false;
}
_RevertPush(length, clean);
return true;
}
std::tuple<bool, T> Pop(bool clean = false)
{
if (Used() >= 1)
{
return {true, _Pop(clean)};
}
return {false, {}};
}
/**
* @brief
*
* @param clean
*/
void Discard(bool clean = false)
{
if (CLEAN or clean)
{
while(Used())
{
_Pop(true);
}
}
_read_cursor = 0;
_write_cursor = 0;
}
const T* GetContiguousArray()
{
return &_buffer[_read_cursor.Index()];
}
/**
* @brief
*
* @param size
* @param clean
* @return true
* @return false
*/
bool Discard(const size_t size, bool clean = false)
{
if (Used() < size)
{
return false;
}
if (CLEAN or clean)
{
for (auto counter = 0; counter < size; ++counter)
{
_Pop(true);
}
}
else
{
_read_cursor += size;
}
return true;
}
size_t Free()
{
return SIZE - Used();
}
size_t Used()
{
return _write_cursor.TrailingDistance(_read_cursor);
}
/**
* @brief
*
*/
class CircularBufferCursor : public BoundedCursor<SIZE>
{
public:
/**
* @brief Construct a new Circular Buffer Cursor object
*
* @param circular_buffer
*/
CircularBufferCursor(_Base& circular_buffer)
: BoundedCursor<SIZE>(circular_buffer._read_cursor, circular_buffer._write_cursor), _buffer(circular_buffer)
{
}
~CircularBufferCursor() = default;
CircularBufferCursor(const CircularBufferCursor& other) = default;
CircularBufferCursor& operator=(const CircularBufferCursor& other) = default;
/**
* @brief
*
* @param value
* @return CircularBufferCursor&
*/
CircularBufferCursor& operator=(const T& value)
{
_buffer[this->Index()] = value;
return *this;
}
/**
* @brief
*
* @return T&
*/
T& Item()
{
return _buffer._buffer[this->Index()];
}
/**
* @brief
*
* @return T
*/
operator T()
{
return _buffer._buffer[this->Index()];
}
/**
* @brief Advance object's cursor until chartest returns true or cursor is invalid.
*
* @param chartest Function pointer to test if character meets stopping criteria.
*/
void Next(bool (*chartest)(const T))
{
for (; this->IsValid() ; ++(*this))
{
if (chartest(this->Item()))
{
return;
}
}
}
private:
_Base& _buffer;
};
CircularBufferCursor GetCursor()
{
return CircularBufferCursor(*this);
}
// can't really be used... as the contents are not always contiguous
// perhaps use some sort of iterator here
// well, it kind of can... it just needs to be called twice!!
size_t PeekUsed()
{
if (_write_cursor.Index() >= _read_cursor.Index())
{
return _write_cursor.TrailingDistance(_read_cursor);
}
else
{
return SIZE - _read_cursor.Index();
}
}
protected:
void _Push(const T& value)
{
_buffer[_write_cursor.Index()] = value;
++_write_cursor;
}
void _RevertPush(size_t length, bool clean)
{
if (CLEAN or clean)
{
for(auto count = 0; count < length; ++count)
{
--_write_cursor;
_buffer[_write_cursor.Index()] = {};
}
}
else
{
_write_cursor -= length;
}
}
T _Pop(bool clean)
{
auto ret = _buffer[_read_cursor.Index()];
if (CLEAN or clean)
{
_buffer[_read_cursor.Index()] = {};
}
++_read_cursor;
return ret;
}
private:
T _buffer[SIZE];
/* _buffer based offset cursors; both point to the NEXT operation location */
ScanCursor<SIZE> _write_cursor;
ScanCursor<SIZE> _read_cursor;
/* Declare sibling classes as friends */
template<typename, size_t, bool> friend class CircularBuffer;
};
| 23.343103 | 117 | 0.431199 | [
"object"
] |
097feec0f5ce965d0cf75c7d364531c12a77fef5 | 5,981 | cc | C++ | src/RegionProps.cc | Gio-ch/Deep_SLAM | 556094b4f4ee6a58256b5e0075c2f712a1db64b8 | [
"CC0-1.0"
] | 6 | 2021-07-31T02:06:33.000Z | 2022-02-26T12:31:46.000Z | src/RegionProps.cc | Gio-ch/Deep_SLAM | 556094b4f4ee6a58256b5e0075c2f712a1db64b8 | [
"CC0-1.0"
] | null | null | null | src/RegionProps.cc | Gio-ch/Deep_SLAM | 556094b4f4ee6a58256b5e0075c2f712a1db64b8 | [
"CC0-1.0"
] | null | null | null | /*
* Regionprops
* Copyright 2015 Andrea Pennisi
*
* This file is part of Regionprops and it is distributed under the terms of the
* GNU Lesser General Public License (Lesser GPL)
*
*
*
* Regionprops is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Regionprops is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Regionprops. If not, see <http://www.gnu.org/licenses/>.
*
*
* Regionprops has been written by Andrea Pennisi
*
* Please, report suggestions/comments/bugs to
* andrea.pennisi@gmail.com
*
*/
#include "regionprops.h"
#include <iostream>
RegionProps::RegionProps(const std::vector<cv::Point> &_contour,
const cv::Mat &_img)
: img(_img.clone()), contour(_contour)
{
compute();
}
void RegionProps::compute()
{
region.setArea(area());
region.setPerimeter(perimeter());
region.setMoments(moments());
region.setCentroid(centroid());
region.setAspectRatio(aspectratio());
region.setBoundingBox(boundingbox());
region.setConvexHull(convex_hull());
region.setConvexArea(convexarea());
region.setEllipse(ellipse());
region.setSolidity(solidity());
region.setMajorAxis(majoraxislength());
region.setMinorAxis(minoraxislength());
region.setOrientation(orientation());
region.setEccentricity(eccentricity());
region.setApprox(approx());
region.setFilledImage(filledimage());
region.setFilledArea(filledarea());
region.setPixelList(pixellist());
region.setConvexImage(conveximage());
pixelparameters();
region.setExtrema(extrema());
}
double RegionProps::area()
{
return cv::contourArea(contour);
}
double RegionProps::perimeter()
{
return cv::arcLength(contour, true);
}
cv::Moments RegionProps::moments()
{
return cv::moments(contour);
}
cv::Point RegionProps::centroid()
{
cv::Point c(0, 0);
if(region.Moments().m00 != 0.0)
{
c.x = region.Moments().m10 / region.Moments().m00;
c.y = region.Moments().m01 / region.Moments().m00;
}
return c;
}
double RegionProps::aspectratio()
{
return region.BoundingBox().width / double(region.BoundingBox().height);
}
double RegionProps::equivalentdiameter()
{
return std::sqrt(4*region.Area()/CV_PI);
}
cv::Rect RegionProps::boundingbox()
{
return cv::boundingRect(contour);
}
double RegionProps::extent()
{
return region.Area()/(region.BoundingBox().width*region.BoundingBox().height);
}
std::vector<cv::Point> RegionProps::convex_hull()
{
std::vector<cv::Point> convex;
cv::convexHull(contour, convex);
return convex;
}
double RegionProps::convexarea()
{
return cv::contourArea(region.ConvexHull());
}
double RegionProps::solidity()
{
return region.Area() / double(region.ConvexArea());
}
cv::RotatedRect RegionProps::ellipse()
{
return cv::fitEllipse(contour);
}
double RegionProps::majoraxislength()
{
return cv::max(region.Ellipse().size.width, region.Ellipse().size.height);
}
double RegionProps::minoraxislength()
{
return cv::min(region.Ellipse().size.width, region.Ellipse().size.height);
}
double RegionProps::orientation()
{
return region.Ellipse().angle;
}
double RegionProps::eccentricity()
{
return std::sqrt(1 - (region.MinorAxis() / region.MajorAxis()) *
(region.MinorAxis() / region.MajorAxis()));
}
std::vector<cv::Point> RegionProps::approx()
{
std::vector<cv::Point> a;
cv::approxPolyDP(contour, a, 0.02*region.Perimeter(), true);
return a;
}
cv::Mat RegionProps::filledimage()
{
cv::Mat filled = cv::Mat::zeros(img.size(), CV_8UC1);
cv::drawContours(filled, std::vector< std::vector<cv::Point> >(1, contour), -1, cv::Scalar(255), -1);
return filled;
}
double RegionProps::filledarea()
{
return cv::countNonZero(region.FilledImage());
}
cv::Mat RegionProps::pixellist()
{
cv::Mat locations;
cv::findNonZero(region.FilledImage(), locations);
return locations.t();
}
cv::Mat RegionProps::conveximage()
{
cv::Mat convex = cv::Mat::zeros(img.size(), CV_8UC1);
cv::drawContours(convex, std::vector< std::vector<cv::Point> >(1,region.ConvexHull()), -1, 255, -1);
return convex;
}
void RegionProps::pixelparameters()
{
double minval, maxval;
cv::Point minloc, maxloc;
cv::Scalar meanval;
cv::minMaxLoc(img, &minval, &maxval, &minloc, &maxloc, region.FilledImage());
meanval = cv::mean(img, region.FilledImage());
region.setMinLoc(minloc);
region.setMaxLoc(maxloc);
region.setMinVal(minval);
region.setMaxVal(maxval);
region.setMeanVal(meanval);
}
std::vector<cv::Point> RegionProps::extrema()
{
std::vector<cv::Point>::iterator it;
std::vector<cv::Point> e;
cv::Point leftMost(img.cols, 0), rightMost(0,0),
topMost(0, 0), bottomMost(0, img.rows);
for(it = contour.begin(); it != contour.end(); ++it)
{
if((*it).x > rightMost.x)
{
rightMost.x = (*it).x;
rightMost.y = (*it).y;
}
if((*it).x < leftMost.x)
{
leftMost.x = (*it).x;
leftMost.y = (*it).y;
}
if((*it).y > topMost.y)
{
topMost.x = (*it).x;
topMost.y = (*it).y;
}
if((*it).y < bottomMost.y)
{
bottomMost.x = (*it).x;
bottomMost.y = (*it).y;
}
}
e.push_back(rightMost);
e.push_back(leftMost);
e.push_back(topMost);
e.push_back(bottomMost);
return e;
}
| 24.817427 | 105 | 0.64638 | [
"vector"
] |
098894a59e570b8c61a3cd29b91333b9809ead38 | 3,915 | cpp | C++ | 20.01.2020/program/src/Board.cpp | zdrzalik-przemek/pobi_proj_szachy | 4a8ce39b780432d57a342987fcafe3ac0cd72cdf | [
"Apache-2.0"
] | 2 | 2020-04-26T19:24:27.000Z | 2020-04-30T16:07:02.000Z | 20.01.2020/program/src/Board.cpp | zdrzalik-przemek/pobi_proj_szachy | 4a8ce39b780432d57a342987fcafe3ac0cd72cdf | [
"Apache-2.0"
] | null | null | null | 20.01.2020/program/src/Board.cpp | zdrzalik-przemek/pobi_proj_szachy | 4a8ce39b780432d57a342987fcafe3ac0cd72cdf | [
"Apache-2.0"
] | null | null | null | //
// Created by Przemek on 29.12.2019.
//
#include <iostream>
#include "Board.h"
#include "Field.h"
#include "Pieces/Piece.h"
#include <algorithm>
const int board_dimensions = 8;
Board::Board() {
for(int i = 0; i < 8; i++){
fields.push_back(std::vector<std::shared_ptr<Field>>());
for(int j = 0; j < 8; j++){
auto tmp = std::make_shared<Field>(i,j);
this->fields[i].push_back(tmp);
}
}
}
std::vector<std::vector<std::shared_ptr<Field>>> Board::get_board() {
return this->fields;
}
std::shared_ptr<Field> Board::get_field(Position position) {
if (position.row < 0 || (position.col < 0)) {
throw std::out_of_range(
"VECTOR INDEX HAS TO BE A NATURAL NUMBER");
}
if(position.row > board_dimensions - 1 || position.col > board_dimensions - 1){
throw std::out_of_range(
"VECTOR INDEX HAS TO BE SMALLER THAN BOARD DIMENSIONS - 1");
}
return this->fields[position.row][position.col];
}
int Board::board_size() {
int tmp = 0;
for(auto &i: this->fields){
tmp += i.size();
}
return tmp;
}
bool Board::is_clear_path(Position pos_beg, Position pos_end) {
try{
if(pos_beg == pos_end) {
throw std::runtime_error("attempted to check clear path in place");
}
}
catch(const std::runtime_error& e){
std::cout<< "Caught " << typeid(e).name() << " in Board::is_clear_path "<< e.what() << "\n";
return false;
}
if(this->get_field(pos_beg)->get_piece() && this->get_field(pos_end)->get_piece() && this->get_field(pos_beg)->get_piece()->get_is_white() == this->get_field(pos_end)->get_piece()->get_is_white()){
return false;
}
if(pos_beg.col - pos_end.col == 0){
for(int i = std::min(pos_beg.row, pos_end.row) + 1; i < (std::max(pos_beg.row, pos_end.row)); i++){
if(this->get_field(Position(i, pos_beg.col))->get_piece() != nullptr){
return false;
}
}
}
if(pos_beg.row - pos_end.row == 0){
for(int i = std::min(pos_beg.col, pos_end.col) + 1; i < (std::max(pos_beg.col, pos_end.col)); i++){
if(this->get_field(Position(pos_beg.row, i))->get_piece() != nullptr){
return false;
}
}
}
if((abs(pos_beg.col - pos_end.col) - abs(pos_beg.row - pos_end.row)) == 0) {
if(pos_end.col > pos_beg.col && (pos_end.row > pos_beg.row)){
int change = 1;
while(pos_beg.col + change != pos_end.col){
if(this->get_field(Position(pos_beg.row + change, pos_beg.col + change))->get_piece() != nullptr){
return false;
}
change++;
}
}
if(pos_end.col < pos_beg.col && (pos_end.row > pos_beg.row)){
int change = 1;
while(pos_beg.col - change != pos_end.col){
if(this->get_field(Position(pos_beg.row + change, pos_beg.col - change))->get_piece() != nullptr){
return false;
}
change++;
}
}
if(pos_end.col > pos_beg.col && (pos_end.row < pos_beg.row)){
int change = 1;
while(pos_beg.col + change != pos_end.col){
if(this->get_field(Position(pos_beg.row - change, pos_beg.col + change))->get_piece() != nullptr){
return false;
}
change++;
}
}
if(pos_end.col < pos_beg.col && (pos_end.row < pos_beg.row)){
int change = 1;
while(pos_beg.col - change != pos_end.col){
if(this->get_field(Position(pos_beg.row - change, pos_beg.col - change))->get_piece() != nullptr){
return false;
}
change++;
}
}
}
return true;
}
| 33.461538 | 201 | 0.527458 | [
"vector"
] |
098a66c6811eb2cac86c66049c2c1ca790c69d39 | 1,045 | hpp | C++ | etl/_tuple/make_tuple.hpp | tobanteAudio/taetl | 0aa6365aa156b297745f395882ff366a8626e5e0 | [
"BSL-1.0"
] | 4 | 2021-11-28T08:48:11.000Z | 2021-12-14T09:53:51.000Z | etl/_tuple/make_tuple.hpp | tobanteEmbedded/tetl | fc3272170843bcab47971191bcd269a86c5b5101 | [
"BSL-1.0"
] | null | null | null | etl/_tuple/make_tuple.hpp | tobanteEmbedded/tetl | fc3272170843bcab47971191bcd269a86c5b5101 | [
"BSL-1.0"
] | 1 | 2019-04-29T20:09:19.000Z | 2019-04-29T20:09:19.000Z |
/// \copyright Tobias Hienzsch 2019-2021
/// Distributed under the Boost Software License, Version 1.0.
/// See accompanying file LICENSE or copy at http://boost.org/LICENSE_1_0.txt
#ifndef TETL_TUPLE_MAKE_TUPLE_HPP
#define TETL_TUPLE_MAKE_TUPLE_HPP
#include "etl/_functional/reference_wrapper.hpp"
#include "etl/_tuple/tuple.hpp"
#include "etl/_type_traits/decay.hpp"
#include "etl/_utility/forward.hpp"
namespace etl {
namespace detail {
template <typename T>
struct unwrap_refwrapper {
using type = T;
};
template <typename T>
struct unwrap_refwrapper<reference_wrapper<T>> {
using type = T&;
};
template <typename T>
using unwrap_decay_t = typename unwrap_refwrapper<decay_t<T>>::type;
} // namespace detail
/// \brief Creates a tuple object, deducing the target type from the types of
/// arguments.
template <typename... Types>
[[nodiscard]] constexpr auto make_tuple(Types&&... args)
{
return tuple<detail::unwrap_decay_t<Types>...>(forward<Types>(args)...);
}
} // namespace etl
#endif // TETL_TUPLE_MAKE_TUPLE_HPP
| 24.880952 | 77 | 0.747368 | [
"object"
] |
099068d2145af1a499ed6a9b5e679ac8d181d7e7 | 7,527 | cpp | C++ | rr_iarrc/src/laplacian_line_detection/laplacian_line_detector.cpp | ldricci3/roboracing-software | d6059042d831f6523e93ae59e7eb246e7664dabc | [
"MIT"
] | null | null | null | rr_iarrc/src/laplacian_line_detection/laplacian_line_detector.cpp | ldricci3/roboracing-software | d6059042d831f6523e93ae59e7eb246e7664dabc | [
"MIT"
] | null | null | null | rr_iarrc/src/laplacian_line_detection/laplacian_line_detector.cpp | ldricci3/roboracing-software | d6059042d831f6523e93ae59e7eb246e7664dabc | [
"MIT"
] | null | null | null | #include <ros/ros.h>
#include <ros/publisher.h>
#include <cv_bridge/cv_bridge.h>
#include <sensor_msgs/Image.h>
#include <opencv2/opencv.hpp>
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
using namespace std;
cv::Mat kernel(int, int);
cv::Mat fillColorLines(const cv::Mat&, const cv::Mat&);
void blockEnvironment(const cv::Mat&);
cv::Mat cutSmall(const cv::Mat&, int);
void publishMessage(const ros::Publisher, const cv::Mat&, std::string);
cv::Mat overlayBinaryGreen(cv::Mat&, const cv::Mat&);
cv::Mat removeAngels(const cv::Mat& img, int distanceFromEarth);
cv_bridge::CvImagePtr cv_ptr;
ros::Publisher pub_line_detector, pub_debug_adaptive, pub_debug_laplacian, pub_debug_overlay;
int blockSky_height, blockWheels_height, blockBumper_height;
int perfect_lines_min_cut, Laplacian_threshold, adaptive_mean_threshold;
int originalWidth, originalHeight;
int decreasedSize = 400;
/**
* Performs Adaptive Threshold to find areas where we are certain there are lines then
* those areas are floodfilled on a Laplacian that has more noise but the entirety of the line.
*
* @param msg image input from camera
*/
void img_callback(const sensor_msgs::ImageConstPtr& msg) {
//Convert msg to Mat image
cv_ptr = cv_bridge::toCvCopy(msg, "bgr8");
cv::Mat frame = cv_ptr->image;
//Store original dimensions and resize
originalHeight = frame.rows;
originalWidth = frame.cols;
cv::resize(frame, frame, cv::Size(decreasedSize, decreasedSize));
//Blur and convert to GrayScale
cv::Mat frame_gray, frame_blur, detected_edges;
cv::GaussianBlur(frame, frame_blur, cv::Size(5,5), 0);
cv::cvtColor(frame_blur, frame_gray, cv::COLOR_BGR2GRAY);
//Performing Adaptive Threshold to detect high-contrast lines in different lighting conditions
//Cut image to ROI, erode small noise, and removes any blob less than a minimum area
//The adaptive image (Little Noise / High Certainty) will represent where we are certain lines are located
cv::Mat thres;
cv::adaptiveThreshold(frame_gray, thres, 255, cv::ADAPTIVE_THRESH_GAUSSIAN_C, cv::THRESH_BINARY, 5, -1);
blockEnvironment(thres);
cv::erode(thres, thres, kernel(3,1));
cv::Mat cut = cutSmall(thres, perfect_lines_min_cut);
//Perform Laplacian operation to find strong edges
//The laplacian image (High Noise / Low Certainty) will allow us to floodfill the whole line in case the adaptive
//only found a small part of it
cv::Mat lapl;
cv::Laplacian(frame_gray, lapl, CV_16S, 3, 1, 0, cv::BORDER_DEFAULT);
cv::threshold(lapl, lapl, -Laplacian_threshold, 255, 1);
cv::convertScaleAbs(lapl, lapl);
//FloodFills the Laplacian at points where we are certain lines are located
//Perform another cut to remove any small resultant noise
cv::Mat fill = fillColorLines(lapl, cut);
fill = cutSmall(fill, perfect_lines_min_cut);
//Make debug green overlay img and resize resultant image to initial dimensions
cv::Mat green_lines = overlayBinaryGreen(frame, fill);
cv::resize(fill, fill, cv::Size(originalWidth, originalHeight));
//Publish Messages
publishMessage(pub_line_detector, fill, "mono8");
publishMessage(pub_debug_adaptive, thres, "mono8");
publishMessage(pub_debug_laplacian, lapl, "mono8");
publishMessage(pub_debug_overlay, green_lines, "bgr8");
}
int main(int argc, char** argv) {
ros::init(argc, argv, "Laplacian");
ros::NodeHandle nh;
ros::NodeHandle nhp("~");
std::string subscription_node;
nhp.param("perfect_lines_min_cut", perfect_lines_min_cut, 200);
nhp.param("Laplacian_threshold", Laplacian_threshold, 2);
nhp.param("adaptive_mean_threshold", adaptive_mean_threshold, 1);
nhp.param("blockSky_height", blockSky_height, 220);
nhp.param("blockWheels_height", blockWheels_height, 200);
nhp.param("blockBumper_height", blockBumper_height, 200);
nhp.param("subscription_node", subscription_node, std::string("/camera/image_color_rect"));
pub_line_detector = nh.advertise<sensor_msgs::Image>("/lines/detection_img", 1); //test publish of image
pub_debug_adaptive = nh.advertise<sensor_msgs::Image>("/lines/debug_adaptive", 1);
pub_debug_laplacian = nh.advertise<sensor_msgs::Image>("/lines/debug_laplacian", 1);
pub_debug_overlay = nh.advertise<sensor_msgs::Image>("/lines/debug_overlay", 1);
auto img_real = nh.subscribe(subscription_node, 1, img_callback);
ros::spin();
return 0;
}
cv::Mat kernel(int x, int y) {
return cv::getStructuringElement(cv::MORPH_RECT,cv::Size(x,y));
}
cv::Mat fillColorLines(const cv::Mat& lines, const cv::Mat& color_found) {
cv::Mat color_left, lines_found(lines.rows,lines.cols,CV_8UC1,cv::Scalar::all(0));
cv::Mat lines_remaining = lines.clone();
lines.copyTo(color_left, color_found);
std::vector<std::vector<cv::Point>> contours;
cv::findContours(color_left, contours,CV_RETR_CCOMP, CV_CHAIN_APPROX_SIMPLE);
for(int i = 0; i < contours.size(); i++ ) {
cv::floodFill(lines_remaining, contours[i][0], cv::Scalar(0));
}
cv::bitwise_xor(lines, lines_remaining, lines_found);
return lines_found;
}
void blockEnvironment(const cv::Mat& img) {
cv::rectangle(img,
cv::Point(0,0),
cv::Point(img.cols, blockSky_height * decreasedSize / originalHeight),
cv::Scalar(0,0,0),CV_FILLED);
cv::rectangle(img,
cv::Point(0,img.rows),
cv::Point(img.cols, blockWheels_height * decreasedSize / originalHeight),
cv::Scalar(0,0,0),CV_FILLED);
cv::rectangle(img,
cv::Point(img.cols/3,img.rows),
cv::Point(2 * img.cols / 3, blockBumper_height * decreasedSize / originalHeight),
cv::Scalar(0,0,0),CV_FILLED);
}
cv::Mat cutSmall(const cv::Mat& color_edges, int size_min) {
cv::Mat contours_color(color_edges.rows,color_edges.cols,CV_8UC1,cv::Scalar::all(0));
std::vector<std::vector<cv::Point>> contours;
cv::findContours(color_edges, contours,CV_RETR_CCOMP, CV_CHAIN_APPROX_SIMPLE);
for( int i = 0; i < contours.size(); i++ ) {
if (size_min < cv::arcLength(contours[i], false) ) {
cv::drawContours(contours_color, contours, i, cv::Scalar(255), CV_FILLED, 8);
}
}
return contours_color;
}
void publishMessage(const ros::Publisher pub, const cv::Mat& img, std::string img_type) {
if (pub.getNumSubscribers() > 0) {
sensor_msgs::Image outmsg;
cv_ptr->image = img;
cv_ptr->encoding = img_type;
cv_ptr->toImageMsg(outmsg);
pub.publish(outmsg);
}
}
cv::Mat overlayBinaryGreen(cv::Mat& frame, const cv::Mat& binary) {
return frame.setTo(cv::Scalar(0,255,0), binary != 0);
}
cv::Mat removeAngels(const cv::Mat& img, int distanceFromEarth) {
//Removes anything that extends from the top of the image to the bottom like glare from the sun
cv::Mat top = img.clone();
cv::rectangle(top,
cv::Point(0,img.rows / 3 + blockSky_height - distanceFromEarth),
cv::Point(img.cols,img.rows),
cv::Scalar(0),CV_FILLED);
std::vector<cv::Point> locations;
cv::findNonZero(top, locations);
int number_of_angles = 20;
for (int i = 0; i < number_of_angles; ++i) {
cv::floodFill(img, locations[i], cv::Scalar(0));
cv::floodFill(top, locations[i], cv::Scalar(0));
cv::findNonZero(top, locations);
}
return img;
}
| 39.825397 | 117 | 0.687791 | [
"vector"
] |
09943e04aae2330e1eb1ffd2432cd6313f4eb62e | 72,356 | cpp | C++ | verifier/Verifier.cpp | oi02lyl/has-verifier | 513c0e975ab591146d7e50ecd657deac9a66f0e4 | [
"MIT"
] | 1 | 2017-01-26T00:16:56.000Z | 2017-01-26T00:16:56.000Z | verifier/Verifier.cpp | oi02lyl/has-verifier | 513c0e975ab591146d7e50ecd657deac9a66f0e4 | [
"MIT"
] | null | null | null | verifier/Verifier.cpp | oi02lyl/has-verifier | 513c0e975ab591146d7e50ecd657deac9a66f0e4 | [
"MIT"
] | null | null | null | /*
* Verifier.cpp
*
* Created on: Feb 3, 2016
* Author: lyl
*/
#include "Verifier.h"
#include <stack>
#include <queue>
#include <vector>
#include <set>
#include <unordered_set>
#include <unordered_map>
#include <map>
#include <algorithm>
namespace std {
Node::Node() {
expr_id = -1;
}
Node::~Node() {
}
bool Node::is_const() {
return false;
}
bool Node::is_navi() {
return false;
}
bool Node::is_var() {
return false;
}
bool ConstNode::is_const() {
return true;
}
bool VarNode::is_var() {
return true;
}
bool NaviNode::is_navi() {
return true;
}
// recursively build the full navigation set
void Verifier::build_tree(Node*& res, int taskid, int varid, int par_expr_id,
int type, string prefix, int& num_expr) {
DBSchema& schema = art.db;
NaviNode* node = new NaviNode();
res = node;
node->expr_id = num_expr++;
node->type = type;
node->par_expr_id = par_expr_id;
expr_name.push_back(prefix);
expr_to_node.push_back(node);
task_var_expr_ids[taskid][varid].insert(node->expr_id);
if (type >= 0) {
node->children = vector<Node*>(schema.relations[type].arity - 1, NULL);
// printf("%d\n", current);
for (int i = 0; i < schema.relations[type].arity - 1; i++) {
char name[30];
sprintf(name, "%s.%d", prefix.c_str(), i + 1);
build_tree(node->children[i], taskid, varid, node->expr_id,
schema.relations[type].types[i + 1], name, num_expr);
}
}
}
void Verifier::add_rename(Node* parent_node, Node* child_node, int task_id,
int child_id) {
// TODO handle the case when input and return variables overlap in the parent
// rename to parent
expr_rename_to_parent[child_node->expr_id] = parent_node->expr_id;
// rename to children
if (expr_rename_to_child[parent_node->expr_id].empty())
expr_rename_to_child[parent_node->expr_id] = vector<int>(
art.tasks[task_id].children.size());
expr_rename_to_child[parent_node->expr_id][child_id] = child_node->expr_id;
if (parent_node->is_navi()) {
NaviNode* n1 = (NaviNode*) parent_node;
NaviNode* n2 = (NaviNode*) child_node;
if (n1->children.size() != n2->children.size()) {
exit(0);
}
for (int i = 0; i < (int) n1->children.size(); i++)
add_rename(n1->children[i], n2->children[i], task_id, child_id);
} else if (parent_node->is_var()) {
VarNode* n1 = (VarNode*) parent_node;
VarNode* n2 = (VarNode*) child_node;
if (n1->children.size() != n2->children.size()) {
printf(
"Bug add rename, id1 = %d, id2 = %d, task = %d, child_id = %d\n",
n1->id, n2->id, task_id, child_id);
exit(0);
}
for (int i = 0; i < (int) n1->children.size(); i++)
add_rename(n1->children[i], n2->children[i], task_id, child_id);
}
}
void Verifier::form_to_dnf_negdown(Formula* form, int task_id,
vector<Conjunct>& conjuncts) {
pushdown_neg(form, false);
vector<Conjunct> res;
form_to_dnf(form, task_id, res);
// remove duplicates
for (Conjunct dj : res) {
sort(dj.eqs.begin(), dj.eqs.end());
sort(dj.uneqs.begin(), dj.uneqs.end());
}
sort(res.begin(), res.end());
conjuncts.clear();
int N = res.size();
for (int i = 0; i < N; i++) {
conjuncts.push_back(res[i]);
while (i + 1 < N && res[i] == res[i + 1])
i++;
}
}
void Verifier::form_to_dnf(Formula* form, int task_id, vector<Conjunct>& res) {
// printf("%s\n", form->to_string().c_str());
if (form == NULL)
return;
if (form->is_const()) {
ConstTerm* term = (ConstTerm*) form;
Conjunct d;
if (!term->value)
d.uneqs.push_back(pair<int, int>(0, 0));
res.push_back(d);
}
if (form->is_cmp()) {
CmpTerm* term = (CmpTerm*) form;
Conjunct d;
int expr1 = para_to_expr(term->p1, task_id);
int expr2 = para_to_expr(term->p2, task_id);
pair<int, int> pair1(expr1, expr2);
pair<int, int> pair2(expr2, expr1);
if (expr1 >= 0 && expr2 >= 0) {
if (unique_sign_pairs.count(pair1) == 0 && unique_sign_pairs.count(pair2) == 0) {
if (term->equal)
d.eqs.push_back(pair<int, int>(expr1, expr2));
else
d.uneqs.push_back(pair<int, int>(expr1, expr2));
}
res.push_back(d);
}
} else if (form->is_relation()) {
RelationTerm* term = (RelationTerm*) form;
vector<int> lefts, rights;
for (int i = 1; i < (int) term->paras.size(); i++) {
int expr_right = para_to_expr(term->paras[i], task_id);
if (expr_right >= 0) {
lefts.push_back(
get_expr_id_navi(task_id, term->paras[0].id, i - 1));
rights.push_back(expr_right);
}
}
if (term->negated) {
for (int i = 0; i < (int) lefts.size(); i++) {
Conjunct d;
pair<int, int> p1(lefts[i], rights[i]);
pair<int, int> p2(rights[i], lefts[i]);
if (unique_sign_pairs.count(p1) == 0 && unique_sign_pairs.count(p2) == 0)
d.uneqs.push_back(pair<int, int>(lefts[i], rights[i]));
res.push_back(d);
}
} else {
Conjunct d;
for (int i = 0; i < (int) lefts.size(); i++) {
pair<int, int> p1(lefts[i], rights[i]);
pair<int, int> p2(rights[i], lefts[i]);
if (unique_sign_pairs.count(p1) == 0 && unique_sign_pairs.count(p2) == 0)
d.eqs.push_back(pair<int, int>(lefts[i], rights[i]));
}
res.push_back(d);
}
} else if (form->is_internal()) {
Internal* term = (Internal*) form;
if (term->op == "&&") {
vector<Conjunct> left, right;
State tmp;
form_to_dnf(term->paras[0], task_id, left);
form_to_dnf(term->paras[1], task_id, right);
for (Conjunct& dl : left)
for (Conjunct& dr : right) {
Conjunct d = dl;
d.eqs.insert(d.eqs.end(), dr.eqs.begin(), dr.eqs.end());
d.uneqs.insert(d.uneqs.end(), dr.uneqs.begin(),
dr.uneqs.end());
// remove formulas that are not satisfiable
set<int> exprs;
for (auto& pp : d.eqs) {
exprs.insert(pp.first);
exprs.insert(pp.second);
}
for (auto& pp : d.uneqs) {
exprs.insert(pp.first);
exprs.insert(pp.second);
}
tmp.exprs = vector<int>(exprs.begin(), exprs.end());
if (convert_eqls_to_state(d, tmp)) {
res.push_back(d);
}
}
} else {
form_to_dnf(term->paras[0], task_id, res);
form_to_dnf(term->paras[1], task_id, res);
}
}
}
void Verifier::preprocess_atms() {
if (!atm_var_id.empty())
return;
atm_var_id = vector<int>(atms.size(), -1);
atm_task = vector<vector<int> >(art.tasks.size(), vector<int>());
for (int atm_id = 0; atm_id < (int) atms.size(); atm_id++){
Automaton& atm = atms[atm_id];
Task& task = art.tasks[atm.taskid];
task.var_types.push_back(-2);
int varid = task.num_var;
task.vars.push_back(varid);
task.num_var++;
atm_var_id[atm_id] = varid;
atm_task[atm.taskid].push_back(atm_id);
if (atm.num_states > (int) art.str_consts.size()) {
while (atm.num_states > (int) art.str_consts.size()) {
int sid = (int) art.str_consts.size();
char str[30];
sprintf(str, "S%d", sid);
art.str_consts.push_back(str);
}
}
}
}
// build the full navigation set
void Verifier::preprocess() {
int num_tasks = art.tasks.size();
// preprocess atms
preprocess_atms();
// profile
profile_vstate_set = vector<set<VASSState> >(num_tasks, set<VASSState>());
profile_cyclomatic = vector<int>(num_tasks, 0);
// reach_map
reach_map = vector<map<VASSState, vector<tuple<State, State, vector<int> > >*> >(num_tasks,
map<VASSState, vector<tuple<State, State, vector<int> > >*>());
empty_states = vector<vector<VASSState> >(num_tasks, vector<VASSState>());
empty_states_tries = vector<TrieNode*>(num_tasks, NULL);
for (int i = 0; i < num_tasks; i++)
empty_states_tries[i] = new TrieNode();
// modify each task to add set variables
for (int i = 0; i < num_tasks; i++)
art.tasks[i].add_set_vars();
// compute input, return and unchanged variables
input_vars = vector<vector<int> >(num_tasks, vector<int>());
passed_vars = vector<vector<int> >(num_tasks, vector<int>());
return_vars = vector<vector<int> >(num_tasks, vector<int>());
returned_vars = vector<vector<int> >(num_tasks, vector<int>());
unchanged_vars = vector<vector<int> >(num_tasks, vector<int>());
for (int i = 0; i < num_tasks; i++) {
Task& task = art.tasks[i];
for (auto& pp : task.input_vars) {
passed_vars[i].push_back(pp.first);
input_vars[i].push_back(pp.second);
}
for (auto& pp : task.return_vars) {
return_vars[i].push_back(pp.first);
returned_vars[i].push_back(pp.second);
}
int num_child = task.children.size();
for (int j = 0; j < num_child; j++) {
Task& child = art.tasks[task.children[j]];
set<int> changed;
for (auto& pp : child.return_vars)
changed.insert(pp.second);
for (int vid : task.vars)
if (changed.count(vid) == 0)
unchanged_vars[task.children[j]].push_back(vid);
}
}
// clean up
expr_name.clear();
expr_to_node.clear();
task_var_expr_ids = vector<vector<set<int> > >(num_tasks,
vector<set<int> >());
task_var_expr = vector<vector<int> >(num_tasks, vector<int>());
for (int i = 0; i < num_tasks; i++) {
task_var_expr_ids[i] = vector<set<int> >(art.tasks[i].num_var,
set<int>());
task_var_expr[i] = vector<int>(art.tasks[i].num_var, -1);
}
int num_expr = 0;
// numeric consts
for (int i = 0; i < (int) art.num_consts.size(); i++) {
ConstNode* node = new ConstNode();
node->id = i;
node->expr_id = num_expr++;
node->type = -1;
char name[10];
sprintf(name, "N%d", i);
expr_name.push_back(name);
expr_to_node.push_back(node);
}
// string consts
for (int i = 0; i < (int) art.str_consts.size(); i++) {
ConstNode* node = new ConstNode();
node->id = i;
node->expr_id = num_expr++;
node->type = -2;
char name[10];
sprintf(name, "S%d", i);
expr_name.push_back(name);
expr_to_node.push_back(node);
}
// null const
{
ConstNode* node = new ConstNode();
node->id = -1;
node->expr_id = num_expr++;
node->type = -3;
expr_name.push_back("NULL");
expr_to_node.push_back(node);
}
// variables
for (int taskid = 0; taskid < num_tasks; taskid++) {
Task& task = art.tasks[taskid];
for (int idx = 0; idx < (int) task.vars.size(); idx++) {
VarNode* node = new VarNode();
node->id = task.vars[idx];
node->type = task.var_types[idx];
node->taskid = taskid;
node->expr_id = num_expr++;
task_var_expr_ids[taskid][idx].insert(node->expr_id);
task_var_expr[taskid][idx] = node->expr_id;
char name[10];
sprintf(name, "T%d.X%d", taskid, idx);
expr_name.push_back(name);
expr_to_node.push_back(node);
if (task.var_types[idx] >= 0) {
int rel_id = task.var_types[idx];
int arity = art.db.relations[rel_id].arity;
node->children = vector<Node*>(arity - 1, NULL);
for (int i = 0; i < arity - 1; i++) {
int type = art.db.relations[rel_id].types[i + 1];
char child_name[15];
sprintf(child_name, "%s.%d", name, i + 1);
build_tree(node->children[i], taskid, node->id,
node->expr_id, type, child_name, num_expr);
}
}
}
}
// build indices for renaming variables
expr_rename_to_parent = vector<int>(num_expr, -1);
expr_rename_to_child = vector<vector<int> >(num_expr, vector<int>());
for (int par_task_id = 0; par_task_id < num_tasks; par_task_id++) {
Task& task = art.tasks[par_task_id];
for (int child_id = 0; child_id < (int) task.children.size();
child_id++) {
int child_task_id = task.children[child_id];
Task& child_task = art.tasks[child_task_id];
for (auto& pp : child_task.input_vars) {
int parent_expr = task_var_expr[par_task_id][pp.first];
int child_expr = task_var_expr[child_task_id][pp.second];
add_rename(expr_to_node[parent_expr], expr_to_node[child_expr],
par_task_id, child_id);
}
for (auto& pp : child_task.return_vars) {
int parent_expr = task_var_expr[par_task_id][pp.second];
int child_expr = task_var_expr[child_task_id][pp.first];
add_rename(expr_to_node[parent_expr], expr_to_node[child_expr],
par_task_id, child_id);
}
}
}
// printf("Start pre-processing formulas\n");
// static analysis for unique sign pairs
get_unique_sign_pairs();
// pre-process formulas
open_conds = vector<vector<Conjunct> >(num_tasks, vector<Conjunct>());
close_conds = vector<vector<Conjunct> >(num_tasks, vector<Conjunct>());
pre_conds = vector<vector<vector<Conjunct> > >(num_tasks,
vector<vector<Conjunct> >());
post_conds = vector<vector<vector<Conjunct> > >(num_tasks,
vector<vector<Conjunct> >());
global_pre_conds.clear();
form_to_dnf_negdown(art.global_pre_cond, 0, global_pre_conds);
vector<int> parent_task(num_tasks, -1);
for (int task_id = 0; task_id < num_tasks; task_id++)
for (int ch : art.tasks[task_id].children)
parent_task[ch] = task_id;
parent_task[0] = 0;
for (int task_id = 0; task_id < num_tasks; task_id++) {
form_to_dnf_negdown(art.tasks[task_id].open_cond, parent_task[task_id],
open_conds[task_id]);
form_to_dnf_negdown(art.tasks[task_id].close_cond, task_id,
close_conds[task_id]);
int num_sers = art.tasks[task_id].services.size();
pre_conds[task_id] = vector<vector<Conjunct> >(num_sers,
vector<Conjunct>());
post_conds[task_id] = vector<vector<Conjunct> >(num_sers,
vector<Conjunct>());
for (int ser_id = 0; ser_id < num_sers; ser_id++) {
form_to_dnf_negdown(art.tasks[task_id].services[ser_id].pre_cond,
task_id, pre_conds[task_id][ser_id]);
form_to_dnf_negdown(art.tasks[task_id].services[ser_id].post_cond,
task_id, post_conds[task_id][ser_id]);
}
}
// find zero, empty string and null
for (int i = 0; i < (int) art.num_consts.size(); i++)
if (art.num_consts[i] == 0)
zero_id = i;
for (int i = 0; i < (int) art.str_consts.size(); i++)
if (art.str_consts[i] == "\"\"")
empty_id = i;
zero_id = get_expr_id_const(-1, zero_id);
empty_id = get_expr_id_const(-2, empty_id);
null_id = get_expr_id_const(-3, 0);
}
int Verifier::para_to_expr(Parameter& para, int task_id) {
if (para.is_wildcard)
return -1;
if (para.is_const)
return get_expr_id_const(para.type, para.id);
else
return get_expr_id_var(task_id, para.id);
}
int Verifier::get_expr_id_const(int type, int id) {
if (type == -1)
return id;
else if (type == -2)
return id + art.num_consts.size();
else
return art.num_consts.size() + art.str_consts.size();
}
int Verifier::get_expr_id_var(int task_id, int vid) {
return task_var_expr[task_id][vid];
}
int Verifier::get_expr_id_navi(int task_id, int vid, int attr) {
return ((VarNode*) expr_to_node[task_var_expr[task_id][vid]])->children[attr]->expr_id;
}
bool Verifier::is_null(int expr) {
if (expr_to_node[expr]->is_const()) {
ConstNode* node = (ConstNode*) expr_to_node[expr];
return node->type == -3;
} else
return false;
}
bool Verifier::is_const(int expr) {
return expr_to_node[expr]->is_const();
}
bool Verifier::is_var(int expr) {
return expr_to_node[expr]->is_var();
}
bool Verifier::is_navi(int expr) {
return expr_to_node[expr]->is_navi();
}
int debug_cnt = 5;
// compute the projection of a state to a set of variables
void Verifier::project(State& state, int taskid, vector<int>& vars,
State& res) {
// printf("project\n");
// initialize
res.exprs.clear();
res.eq_classes.clear();
res.uneqs.clear();
int num_expr = state.exprs.size();
vector<bool> keep(num_expr, false);
// the number of equivalence classes
int num_eqc = 0;
for (int i = 0; i < num_expr; i++)
if (state.eq_classes[i] + 1 > num_eqc)
num_eqc = state.eq_classes[i] + 1;
vector<int> eq_cnt(num_eqc, 0);
// compute the set of expressions to be kept
for (int i = 0; i < num_expr; i++) {
int expr = state.exprs[i];
if (is_const(expr))
keep[i] = true;
else {
for (int x : vars) {
if (task_var_expr_ids[taskid][x].count(expr)) {
keep[i] = true;
break;
}
}
}
if (keep[i]) {
int eqc = state.eq_classes[i];
eq_cnt[eqc]++;
}
}
for (auto& pp : state.uneqs)
if (eq_cnt[pp.first] > 0 && eq_cnt[pp.second] > 0) {
eq_cnt[pp.first]++;
eq_cnt[pp.second]++;
}
vector<int> new_eq_idx(num_eqc, -1);
int num_new_eq = 0;
for (int i = 0; i < num_expr; i++)
if (keep[i] && eq_cnt[state.eq_classes[i]] > 1) {
res.exprs.push_back(state.exprs[i]);
// set equivalence classes
if (new_eq_idx[state.eq_classes[i]] < 0)
new_eq_idx[state.eq_classes[i]] = num_new_eq++;
res.eq_classes.push_back(new_eq_idx[state.eq_classes[i]]);
}
for (auto pp : state.uneqs) {
if (new_eq_idx[pp.first] >= 0 && new_eq_idx[pp.second] >= 0) {
int e1 = new_eq_idx[pp.first];
int e2 = new_eq_idx[pp.second];
if (e1 > e2)
swap(e1, e2);
res.uneqs.push_back(pair<int, int>(e1, e2));
}
}
sort(res.uneqs.begin(), res.uneqs.end());
//
// if (debug_cnt >= 0) {
// for (int var : vars)
// printf("X%d ", var);
// printf("\nBefore:\n");
// dump_state(state);
// printf("After:\n");
// dump_state(res);
// printf("\n");
// debug_cnt--;
// }
}
void Verifier::insert_state_to_eqls(State& state, Conjunct& conjunct) {
vector<pair<int, int> >& eqs = conjunct.eqs;
vector<pair<int, int> >& uneqs = conjunct.uneqs;
int num_expr = state.exprs.size();
int num_eqc = 0;
for (int i = 0; i < num_expr; i++)
if (state.eq_classes[i] + 1 > num_eqc)
num_eqc = state.eq_classes[i] + 1;
vector<vector<int> > eq_sets(num_eqc, vector<int>());
for (int i = 0; i < num_expr; i++)
eq_sets[state.eq_classes[i]].push_back(state.exprs[i]);
for (int i = 0; i < num_eqc; i++)
for (int j = 1; j < (int) eq_sets[i].size(); j++)
if (eq_sets[i][0] < eq_sets[i][j])
eqs.push_back(pair<int, int>(eq_sets[i][0], eq_sets[i][j]));
else
eqs.push_back(pair<int, int>(eq_sets[i][j], eq_sets[i][0]));
for (auto pp : state.uneqs) {
int e1 = eq_sets[pp.first][0];
int e2 = eq_sets[pp.second][0];
if (e1 < e2)
uneqs.push_back(pair<int, int>(e1, e2));
else
uneqs.push_back(pair<int, int>(e2, e1));
}
}
bool pair_first_comp(pair<int, int> l, pair<int, int> r) {
return l.first < r.first;
}
void Verifier::get_child_expr(int expr, vector<int>& res) {
res.clear();
Node* node = expr_to_node[expr];
if (node->is_var()) {
VarNode* vn = (VarNode*) node;
for (Node* child : vn->children)
if (child != NULL)
res.push_back(child->expr_id);
} else if (node->is_navi()) {
NaviNode* vn = (NaviNode*) node;
for (Node* child : vn->children)
if (child != NULL)
res.push_back(child->expr_id);
}
}
void Verifier::rename_to_set(int task_id, int set_id, vector<int>& vars,
State& state) {
vector<int>& set_vars = art.tasks[task_id].set_var_ids[set_id];
Conjunct dj;
for (int i = 0; i < (int) vars.size(); i++) {
int svid = set_vars[i];
int expr1 = get_expr_id_var(task_id, vars[i]);
int expr2 = get_expr_id_var(task_id, svid);
dj.eqs.push_back(pair<int, int>(expr1, expr2));
}
State res;
if (!intersect(state, dj, res)) {
printf("bug in rename to set\n");
dump_state(state);
intersect(state, dj, res);
exit(0);
}
project(res, task_id, set_vars, state);
}
void Verifier::rename_from_set(int task_id, int set_id, vector<int>& vars,
State& state) {
vector<int>& set_vars = art.tasks[task_id].set_var_ids[set_id];
Conjunct dj;
for (int i = 0; i < (int) vars.size(); i++) {
int svid = set_vars[i];
int expr1 = get_expr_id_var(task_id, vars[i]);
int expr2 = get_expr_id_var(task_id, svid);
dj.eqs.push_back(pair<int, int>(expr1, expr2));
}
State res;
if (!intersect(state, dj, res)) {
printf("bug in rename from set\n");
exit(0);
}
project(res, task_id, vars, state);
}
int Verifier::union_find_set_find(map<int, int>& parents, int expr) {
if (parents[expr] == expr)
return expr;
vector<int> path;
path.push_back(expr);
while (expr != parents[expr]) {
expr = parents[expr];
path.push_back(expr);
}
for (int ex : path)
parents[ex] = expr;
return expr;
}
void Verifier::union_find_set_union(map<int, int>& parents, int expr1,
int expr2) {
int p1 = union_find_set_find(parents, expr1);
int p2 = union_find_set_find(parents, expr2);
if (p1 == p2)
return;
if (p1 > p2)
swap(p1, p2);
parents[p2] = p1;
vector<int> p1_child_expr, p2_child_expr;
get_child_expr(p1, p1_child_expr);
get_child_expr(p2, p2_child_expr);
if (p1_child_expr.size() == p2_child_expr.size()) {
// printf("BUG!\n");
// printf("%s\n", expr_name[p1].c_str());
// printf("%s\n", expr_name[p2].c_str());
//
// exit(0);
int sz = p1_child_expr.size();
for (int i = 0; i < sz; i++) {
int c1 = p1_child_expr[i];
int c2 = p2_child_expr[i];
if (parents.count(c1) == 0 && parents.count(c2) == 0)
continue;
if (parents.count(c1) == 0)
parents[c1] = c1;
if (parents.count(c2) == 0)
parents[c2] = c2;
union_find_set_union(parents, c1, c2);
}
}
}
void Verifier::get_initial_state(int task_id, State& res) {
Conjunct conjunct;
set<int> input_vars_set(input_vars[task_id].begin(),
input_vars[task_id].end());
set<int> expr_set;
int num_vars = art.tasks[task_id].vars.size();
unordered_set<int> atm_state_exprs;
for (int atm_id : atm_task[task_id])
atm_state_exprs.insert(get_expr_id_var(task_id, atm_var_id[atm_id]));
for (int vid = 0; vid < num_vars; vid++)
if (input_vars_set.count(vid) == 0) {
int type = art.tasks[task_id].var_types[vid];
int expr = task_var_expr[task_id][vid];
// printf("%d %d %d\n", vid, type, expr);
if (type == -1) {
conjunct.eqs.push_back(pair<int, int>(expr, zero_id));
expr_set.insert(zero_id);
} else if (type == -2) {
if (atm_state_exprs.count(expr) == 0) {
conjunct.eqs.push_back(pair<int, int>(expr, empty_id));
expr_set.insert(empty_id);
} else {
// also initialize atm state
int state_expr = get_expr_id_const(-2, 0);
conjunct.eqs.push_back(pair<int, int>(expr, state_expr));
expr_set.insert(state_expr);
}
} else {
conjunct.eqs.push_back(pair<int, int>(expr, null_id));
expr_set.insert(null_id);
}
expr_set.insert(expr);
}
res.exprs = vector<int>(expr_set.begin(), expr_set.end());
convert_eqls_to_state(conjunct, res);
}
// return true if eqs and uneqs can be coverted to a state
// assuming the list of expressions are set in state
bool Verifier::convert_eqls_to_state(Conjunct& conjunct, State& state) {
// printf("convert_eqls_to_state\n");
vector<pair<int, int> >& eqs = conjunct.eqs;
vector<pair<int, int> >& uneqs = conjunct.uneqs;
sort(eqs.begin(), eqs.end());
sort(uneqs.begin(), uneqs.end());
int num_expr = state.exprs.size();
map<int, int> eqc_map;
set<int> const_set;
for (int expr : state.exprs) {
eqc_map[expr] = expr;
if (is_const(expr))
const_set.insert(expr);
}
for (auto& eq : eqs)
union_find_set_union(eqc_map, eq.first, eq.second);
// early pruning
for (auto& pp : uneqs) {
if (eqc_map[pp.first] == eqc_map[pp.second])
return false;
}
for (int expr : state.exprs)
union_find_set_find(eqc_map, expr);
// handle NULLs
int null_par = -1;
for (int expr : state.exprs)
if (is_null(expr))
null_par = eqc_map[expr];
if (null_par >= 0) {
// no navigation can equal to NULL
// if a variable equals NULL, then it has no navigation
for (int expr : state.exprs) {
if (eqc_map[expr] == null_par) {
if (!is_var(expr) && !is_null(expr))
return false;
vector<int> children;
get_child_expr(expr, children);
for (int ch : children)
if (eqc_map.count(ch) > 0)
return false;
}
}
}
int num_eqc = 0;
state.exprs.clear();
for (auto& kv : eqc_map)
state.exprs.push_back(kv.first);
for (int expr : state.exprs) {
int parent = eqc_map[expr];
if (expr == parent)
eqc_map[expr] = num_eqc++;
else
eqc_map[expr] = eqc_map[parent];
}
unordered_set<int> const_eqc_set;
unordered_set<int> non_null_set;
int null_eqc = -1;
// check inconsistency and set uneqs and remove sets with only one element
for (int const_expr : const_set) {
int eqc = eqc_map[const_expr];
if (const_eqc_set.count(eqc) > 0)
return false;
const_eqc_set.insert(eqc);
}
for (int expr : state.exprs) {
if (is_null(expr))
null_eqc = eqc_map[expr];
else {
if (is_navi(expr) || is_const(expr))
non_null_set.insert(eqc_map[expr]);
vector<int> children;
get_child_expr(expr, children);
bool has_child = false;
for (int ch : children)
if (eqc_map.count(ch) > 0) {
has_child = true;
break;
}
if (has_child)
non_null_set.insert(eqc_map[expr]);
}
}
set<pair<int, int> > uneq_set;
for (auto& pp : uneqs) {
int eq1 = eqc_map[pp.first];
int eq2 = eqc_map[pp.second];
if (eq1 > eq2)
swap(eq1, eq2);
if (eq1 == eq2)
return false;
if (((const_eqc_set.count(eq1) == 0 || const_eqc_set.count(eq2) == 0))
&& !(eq1 == null_eqc && non_null_set.count(eq2) > 0)
&& !(eq2 == null_eqc && non_null_set.count(eq1) > 0))
uneq_set.insert(pair<int, int>(eq1, eq2));
}
// state.uneqs = vector<pair<int, int> >(uneq_set.begin(), uneq_set.end());
// printf("here\n");
vector<int> single(num_eqc, 0);
vector<int> unique_parent(num_eqc, -1); // -1: unknown parent -2: not unique
for (auto& pp : eqc_map) {
int eqc = pp.second;
int expr = pp.first;
single[eqc]++;
if (unique_parent[eqc] != -2) {
if (is_const(expr) || is_var(expr))
unique_parent[eqc] = -2;
else {
int par_expr_id = ((NaviNode*) expr_to_node[expr])->par_expr_id;
if (eqc_map.count(par_expr_id) == 0)
unique_parent[eqc] = -2;
else {
int par_eqc = eqc_map[par_expr_id];
if (unique_parent[eqc] == -1)
unique_parent[eqc] = par_eqc;
else if (unique_parent[eqc] != par_eqc)
unique_parent[eqc] = -2;
}
}
}
}
for (auto& pp : uneq_set) {
int eqc1 = pp.first;
int eqc2 = pp.second;
if (single[eqc1] == 0 || single[eqc2] == 0)
continue;
single[eqc1]++;
single[eqc2]++;
unique_parent[eqc1] = -2;
unique_parent[eqc2] = -2;
}
// reconstruct the list of expressions
state.exprs.clear();
state.eq_classes.clear();
state.uneqs.clear();
for (auto& kv : eqc_map) {
if (single[kv.second] == 1 || unique_parent[kv.second] >= 0)
continue;
state.exprs.push_back(kv.first);
state.eq_classes.push_back(kv.second);
}
num_expr = state.exprs.size();
// rename eqc's
int eqc_idx = 0;
vector<int> rename(num_eqc, -1);
for (int i = 0; i < num_expr; i++) {
if (rename[state.eq_classes[i]] < 0)
rename[state.eq_classes[i]] = eqc_idx++;
state.eq_classes[i] = rename[state.eq_classes[i]];
}
for (auto uneq : uneq_set) {
int e1 = rename[uneq.first];
int e2 = rename[uneq.second];
if (e1 >= 0 && e2 >= 0) {
if (e1 > e2)
swap(e1, e2);
state.uneqs.push_back(pair<int, int>(e1, e2));
}
}
sort(state.uneqs.begin(), state.uneqs.end());
/*
for (int i = 0; i < (int) state.uneqs.size(); i++) {
state.uneqs[i].first = rename[state.uneqs[i].first];
state.uneqs[i].second = rename[state.uneqs[i].second];
if (state.uneqs[i].first < 0 || state.uneqs[i].second < 0) {
printf("4: %d %d\n", state.uneqs[i].first, state.uneqs[i].second);
exit(0);
}
}
if (!state.validate()) {
printf("At merging:\n");
dump_state(state);
exit(0);
}
*/
return true;
}
// intersect two states. Return true if the intersection is not empty
bool Verifier::intersect(State& s1, State& s2, State& res) {
// printf("intersect\n");
set<int> expr_set(s1.exprs.begin(), s1.exprs.end());
expr_set.insert(s2.exprs.begin(), s2.exprs.end());
res.exprs = vector<int>(expr_set.begin(), expr_set.end());
Conjunct combined;
insert_state_to_eqls(s1, combined);
insert_state_to_eqls(s2, combined);
bool flag = convert_eqls_to_state(combined, res);
// if (debug_cnt >= 0) {
// printf("S1:\n");
// // printf("%d %d\n", (int) s1.exprs.size(), (int) flag);
// dump_state(s1);
// printf("S2:\n");
// dump_state(s2);
// if (flag) {
// printf("Res:\n");
// dump_state(res);
// } else {
// printf("Res: Empty\n");
// }
// printf("\n");
// debug_cnt--;
// }
return flag;
}
bool Verifier::intersect(State& s, Conjunct& conjunct, State& res) {
set<int> expr_set(s.exprs.begin(), s.exprs.end());
for (auto& pp : conjunct.eqs) {
expr_set.insert(pp.first);
expr_set.insert(pp.second);
}
for (auto& pp : conjunct.uneqs) {
expr_set.insert(pp.first);
expr_set.insert(pp.second);
}
Conjunct combined = conjunct;
insert_state_to_eqls(s, combined);
res.exprs = vector<int>(expr_set.begin(), expr_set.end());
bool flag = convert_eqls_to_state(combined, res);
return flag;
}
bool Verifier::intersect(State& s, vector<Conjunct>& conjuncts,
vector<State>& res) {
set<State> res_set;
for (Conjunct dj : conjuncts) {
State state;
if (intersect(s, dj, state)) {
res_set.insert(state);
// res.push_back(state);
}
}
res = vector<State>(res_set.begin(), res_set.end());
return !res.empty();
}
void Verifier::rename_to_parent(State& state) {
int num_expr = state.exprs.size();
for (int i = 0; i < num_expr; i++)
if (!is_const(state.exprs[i]))
state.exprs[i] = expr_rename_to_parent[state.exprs[i]];
}
void Verifier::rename_to_child(int child_id, State& state) {
int num_expr = state.exprs.size();
for (int i = 0; i < num_expr; i++)
if (!is_const(state.exprs[i]))
state.exprs[i] = expr_rename_to_child[state.exprs[i]][child_id];
}
void Verifier::dump_state(State& state) {
printf("Expressions+EQC:");
for (int i = 0; i < (int) state.exprs.size(); i++)
printf(" %s:%d", expr_name[state.exprs[i]].c_str(),
state.eq_classes[i]);
printf("\nUNEQ:");
for (int i = 0; i < (int) state.uneqs.size(); i++)
printf(" %d:%d", state.uneqs[i].first, state.uneqs[i].second);
printf("\n");
}
void Verifier::dump_vass_state(VASSState& state) {
printf("State:\n");
dump_state(state.state);
for (auto& pp : state.returns) {
printf("child%d:\n", pp.first);
dump_state(pp.second);
}
int cc = 0;
for (auto& pp : state.counters) {
printf("counter%d: cnt = %d\n", cc++, pp.second);
dump_state(pp.first);
}
}
bool Verifier::satisfy() {
vector<tuple<State, State, vector<int> > > res;
reachable_root(res);
for (auto tp : res)
for (int atm_id : get<2>(tp))
if (atm_id == 0)
return true;
return false;
}
void Verifier::reachable_root(vector<tuple<State, State, vector<int> > >& results) {
for (Conjunct& d : global_pre_conds) {
State start;
set<int> exprs;
for (auto& pp : d.eqs) {
exprs.insert(pp.first);
exprs.insert(pp.second);
}
for (auto& pp : d.uneqs) {
exprs.insert(pp.first);
exprs.insert(pp.second);
}
start.exprs = vector<int>(exprs.begin(), exprs.end());
if (convert_eqls_to_state(d, start)) {
vector<tuple<State, State, vector<int> > >* vec = reachable(0, start);
results.insert(results.end(), vec->begin(), vec->end());
}
}
sort(results.begin(), results.end());
}
void Verifier::update_counter(vector<pair<State, int> >& counter, State& state,
int delta) {
vector<pair<State, int> > res;
bool found = false;
for (auto& cnt : counter) {
if (cnt.first == state) {
found = true;
if (cnt.second >= 0) {
int val = cnt.second + delta;
if (val > 0)
res.push_back(pair<State, int>(cnt.first, val));
} else
res.push_back(cnt);
} else
res.push_back(cnt);
}
if (!found && delta > 0)
res.push_back(pair<State, int>(state, delta));
sort(res.begin(), res.end());
counter = res;
}
void Verifier::insert_to_set(int task_id, SetUpdate& su, State& cur_state,
vector<pair<State, int> >& counters) {
State state_insert;
vector<int> inst_vars = su.vars;
inst_vars.insert(inst_vars.end(), input_vars[task_id].begin(),
input_vars[task_id].end());
project(cur_state, task_id, inst_vars, state_insert);
rename_to_set(task_id, su.setid, su.vars, state_insert);
update_counter(counters, state_insert, 1);
}
void Verifier::retrieve_from_set(int task_id, SetUpdate& su, VASSState* vstate,
vector<VASSState*>& next_vstates) {
for (auto& pp : vstate->counters) {
VASSState* next = new VASSState();
State state_retrieved = pp.first;
rename_from_set(task_id, su.setid, su.vars, state_retrieved);
if (intersect(vstate->state, state_retrieved, next->state)) {
next->returns.clear();
next->counters = vstate->counters;
update_counter(next->counters, state_retrieved, -1);
next_vstates.push_back(next);
} else
delete next;
}
}
void Verifier::get_atm_states(int task_id, State& state, vector<pair<int, int> >& results) {
for (int atm_id : atm_task[task_id]) {
int var_id = atm_var_id[atm_id];
int expr = get_expr_id_var(task_id, var_id);
int eqc = -1;
int sid = -1;
for (int i = 0; i < (int) state.exprs.size(); i++)
if (state.exprs[i] == expr) {
eqc = state.eq_classes[i];
break;
}
if (eqc >= 0) {
for (int i = 0; i < (int) state.exprs.size(); i++)
if (state.eq_classes[i] == eqc) {
int e = state.exprs[i];
if (is_const(e)) {
ConstNode* const_node = (ConstNode*) expr_to_node[e];
if (const_node->type == -2)
sid = const_node->id;
}
}
if (sid >= 0)
results.push_back(pair<int, int>(atm_id, sid));
}
}
}
void Verifier::make_atm_transition(int task_id, VASSState* now,
vector<pair<int, int> >& prev_atm_states, int ser_id, bool is_open,
int child_id, vector<int>& accepted_child_atms, vector<VASSState*>& results) {
results.clear();
results.push_back(now);
for (pair<int, int>& atm_state : prev_atm_states) {
int atm_id = atm_state.first;
int state_id = atm_state.second;
vector<VASSState*> new_results;
for (VASSState* vstate : results) {
for (pair<vector<AProp*>, int>& trans : atms[atm_id].transition[state_id]) {
vector<VASSState*> next_set;
VASSState* new_vstate = new VASSState();
*new_vstate = *vstate;
next_set.push_back(new_vstate);
bool valid = true;
for (AProp* prop : trans.first) {
if (prop->is_fo()) {
vector<Conjunct> conjuncts;
get_atm_form_conjunct((APropFO*) prop, task_id,
conjuncts);
vector<VASSState*> new_next_set;
for (Conjunct& dis : conjuncts) {
for (VASSState* next : next_set) {
State tmp;
if (intersect(next->state, dis, tmp)) {
VASSState* new_vstate = new VASSState();
*new_vstate = *next;
new_vstate->state = tmp;
new_next_set.push_back(new_vstate);
}
}
}
for (VASSState* next : next_set)
delete next;
next_set = new_next_set;
if (next_set.empty()) {
valid = false;
break;
}
} else if (prop->is_child()) {
APropChild* apc = (APropChild*) prop;
bool flag = (ser_id < 0 && apc->child_id == child_id
&& apc->is_open == is_open);
if (flag == prop->negated) {
valid = false;
break;
}
} else if (prop->is_service()) {
APropService* aps = (APropService*) prop;
bool flag = (ser_id >= 0 && aps->ser_id == ser_id);
if (flag == prop->negated) {
valid = false;
break;
}
} else {
APropSubForm* apsf = (APropSubForm*) prop;
bool flag = (ser_id >= 0 && is_open
&& apsf->child_id == child_id);
if (flag) {
bool accept = false;
for (int accepted_atm : accepted_child_atms) {
if (accepted_atm == apsf->auto_id) {
accept = true;
break;
}
}
if (!accept)
flag = false;
}
if (flag != prop->negated) {
valid = false;
break;
}
}
}
if (valid) {
for (VASSState* next : next_set) {
Conjunct dis;
int expr1 = get_expr_id_const(-2, trans.second);
int expr2 = get_expr_id_var(task_id, atm_var_id[atm_id]);
dis.eqs.push_back(pair<int, int>(expr1, expr2));
State tmp;
if (intersect(next->state, dis, tmp)) {
next->state = tmp;
new_results.push_back(next);
}
}
} else {
for (VASSState* next : next_set)
delete next;
}
}
}
for (VASSState* vstate : results)
delete vstate;
results.clear();
set<VASSState> vstate_sets;
for (VASSState* vstate : new_results) {
if (vstate_sets.count(*vstate) == 0) {
results.push_back(vstate);
vstate_sets.insert(*vstate);
} else {
delete vstate;
}
}
}
}
void Verifier::get_atm_form_conjunct(APropFO* prop, int task_id,
vector<Conjunct>& result) {
if (atm_form_dis_map.count(prop) > 0)
result = atm_form_dis_map[prop];
if (prop->negated) {
Internal* new_form = new Internal();
new_form->op = "!";
new_form->paras.push_back(prop->fo->copy());
prop->fo = new_form;
}
form_to_dnf_negdown(prop->fo, task_id, result);
atm_form_dis_map[prop] = result;
}
void Verifier::get_next_states(int task_id, VASSState* vstate,
vector<VASSState*>& results) {
clock_t start = clock();
results.clear();
Task& task = art.tasks[task_id];
int num_child = task.children.size();
int num_sers = task.services.size();
bool no_active = vstate->returns.empty();
unordered_set<int> active_child;
for (auto& pp : vstate->returns)
active_child.insert(pp.first);
vector<pair<int, int> > prev_atm_states;
get_atm_states(task_id, vstate->state, prev_atm_states);
VASSState* next = NULL;
vector<State> vec_tmp;
// opening child task
for (int i = 0; i < num_child; i++) {
if (active_child.count(i) == 0
&& intersect(vstate->state, open_conds[task.children[i]],
vec_tmp)) {
for (State& after_precond : vec_tmp) {
State input;
project(after_precond, task_id, passed_vars[task.children[i]],
input);
rename_to_child(i, input);
vector<tuple<State, State, vector<int> > >* outputs;
time_nextstate += clock() - start;
outputs = reachable(task.children[i], input);
start = clock();
for (tuple<State, State, vector<int> >& out : *outputs) {
next = new VASSState();
if (!intersect(after_precond, get<0>(out), next->state))
continue;
next->returns = vstate->returns;
next->returns.push_back(pair<int, State>(i, get<1>(out)));
sort(next->returns.begin(), next->returns.end());
next->counters = vstate->counters;
vector<VASSState*> next_set;
make_atm_transition(task_id, next, prev_atm_states, -1,
true, i, get<2>(out), next_set);
results.insert(results.end(), next_set.begin(),
next_set.end());
// results.push_back(next);
}
}
}
}
// closing child task
for (auto& ret : vstate->returns) {
int i = ret.first;
State tmp;
project(vstate->state, task_id, unchanged_vars[task.children[i]], tmp);
next = new VASSState();
if (intersect(tmp, ret.second, next->state)) {
for (auto& pp : vstate->returns)
if (pp.first != i)
next->returns.push_back(pp);
next->counters = vstate->counters;
vector<VASSState*> next_set;
vector<int> tmp;
make_atm_transition(task_id, next, prev_atm_states, -1,
false, i, tmp, next_set);
results.insert(results.end(), next_set.begin(),
next_set.end());
}
}
// applying internal service
if (no_active) {
for (int i = 0; i < num_sers; i++) {
// get insert and retrieve info
vector<SetUpdate> retrieve;
vector<SetUpdate> insert_before;
vector<SetUpdate> insert_after;
// handle insert before and insert after
// handle multiple insert and retrieve
for (SetUpdate& su : task.services[i].set_update) {
if (su.type == InsertBefore)
insert_before.push_back(su);
else if (su.type == InsertAfter)
insert_after.push_back(su);
else if (su.type == Retrieve)
retrieve.push_back(su);
}
// intersect with pre-condition
intersect(vstate->state, pre_conds[task_id][i], vec_tmp);
State projected;
vector<State> after_postconds;
for (State& after_precond : vec_tmp) {
// insertion
vector<pair<State, int> > after_insert = vstate->counters;
for (SetUpdate& su : insert_before)
insert_to_set(task_id, su, after_precond, after_insert);
// project to preserving variables
project(after_precond, task_id, task.services[i].var_prop,
projected);
// intersect with post-condition
intersect(projected, post_conds[task_id][i], after_postconds);
for (State& after_postcond : after_postconds) {
VASSState* vstate = new VASSState();
vstate->state = after_postcond;
vstate->returns.clear();
vstate->counters = after_insert;
vector<VASSState*> candidates;
candidates.push_back(vstate);
int ptr_head = 0, ptr_end = 1;
for (SetUpdate& su : retrieve) {
for (int i = ptr_head; i < ptr_end; i++) {
vector<VASSState*> new_vstates;
retrieve_from_set(task_id, su, candidates[i],
new_vstates);
candidates.insert(candidates.end(),
new_vstates.begin(), new_vstates.end());
}
ptr_head = ptr_end;
ptr_end = candidates.size();
}
for (VASSState* cand : candidates) {
vector<VASSState*> next_set;
vector<int> tmp;
make_atm_transition(task_id, cand, prev_atm_states, -1,
false, i, tmp, next_set);
for (VASSState* next : next_set) {
for (SetUpdate& su : insert_after)
insert_to_set(task_id, su, next->state,
next->counters);
results.push_back(next);
}
}
}
}
}
}
// remove duplicate
vector<VASSState*> new_results;
set<VASSState> vstate_set;
for (VASSState* vstate : results) {
if (vstate_set.count(*vstate) == 0) {
vstate_set.insert(*vstate);
new_results.push_back(vstate);
} else
delete vstate;
}
results = new_results;
time_nextstate += clock() - start;
}
int global_counter = 0;
void Verifier::descendants(vector<vector<int> >& edges, int v,
vector<int>& desc) {
queue<int> que;
unordered_set<int> visited;
que.push(v);
visited.insert(v);
while (!que.empty()) {
int now = que.front();
que.pop();
for (int next : edges[now])
if (visited.count(next) == 0) {
que.push(next);
visited.insert(next);
}
}
desc = vector<int>(visited.begin(), visited.end());
}
vector<tuple<State, State, vector<int> > >* Verifier::reachable(int taskid,
State& input_state) {
VASSState* init = new VASSState();
// intersect with initialization
State init_state;
get_initial_state(taskid, init_state);
bool flag = intersect(input_state, init_state, init->state);
// dump_state(input_state);
// dump_state(init_state);
if (!flag) {
printf("Bug in initial state! Check overlapping between inputs / returns variables in task %d\n", taskid);
flag = intersect(input_state, init_state, init->state);
exit(0);
}
//init->state = input_state;
init->returns.clear();
init->counters.clear();
num_reach_map_tests++;
auto map_ptr = reach_map[taskid].find(*init);
if (map_ptr != reach_map[taskid].end()) {
num_reach_map_hits++;
delete init;
return map_ptr->second;
}
// Karp-Miller Tree
vector<VASSState*> que;
vector<vector<int> > backward_edges;
vector<vector<int> > forward_edges;
vector<bool> pruned;
// set of output states each VASSState can reach
vector<set<tuple<State, State, vector<int> > > > output_sets;
VASSStateStore visited(que, naive);
// add initial states
que.push_back(init);
backward_edges.push_back(vector<int>());
forward_edges.push_back(vector<int>());
pruned.push_back(false);
output_sets.push_back(set<tuple<State, State, vector<int> > >());
visited.insert(0);
// profiling
clock_t start_time = 0;
int ptr_idx = 0;
while (ptr_idx < (int) que.size()) {
if ((float) (clock() - timer) / CLOCKS_PER_SEC >= 600)
break;
global_counter++;
VASSState* now = que[ptr_idx];
int now_idx = ptr_idx;
ptr_idx++;
if (debug && global_counter % 1000 == 0) {
printf("At task %d, cnt = %d\n", taskid, global_counter);
for (int i = 0; i < (int) art.tasks.size(); i++)
printf("Task %d : reach_map.size() = %d\n", i,
(int) reach_map[i].size());
dump_vass_state(*now);
printf("\n");
}
if (pruned[now_idx])
continue;
// check whether there exists empty superstate
vector<int> cand_ids;
empty_states_tries[taskid]->query(*now, cand_ids);
bool has_empty_superstate = false;
for (int idx : cand_ids) {
if ((naive != 2 && now->is_substate_of(empty_states[taskid][idx])) ||
(naive == 2 && now->is_substate_of_naive(empty_states[taskid][idx], naive))) {
has_empty_superstate = true;
break;
}
}
if (has_empty_superstate)
continue;
// check previously reached
auto reach_map_ptr = reach_map[taskid].find(*now);
num_reach_map_tests++;
if (reach_map_ptr != reach_map[taskid].end()) {
num_reach_map_hits++;
output_sets[now_idx].insert(reach_map_ptr->second->begin(),
reach_map_ptr->second->end());
continue;
}
// collect ancestors
vector<int> ancestors;
descendants(backward_edges, now_idx, ancestors);
unordered_set<int> anc_set(ancestors.begin(), ancestors.end());
// printf("%d\n", (int) ancestors.size());
// compute next states
vector<VASSState*> next_states;
get_next_states(taskid, now, next_states);
for (VASSState* next : next_states) {
// prune the search if a superstate is visited
// if equals to the superstate, add forward/backward edges
num_superstate_tests++;
start_time = clock();
int equal_vstate_idx = -1;
if (visited.superstate(next, pruned, equal_vstate_idx)) {
time_superstate += clock() - start_time;
num_superstate_hits++;
// add edges only if equal
if (equal_vstate_idx >= 0) {
forward_edges[now_idx].push_back(equal_vstate_idx);
backward_edges[equal_vstate_idx].push_back(now_idx);
delete next;
} else {
// add edges and set pruned to be true
int next_idx = (int) que.size();
que.push_back(next);
backward_edges.push_back(vector<int>());
forward_edges.push_back(vector<int>());
backward_edges[next_idx].push_back(now_idx);
forward_edges[now_idx].push_back(next_idx);
pruned.push_back(true);
output_sets.push_back(set<tuple<State, State, vector<int> > >());
}
continue;
}
time_superstate += clock() - start_time;
// omega operation
start_time = clock();
TrieNode* counter_trie = next->get_counter_trie();
bool changed = true;
while (changed) {
changed = false;
for (int anc_idx : ancestors) {
if (naive != 2)
que[anc_idx]->is_substate_of(*next, counter_trie, true,
changed);
else {
que[anc_idx]->is_substate_of_naive(*next, true, changed,
naive);
}
}
}
delete counter_trie;
// remove counters that are substate of an omega counter
if (naive != 2) {
vector<pair<State, int> > new_counters;
for (pair<State, int>& cnt : next->counters) {
bool found = false;
for (pair<State, int>& omega_cnt : next->counters)
if (omega_cnt.second < 0 && cnt.first != omega_cnt.first
&& cnt.first.is_substate_of(omega_cnt.first)) {
found = true;
break;
}
if (!found)
new_counters.push_back(cnt);
}
next->counters = new_counters;
}
time_omega += clock() - start_time;
// pruned substates and their descendants
vector<int> substate_indices;
num_substate_tests++;
start_time = clock();
visited.substates(next, substate_indices);
time_substate += clock() - start_time;
num_substate_hits += (!substate_indices.empty());
for (int ss_idx : substate_indices) {
if (anc_set.count(ss_idx) == 0 || !pruned[ss_idx]) {
vector<int> desc;
descendants(forward_edges, ss_idx, desc);
for (int d : desc)
pruned[d] = true;
}
}
// add edges
int next_idx = (int) que.size();
que.push_back(next);
backward_edges.push_back(vector<int>());
forward_edges.push_back(vector<int>());
backward_edges[next_idx].push_back(now_idx);
forward_edges[now_idx].push_back(next_idx);
pruned.push_back(false);
output_sets.push_back(set<tuple<State, State, vector<int> > >());
visited.insert(next_idx);
}
}
// profiling: get cyclomatic complexity
profile_cyclomatic[taskid] = max(profile_cyclomatic[taskid],
profile_get_cyclomatic(taskid, que, forward_edges));
int que_size = que.size();
// perform repeated reachability test
vector<bool> repeated;
// TODO: ignore repeated reachability test when there is no atm
if (atm_task[taskid].empty() || naive == 1 || naive == 2)
repeated = vector<bool>(que_size, false);
else
repeated_reachable(taskid, que, visited, forward_edges, pruned, repeated);
// collect final states
for (int idx = que_size - 1; idx >= 0; idx--) {
VASSState* now = que[idx];
if (!pruned[idx] && reach_map[taskid].count(*now) == 0) {
if (now->returns.empty()) {
vector<State> last_states;
// finite local runs
intersect(now->state, close_conds[taskid], last_states);
// infinite local runs
if (repeated[idx])
last_states.push_back(now->state);
int num_last_states = last_states.size();
for (int last_idx = 0; last_idx < num_last_states; last_idx++) {
State& last = last_states[last_idx];
tuple<State, State, vector<int> > out;
if (last_idx < num_last_states - 1 || !repeated[idx]) {
// finite
project(last, taskid, input_vars[taskid], get<0>(out));
project(last, taskid, return_vars[taskid], get<1>(out));
rename_to_parent(get<0>(out));
rename_to_parent(get<1>(out));
} else {
// infinite
project(last, taskid, input_vars[taskid], get<0>(out));
rename_to_parent(get<0>(out));
// write something invalid to get<1>(out)
State invalid;
invalid.exprs.push_back(0);
invalid.eq_classes.push_back(0);
invalid.uneqs.push_back(pair<int, int>(0, 0));
get<1>(out) = invalid;
}
vector<pair<int, int> > atm_states;
get_atm_states(taskid, last, atm_states);
for (pair<int, int>& atm_state : atm_states) {
int atm_id = atm_state.first;
int state_id = atm_state.second;
if (atms[atm_id].states[state_id].accept) {
if (repeated[idx] || taskid != 0 )
get<2>(out).push_back(atm_id);
}
}
output_sets[idx].insert(out);
}
}
// reach_map[taskid][*now] = new vector<pair<State, State> >(
// output_sets[idx].begin(), output_sets[idx].end());
//
// // build index for empty states
// if (output_sets[idx].empty()) {
// int state_id = (int) empty_states[taskid].size();
// empty_states[taskid].push_back(*now);
// empty_states_tries[taskid]->insert(state_id, empty_states[taskid][state_id]);
// }
}
for (int prev_idx : backward_edges[idx]) {
output_sets[prev_idx].insert(output_sets[idx].begin(),
output_sets[idx].end());
}
}
reach_map[taskid][*init] = new vector<tuple<State, State, vector<int> > >(
output_sets[0].begin(), output_sets[0].end());
// build index for empty states
if (output_sets[0].empty()) {
int state_id = (int) empty_states[taskid].size();
empty_states[taskid].push_back(*init);
empty_states_tries[taskid]->insert(state_id,
empty_states[taskid][state_id]);
}
vector<tuple<State, State, vector<int> > >* res = reach_map[taskid][*init];
// collect all vstates for profiling
for (VASSState* vstate : que)
profile_vstate_set[taskid].insert(*vstate);
// delete all vass_states
for (VASSState* vstate : que)
delete vstate;
return res;
}
void Verifier::repeated_reachable(int taskid, vector<VASSState*>& que,
VASSStateStore& visited, vector<vector<int> >& forward_edges,
vector<bool>& pruned, vector<bool>& result) {
// profiling
clock_t start = clock();
int num_nodes = que.size();
result = vector<bool>(num_nodes, false);
// mark omega nodes
for (int i = 0; i < num_nodes; i++) {
bool has_omega = false;
for (auto& counter : que[i]->counters)
if (counter.second == -1) {
has_omega = true;
break;
}
if (has_omega)
result[i] = true;
}
// Compute the strongly connected components
vector<int> color(num_nodes, 0);
vector<bool> in_stack(num_nodes, false);
vector<int> visit_idx(num_nodes, -1);
vector<int> low_idx(num_nodes, -1);
stack<int> dfs_stk, scc_stk;
dfs_stk.push(0);
// color[0] = 1;
int current_idx = 0;
VASSStateStore visited_new(que, naive);
//visited_new.insert(0);
// int cnt = 0;
while (!dfs_stk.empty()) {
if ((float) (clock() - timer) / CLOCKS_PER_SEC >= 600)
break;
int u = dfs_stk.top();
if (color[u] == 0) {
int eq_idx = -1;
if (visited_new.superstate(que[u], eq_idx)) {
color[u] = 2;
dfs_stk.pop();
} else {
visited_new.insert(u);
visit_idx[u] = current_idx;
low_idx[u] = current_idx++;
color[u] = 1;
scc_stk.push(u);
in_stack[u] = true;
// add forward edges if missing
int vid = -1, tmp = -1;
if (forward_edges[u].empty()) {
vector<VASSState*> next_states;
// time_scc += clock() - start;
get_next_states(taskid, que[u], next_states);
// start = clock();
for (VASSState* vstate : next_states) {
bool added = false;
bool covered = visited.superstate(vstate, tmp);
//if (!covered)
// printf("bug!\n");
if (covered
&& !visited.superstate_strict(vstate, tmp)) {
if (!visited_new.superstate(vstate, vid)) {
vid = (int) que.size();
que.push_back(vstate);
// visited_new.insert(vid);
color.push_back(0);
in_stack.push_back(false);
visit_idx.push_back(-1);
low_idx.push_back(-1);
forward_edges.push_back(vector<int>());
added = true;
forward_edges[u].push_back(vid);
if (color[vid] == 0) {
// color[vid] = 1;
dfs_stk.push(vid);
} else if (in_stack[vid] && visit_idx[vid] >= 0)
low_idx[u] = min(low_idx[u],
visit_idx[vid]);
}
}
if (!added)
delete vstate;
}
} else {
for (int v : forward_edges[u])
if (!result[v] && visited.superstate(que[v], tmp)
&& !visited.superstate_strict(que[v], tmp)
&& !(visited_new.superstate(que[v], vid))) {
if (color[v] == 0) {
// visited_new.insert(v);
// color[v] = 1;
dfs_stk.push(v);
} else if (in_stack[v] && visit_idx[v] >= 0)
low_idx[u] = min(low_idx[u], visit_idx[v]);
}
}
}
} else if (color[u] == 1) {
color[u] = 2;
dfs_stk.pop();
for (int v : forward_edges[u])
if (low_idx[v] >= 0)
low_idx[u] = min(low_idx[u], low_idx[v]);
if (low_idx[u] == visit_idx[u]) {
vector<int> scc;
while (true) {
int v = scc_stk.top();
scc_stk.pop();
scc.push_back(v);
in_stack[v] = false;
if (v == u)
break;
}
if (scc.size() > 1) {
for (int v : scc)
if (v < num_nodes)
result[v] = true;
} else {
bool self_loop = false;
for (int v : forward_edges[u])
if (u == v) {
self_loop = true;
break;
}
if (self_loop && u < num_nodes)
result[u] = true;
}
}
} else {
dfs_stk.pop();
}
}
// mark all self-loops
for (int u = 0; u < num_nodes; u++) {
if (result[u])
continue;
bool self_loop = false;
for (int v : forward_edges[u])
if (u == v) {
self_loop = true;
break;
}
if (self_loop)
result[u] = true;
}
time_scc += clock() - start;
}
void Verifier::get_eql_sets(vector<tuple<int, int, bool> >& eql_sets) {
eql_sets.clear();
// pre-, post-, open-, close-conditions
for (int task_id = 0; task_id < (int) art.tasks.size(); task_id++) {
Task& task = art.tasks[task_id];
get_eql_sets(task_id, task.close_cond, eql_sets);
for (int child_task_id : task.children)
get_eql_sets(task_id, art.tasks[child_task_id].open_cond, eql_sets);
for (Service& ser : task.services) {
get_eql_sets(task_id, ser.pre_cond, eql_sets);
get_eql_sets(task_id, ser.post_cond, eql_sets);
}
}
// eqls for opening/closing tasks
for (int task_id = 0; task_id < (int) art.tasks.size(); task_id++) {
Task& task = art.tasks[task_id];
// opening
for (int child : task.children) {
Task& child_task = art.tasks[child];
set<int> input_var_set(input_vars[child].begin(), input_vars[child].end());
for (int vid = 0; vid < child_task.num_var; vid++)
if (input_var_set.count(vid) > 0) {
for (int expr : task_var_expr_ids[child][vid]) {
int e = expr_rename_to_parent[expr];
eql_sets.push_back(tuple<int, int, bool>(expr, e, true));
}
}
}
// closing
for (int child : task.children)
for (int vid : return_vars[child]) {
for (int expr : task_var_expr_ids[child][vid]) {
int e = expr_rename_to_parent[expr];
eql_sets.push_back(tuple<int, int, bool>(expr, e, true));
}
}
// initialization
for (int vid = 0; vid < task.num_var; vid++) {
int expr = get_expr_id_var(task_id, vid);
if (task.var_types[vid] == -1)
eql_sets.push_back(tuple<int, int, bool>(expr, zero_id, true));
else if (task.var_types[vid] == -2)
eql_sets.push_back(tuple<int, int, bool>(expr, empty_id, true));
else
eql_sets.push_back(tuple<int, int, bool>(expr, null_id, true));
}
}
// eqls in property
for (Automaton& atm : atms) {
for (int sid = 0; sid < atm.num_states; sid++)
for (auto& tran : atm.transition[sid])
for (AProp* prop : tran.first)
if (prop->is_fo()) {
APropFO* p = (APropFO*) prop;
get_eql_sets(atm.taskid, p->fo, eql_sets);
}
}
}
void Verifier::get_eql_sets(int expr1, int expr2, vector<tuple<int, int, bool> >& res) {
res.push_back(tuple<int, int, bool>(expr1, expr2, true));
if ((is_navi(expr1) || is_var(expr1)) && (is_navi(expr2) || is_var(expr2))) {
vector<int> ch1, ch2;
get_child_expr(expr1, ch1);
get_child_expr(expr2, ch2);
if (ch1.size() != ch2.size()) {
printf("children sizes of %s and %s doesn't match!", expr_name[expr1].c_str(), expr_name[expr2].c_str());
exit(0);
}
int sz = ch1.size();
for (int i = 0; i < sz; i++) {
int c1 = ch1[i];
int c2 = ch2[i];
get_eql_sets(c1, c2, res);
}
}
}
void Verifier::get_eql_sets(int task_id, Formula* form, vector<tuple<int, int, bool> >& res, bool pushed_down) {
if (!pushed_down)
pushdown_neg(form, false);
if (form == NULL || form->is_const())
return;
else if (form->is_cmp()) {
CmpTerm* term = (CmpTerm*) form;
int expr1 = para_to_expr(term->p1, task_id);
int expr2 = para_to_expr(term->p2, task_id);
if (term->equal)
get_eql_sets(expr1, expr2, res);
else
res.push_back(tuple<int, int, bool>(expr1, expr2, false));
} else if (form->is_relation()) {
RelationTerm* term = (RelationTerm*) form;
vector<int> lefts, rights;
for (int i = 1; i < (int) term->paras.size(); i++) {
int expr_right = para_to_expr(term->paras[i], task_id);
if (expr_right >= 0) {
lefts.push_back(
get_expr_id_navi(task_id, term->paras[0].id, i - 1));
rights.push_back(expr_right);
}
}
vector<tuple<int, int, bool> > tmp;
for (int i = 0; i < (int) lefts.size(); i++)
get_eql_sets(lefts[i], rights[i], tmp);
if (term->negated) {
for (auto& tp : tmp)
get<2>(tp) = false;
}
res.insert(res.end(), tmp.begin(), tmp.end());
} else if (form->is_internal()) {
Internal* term = (Internal*) form;
get_eql_sets(task_id, term->paras[0], res, true);
get_eql_sets(task_id, term->paras[1], res, true);
}
}
void Verifier::get_unique_sign_pairs() {
if (naive == 3 || !unique_sign_pairs.empty())
return;
vector<tuple<int, int, bool> > eql_sets;
get_eql_sets(eql_sets);
// bfs
int N = expr_name.size();
vector<vector<pair<int, bool> > > edges(N, vector<pair<int, bool> >());
for (auto& tp : eql_sets) {
int u = get<0>(tp);
int v = get<1>(tp);
bool flag = get<2>(tp);
edges[u].push_back(pair<int, bool>(v, flag));
edges[v].push_back(pair<int, bool>(u, flag));
}
// unequality edges
vector<int> eql_cc(N, -1);
int num_cc = 0;
for (int expr = 0; expr < N; expr++) {
if (eql_cc[expr] >= 0)
continue;
queue<int> que;
que.push(expr);
eql_cc[expr] = num_cc++;
while (!que.empty()) {
int u = que.front();
que.pop();
for (auto pp : edges[u])
if (pp.second) {
if (eql_cc[pp.first] < 0) {
eql_cc[pp.first] = eql_cc[expr];
que.push(pp.first);
}
}
}
}
// remove duplicate edges
for (auto edge : eql_sets)
if (get<2>(edge) == false) {
int u = get<0>(edge);
int v = get<1>(edge);
if (eql_cc[u] != eql_cc[v])
unique_sign_pairs.insert(pair<int, int>(u, v));
}
// find connected components of all edges
eql_cc = vector<int>(N, -1);
num_cc = 0;
for (int expr = 0; expr < N; expr++) {
if (eql_cc[expr] >= 0)
continue;
queue<int> que;
que.push(expr);
eql_cc[expr] = num_cc++;
Conjunct conj;
set<int> exprs;
while (!que.empty()) {
int u = que.front();
que.pop();
exprs.insert(u);
if (is_const(u))
continue;
for (auto pp : edges[u]) {
if (eql_cc[pp.first] < 0) {
eql_cc[pp.first] = eql_cc[expr];
que.push(pp.first);
}
if (pp.second)
conj.eqs.push_back(pair<int, int>(u, pp.first));
else
conj.uneqs.push_back(pair<int, int>(u, pp.first));
}
}
State tmp;
set<int> expr_set;
for (pair<int, int> pp : conj.eqs) {
expr_set.insert(pp.first);
expr_set.insert(pp.second);
}
for (pair<int, int> pp : conj.uneqs) {
expr_set.insert(pp.first);
expr_set.insert(pp.second);
}
tmp.exprs = vector<int>(expr_set.begin(), expr_set.end());
if (convert_eqls_to_state(conj, tmp)) {
for (pair<int, int> pp : conj.eqs)
unique_sign_pairs.insert(pp);
}
}
// equality edges
/*
set<pair<int, int> > added;
BCCGraph bcc(N);
for (auto edge : eql_sets)
if (get<2>(edge)) {
int u = get<0>(edge);
int v = get<1>(edge);
if (is_const(u) || is_const(v))
continue;
if (u > v) swap(u, v);
if (added.count(pair<int, int>(u, v)) > 0)
continue;
added.insert(pair<int, int>(u, v));
bcc.addEdge(u, v);
bcc.addEdge(v, u);
}
unordered_set<int> to_traverse;
vector<vector<pair<int, int> > > decomp;
bcc.BCC(decomp);
for (auto edge : eql_sets) {
if (get<2>(edge))
continue;
to_traverse.insert(get<0>(edge));
to_traverse.insert(get<1>(edge));
}
set<pair<int, int> > marked_edge;
set<pair<int, int> > uneql_set;
for (auto edge : eql_sets)
if (!get<2>(edge)) {
uneql_set.insert(pair<int, int>(get<0>(edge), get<1>(edge)));
uneql_set.insert(pair<int, int>(get<1>(edge), get<0>(edge)));
}
for (int start = 0; start < N; start++) {
if (to_traverse.count(start) > 0 || is_const(start)) {
queue<int> que;
que.push(start);
vector<int> from(N, -1);
from[start] = start;
vector<int> visited;
while (!que.empty()) {
int u = que.front();
visited.push_back(u);
que.pop();
for (auto pp : edges[u])
if (pp.second && from[pp.first] == -1) {
from[pp.first] = u;
if (!is_const(pp.first))
que.push(pp.first);
else
visited.push_back(pp.first);
}
}
for (int end : visited)
if ((is_const(start) && is_const(end) && start != end) ||
uneql_set.count(pair<int, int>(start, end)) > 0) {
int u = end;
while (u != start) {
int v = from[u];
marked_edge.insert(pair<int, int>(v, u));
marked_edge.insert(pair<int, int>(u, v));
u = v;
}
}
}
}
for (auto bc : decomp) {
bool found = false;
for (auto pp : bc)
if (marked_edge.count(pp) > 0)
found = true;
if (found) {
for (auto pp : bc) {
marked_edge.insert(pp);
swap(pp.first, pp.second);
marked_edge.insert(pp);
}
}
}
for (auto edge : eql_sets)
if (get<2>(edge)) {
int u = get<0>(edge);
int v = get<1>(edge);
if (marked_edge.count(pair<int, int>(u, v)) == 0) {
unique_sign_pairs.insert(pair<int, int>(u, v));
// printf("%s %s\n", expr_name[u].c_str(), expr_name[v].c_str());
}
}
*/
// printf("%d\n", (int) unique_sign_pairs.size());
}
void Verifier::profile_get_num_counters(vector<int>& results) {
int num_tasks = art.tasks.size();
results = vector<int>(num_tasks, 0);
for (int i = 0; i < num_tasks; i++) {
set<State> state_set;
for (auto& vs : profile_vstate_set[i])
for (auto& cnt : vs.counters)
state_set.insert(cnt.first);
results[i] = state_set.size();
}
}
void Verifier::profile_get_num_states(vector<int>& results) {
int num_tasks = art.tasks.size();
results = vector<int>(num_tasks, 0);
for (int i = 0; i < num_tasks; i++) {
set<State> state_set;
for (auto& vs : profile_vstate_set[i])
state_set.insert(vs.state);
results[i] = state_set.size();
}
}
int Verifier::profile_get_max_active_counters() {
int result = 0;
int num_tasks = art.tasks.size();
for (int i = 0; i < num_tasks; i++)
for (auto& vs : profile_vstate_set[i])
result = max(result, (int) vs.counters.size());
return result;
}
int Verifier::profile_get_cyclomatic(int task_id, vector<VASSState*>& que, vector<vector<int> >& forward_edges) {
int N = que.size();
Task& task = art.tasks[task_id];
int max_cyc = 0;
for (int vid = 0; vid < task.num_var; vid++) {
if (task.var_types[vid] >= 0)
continue;
vector<int> projected;
map<State, int> proj_map;
vector<int> nonid_vars(1, vid);
for (int i = 0; i < N; i++) {
State p;
State tmp = que[i]->state;
tmp.uneqs.clear();
project(tmp, task_id, nonid_vars, p);
if (proj_map.count(p) == 0) {
proj_map[p] = (int) proj_map.size();
// dump_state(p);
}
projected.push_back(proj_map[p]);
}
set<pair<int, int> > edge_set;
for (int u = 0; u < N; u++) {
int new_u = projected[u];
for (int v : forward_edges[u]) {
int new_v = projected[v];
edge_set.insert(pair<int, int>(new_u, new_v));
}
}
// TODO
// print out debug info when cyc > 100
max_cyc = max(max_cyc, (int) edge_set.size() - (int) proj_map.size() + 2);
// printf("%d\n-----------------------\n", max_cyc);
}
return max_cyc;
}
//
// biconnected components
//
BCCGraph::BCCGraph(int _V)
{
V = _V;
E = 0;
adj = vector<list<int> >(V, list<int>());
}
void BCCGraph::addEdge(int v, int w)
{
adj[v].push_back(w);
E++;
}
// A recursive function that finds and prints strongly connected
// components using DFS traversal
// u --> The vertex to be visited next
// disc[] --> Stores discovery times of visited vertices
// low[] -- >> earliest visited vertex (the vertex with minimum
// discovery time) that can be reached from subtree
// rooted with current vertex
// *st -- >> To store visited edges
void BCCGraph::BCCUtil(int u, int disc[], int low[], list<Edge> *st,
int parent[])
{
// A static variable is used for simplicity, we can avoid use
// of static variable by passing a pointer.
static int time = 0;
// Initialize discovery time and low value
disc[u] = low[u] = ++time;
int children = 0;
// Go through all vertices adjacent to this
list<int>::iterator i;
for (i = adj[u].begin(); i != adj[u].end(); ++i)
{
int v = *i; // v is current adjacent of 'u'
// If v is not visited yet, then recur for it
if (disc[v] == -1)
{
children++;
parent[v] = u;
//store the edge in stack
st->push_back(Edge(u,v));
BCCUtil(v, disc, low, st, parent);
// Check if the subtree rooted with 'v' has a
// connection to one of the ancestors of 'u'
// Case 1 -- per Strongly Connected Components Article
low[u] = min(low[u], low[v]);
//If u is an articulation point,
//pop all edges from stack till u -- v
if( (disc[u] == 1 && children > 1) ||
(disc[u] > 1 && low[v] >= disc[u]) )
{
while(st->back().u != u || st->back().v != v)
{
result.back().push_back(pair<int, int>(st->back().u, st->back().v));
st->pop_back();
}
result.back().push_back(pair<int, int>(st->back().u, st->back().v));
st->pop_back();
result.push_back(vector<pair<int, int> >());
}
}
// Update low value of 'u' only of 'v' is still in stack
// (i.e. it's a back edge, not cross edge).
// Case 2 -- per Strongly Connected Components Article
else if(v != parent[u] && disc[v] < low[u])
{
low[u] = min(low[u], disc[v]);
st->push_back(Edge(u,v));
}
}
}
// The function to do DFS traversal. It uses BCCUtil()
void BCCGraph::BCC(vector<vector<pair<int, int> > >& res)
{
result.push_back(vector<pair<int, int> >());
int *disc = new int[V];
int *low = new int[V];
int *parent = new int[V];
list<Edge> *st = new list<Edge>[E];
// Initialize disc and low, and parent arrays
for (int i = 0; i < V; i++)
{
disc[i] = -1;
low[i] = -1;
parent[i] = -1;
}
for (int i = 0; i < V; i++)
{
if (disc[i] == -1)
BCCUtil(i, disc, low, st, parent);
int j = 0;
//If stack is not empty, pop all edges from stack
while(st->size() > 0) {
j = 1;
result.back().push_back(pair<int, int>(st->back().u, st->back().v));
st->pop_back();
}
if(j == 1)
result.push_back(vector<pair<int, int> >());
}
if (result.back().empty())
result.pop_back();
res = result;
}
}
| 28.264063 | 113 | 0.595279 | [
"vector"
] |
09a57e206586d41e8208a0bcdd9b27b2c29e5a3f | 9,420 | cpp | C++ | retroc/test/rand.cpp | raggledodo/testify | e96e793b7082c3eb95f6177d5e7b0612ef6cd29c | [
"MIT"
] | null | null | null | retroc/test/rand.cpp | raggledodo/testify | e96e793b7082c3eb95f6177d5e7b0612ef6cd29c | [
"MIT"
] | null | null | null | retroc/test/rand.cpp | raggledodo/testify | e96e793b7082c3eb95f6177d5e7b0612ef6cd29c | [
"MIT"
] | null | null | null | #include <unordered_set>
#include <unordered_map>
#include "gtest/gtest.h"
#include "retroc/rand.hpp"
#define ASSERT_ARR_BETWEEN(bot, top, arr)\
for (auto v : arr) {\
ASSERT_LE(bot, v);\
ASSERT_GE(top, v);\
}
int main (int argc, char** argv)
{
size_t seed = std::time(nullptr);
retro::get_engine().seed(seed);
::testing::InitGoogleTest(&argc, argv);
int ret = RUN_ALL_TESTS();
return ret;
}
template <typename Arr>
void vec_randomness (Arr vec, Arr vec2,
retro::Range<retro::IterT<typename Arr::iterator> > range,
size_t n, double similarity_thresh)
{
// constraint
ASSERT_EQ(n, vec.size());
ASSERT_EQ(n, vec2.size());
ASSERT_ARR_BETWEEN(range.min_, range.max_, vec)
// randomness between different arrays
double dist = 0;
for (uint i = 0; i < n; ++i)
{
double diff = (double) vec[i] - (double) vec2[i];
dist += diff * diff;
}
dist = std::sqrt(dist) / (range.max_ - range.min_);
EXPECT_LT(similarity_thresh, dist);
}
TEST(RANDO, GenDoubles)
{
const double separation_metric = 0.01;
const double similarity_thresh = 0.1;
retro::Range<double> range(-10.2, 24.2);
size_t n = 5000;
auto vec = retro::get_vec<double>(n, range);
auto vec2 = retro::get_vec<double>(n, range);
vec_randomness(vec, vec2, range, n, similarity_thresh);
// randomness within a single array
std::vector<double> svec = vec;
std::sort(svec.begin(), svec.end());
double diff = 0;
for (uint i = 0; i < n - 1; ++i)
{
diff += (svec[i+1] - svec[i]);
}
double avgdiff = diff / (n - 1);
EXPECT_GT(separation_metric, avgdiff);
}
TEST(RANDO, GenFloats)
{
const float separation_metric = 0.1;
const float similarity_thresh = 0.1;
retro::Range<float> range(-235, 252);
size_t n = 7000;
auto vec = retro::get_vec<float>(n, range);
auto vec2 = retro::get_vec<float>(n, range);
vec_randomness(vec, vec2, range, n, similarity_thresh);
// randomness within a single array
std::vector<float> svec = vec;
std::sort(svec.begin(), svec.end());
float diff = 0;
for (uint i = 0; i < n - 1; ++i)
{
diff += (svec[i+1] - svec[i]);
}
float avgdiff = diff / (n - 1);
EXPECT_GT(separation_metric, avgdiff);
}
TEST(RANDO, GenInt32s)
{
const double separation_metric = 1;
const double similarity_thresh = 0.1;
retro::Range<int32_t> range(-100, 252);
size_t n = 3000;
auto vec = retro::get_vec<int32_t>(n, range);
auto vec2 = retro::get_vec<int32_t>(n, range);
vec_randomness(vec, vec2, range, n, similarity_thresh);
// randomness within a single array
std::vector<int32_t> svec = vec;
std::sort(svec.begin(), svec.end());
double diff = 0;
for (uint i = 0; i < n - 1; ++i)
{
diff += (svec[i+1] - svec[i]);
}
double avgdiff = diff / (n - 1);
EXPECT_GT(separation_metric, avgdiff);
}
TEST(RANDO, GenUint32s)
{
const double separation_metric = 1;
const double similarity_thresh = 0.1;
retro::Range<uint32_t> range(100, 252);
size_t n = 6000;
auto vec = retro::get_vec<uint32_t>(n, range);
auto vec2 = retro::get_vec<uint32_t>(n, range);
vec_randomness(vec, vec2, range, n, similarity_thresh);
// randomness within a single array
std::vector<uint32_t> svec = vec;
std::sort(svec.begin(), svec.end());
double diff = 0;
for (uint i = 0; i < n - 1; ++i)
{
diff += ((double) svec[i+1] - (double) svec[i]);
}
double avgdiff = diff / (n - 1);
EXPECT_GT(separation_metric, avgdiff);
}
TEST(RANDO, GenInt64s)
{
const double separation_metric = 1;
const double similarity_thresh = 0.1;
retro::Range<int64_t> range(-100, 252);
size_t n = 5500;
auto vec = retro::get_vec<int64_t>(n, range);
auto vec2 = retro::get_vec<int64_t>(n, range);
vec_randomness(vec, vec2, range, n, similarity_thresh);
// randomness within a single array
std::vector<int64_t> svec = vec;
std::sort(svec.begin(), svec.end());
double diff = 0;
for (uint i = 0; i < n - 1; ++i)
{
diff += (svec[i+1] - svec[i]);
}
double avgdiff = diff / (n - 1);
EXPECT_GT(separation_metric, avgdiff);
}
TEST(RANDO, GenUint64s)
{
const double separation_metric = 1;
const double similarity_thresh = 0.1;
retro::Range<uint64_t> range(100, 252);
size_t n = 6000;
auto vec = retro::get_vec<uint64_t>(n, range);
auto vec2 = retro::get_vec<uint64_t>(n, range);
vec_randomness(vec, vec2, range, n, similarity_thresh);
// randomness within a single array
std::vector<uint64_t> svec = vec;
std::sort(svec.begin(), svec.end());
double diff = 0;
for (uint i = 0; i < n - 1; ++i)
{
diff += ((double) svec[i+1] - (double) svec[i]);
}
double avgdiff = diff / (n - 1);
EXPECT_GT(separation_metric, avgdiff);
}
TEST(RANDO, GenStr)
{
const double similarity_thresh = 0.1;
const std::string content = "0123456789"
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
size_t n = 9300;
std::string instr = retro::get_string(n, content);
std::string instr2 = retro::get_string(n, content);
vec_randomness(instr, instr2, retro::Range<char>('0', 'z'), n, similarity_thresh);
// randomness within a single string
std::unordered_map<char,uint> occurrences;
for (char c : instr)
{
if (occurrences.find(c) == occurrences.end())
{
occurrences[c] = 0;
}
occurrences[c]++;
}
size_t nbins = occurrences.size();
size_t missing = content.size() - nbins;
EXPECT_GT(0.05 * content.size(), missing);
// stdev of occurrence should be close to 0
double mean = 0;
for (auto& opair : occurrences)
{
mean += opair.second;
}
mean /= nbins;
double stdev = 0;
for (auto& opair : occurrences)
{
double diff = (double) opair.second - mean;
stdev += diff * diff;
}
stdev = std::sqrt(stdev / nbins);
double rel_stdev = stdev / n;
EXPECT_GT(0.01, rel_stdev);
}
TEST(RANDO, GenChoice)
{
const double similarity_thresh = 0.1;
std::vector<uint64_t> carr = retro::choose(19, 6);
std::vector<uint64_t> carr2 = retro::choose(19, 6);
// constraint
std::unordered_set<uint64_t> carr_set(carr.begin(), carr.end());
EXPECT_EQ(6, carr.size());
EXPECT_EQ(carr.size(), carr_set.size()) <<
"chosen vec doesn't contain unique values";
uint64_t mic = *std::min_element(carr.begin(), carr.end());
uint64_t mac = *std::max_element(carr.begin(), carr.end());
EXPECT_LE(0, mic) << "chosen vec not within range [0, 19)";
EXPECT_GT(19, mac) << "chosen vec not within range [0, 19)";
// randomness between different choose ops
double dist = 0;
for (uint i = 0; i < 6; ++i)
{
double diff = (double) carr[i] - (double) carr2[i];
dist += diff * diff;
}
dist = std::sqrt(dist) / 19;
EXPECT_LT(similarity_thresh, dist);
const uint sample_size = 3000;
uint nbins = carr.size();
uint occurrences[nbins];
std::memset(occurrences, 0, sizeof(uint) * nbins);
auto begit = carr.begin();
auto endit = carr.end();
for (uint i = 0; i < sample_size; ++i)
{
auto it = retro::select(begit, endit);
size_t d = std::distance(begit, it);
occurrences[d]++;
}
// stdev of occurrence should be close to 0
double mean = 0;
for (uint i = 0; i < nbins; ++i)
{
mean += occurrences[i];
}
mean /= nbins;
double stdev = 0;
for (uint i = 0; i < nbins; ++i)
{
double diff = (double) occurrences[i] - mean;
stdev += diff * diff;
}
stdev = std::sqrt(stdev / nbins);
double rel_stdev = stdev / sample_size;
EXPECT_GT(0.1, rel_stdev);
}
TEST(RANDO, GenTree)
{
const uint32_t N = 147;
retro::Graph<N> tree;
retro::get_minspan_tree(tree);
retro::Graph<N> tree2;
retro::get_minspan_tree(tree2);
// constraint
// let's go through the tree, assertion:
// MUST visit every node once and only once
bool visited[N];
std::memset(visited, false, N);
tree.breadth_traverse(0,
[&](uint32_t node, std::vector<uint32_t>&)
{
ASSERT_FALSE(visited[node]) << "node=" << node << " is visited twice";
visited[node] = true;
});
for (uint i = 0; i < N; ++i)
{
EXPECT_TRUE(visited[i]) << "tree is disconnected from node " << i;
}
// randomness between trees
uint32_t nand = 0;
uint32_t nor = 0;
for (uint32_t i = 0; i < N; ++i)
{
for (uint32_t j = 0; j < N; ++j)
{
nand += (tree.get(i, j) && tree2.get(i, j));
nor += (tree.get(i, j) || tree2.get(i, j));
}
}
double sim_frac = (double) nand / nor;
EXPECT_GT(0.05, sim_frac);
}
TEST(RANDO, GenGraph)
{
const uint32_t N = 137;
retro::Graph<N> graph;
retro::get_graph(graph);
retro::Graph<N> graph2;
retro::get_graph(graph2);
// randomness between graphs
uint32_t nand = 0;
uint32_t nor = 0;
for (uint32_t i = 0; i < N; ++i)
{
for (uint32_t j = 0; j < N; ++j)
{
nand += (graph.get(i, j) && graph2.get(i, j));
nor += (graph.get(i, j) || graph2.get(i, j));
}
}
double sim_frac = (double) nand / nor;
EXPECT_GT(0.5, sim_frac);
}
TEST(RANDO, GenCGraph)
{
const uint32_t N = 123;
retro::Graph<N> graph;
retro::get_conn_graph(graph);
retro::Graph<N> graph2;
retro::get_conn_graph(graph2);
// constraint
// let's go through the graph, assertion:
// MUST visit every node
bool visited[N];
std::memset(visited, false, N);
graph.breadth_traverse(0,
[&](uint32_t node, std::vector<uint32_t>&)
{
visited[node] = true;
});
for (size_t i = 0; i < N; ++i)
{
EXPECT_TRUE(visited[i]) << "connected graph is disconnected from node " << i;
}
// randomness between graphs
uint32_t nand = 0;
uint32_t nor = 0;
for (uint32_t i = 0; i < N; ++i)
{
for (uint32_t j = 0; j < N; ++j)
{
nand += (graph.get(i, j) && graph2.get(i, j));
nor += (graph.get(i, j) || graph2.get(i, j));
}
}
double sim_frac = (double) nand / nor;
EXPECT_GT(0.5, sim_frac);
}
| 23.72796 | 83 | 0.648514 | [
"vector"
] |
09aabec893c8c15e01190c31aa92e553573fc353 | 3,070 | cpp | C++ | rai/core_test/common_util.cpp | gokoo/Raicoin | 494be83a1e29106d268f71e613fac1e4033a82f2 | [
"MIT"
] | 6 | 2020-10-19T06:39:08.000Z | 2022-03-06T21:12:50.000Z | rai/core_test/common_util.cpp | gokoo/Raicoin | 494be83a1e29106d268f71e613fac1e4033a82f2 | [
"MIT"
] | null | null | null | rai/core_test/common_util.cpp | gokoo/Raicoin | 494be83a1e29106d268f71e613fac1e4033a82f2 | [
"MIT"
] | 1 | 2020-10-19T06:39:09.000Z | 2020-10-19T06:39:09.000Z | #include <gtest/gtest.h>
#include <rai/core_test/test_util.hpp>
#include <rai/common/util.hpp>
TEST(CommonUtil, CheckUtf8)
{
bool ctrl;
ASSERT_EQ(false, rai::CheckUtf8("Raicoin", ctrl));
ASSERT_EQ(false, ctrl);
ASSERT_EQ(false, rai::CheckUtf8("κόσμε", ctrl));
ASSERT_EQ(false, ctrl);
std::vector<uint8_t> boundary_first{
0x00,
0xC2, 0x80,
0xE0, 0xA0, 0x80,
0xF0, 0x90, 0x80, 0x80
};
ASSERT_EQ(false, rai::CheckUtf8(boundary_first, ctrl));
ASSERT_EQ(true, ctrl);
std::vector<uint8_t> boundary_first_2{
0xF8, 0x88, 0x80, 0x80, 0x80
};
ASSERT_EQ(true, rai::CheckUtf8(boundary_first_2, ctrl));
std::vector<uint8_t> boundary_first_3{
0xFC, 0x84, 0x80, 0x80, 0x80, 0x80
};
ASSERT_EQ(true, rai::CheckUtf8(boundary_first_3, ctrl));
std::vector<uint8_t> boundary_last{
0x7F,
0xDF, 0xBF,
0xEF, 0xBF, 0xBF,
0xF4, 0x8F, 0xBF, 0xBF
};
ASSERT_EQ(false, rai::CheckUtf8(boundary_last, ctrl));
ASSERT_EQ(true, ctrl);
std::vector<uint8_t> boundary_last_2{
0xFB, 0xBF, 0xBF, 0xBF, 0xBF
};
ASSERT_EQ(true, rai::CheckUtf8(boundary_last_2, ctrl));
std::vector<uint8_t> boundary_last_3{
0xFD, 0xBF, 0xBF, 0xBF, 0xBF, 0xBF
};
ASSERT_EQ(true, rai::CheckUtf8(boundary_last_3, ctrl));
std::vector<uint8_t> boundary_other{
0xED, 0x9F, 0xBF, // U-0000D7FF
0xEE, 0x80, 0x80, // U-0000E000
0xEF, 0xBF, 0xBD, // U-0000FFFD
0xF4, 0x8F, 0xBF, 0xBF // U-0010FFFF
};
ASSERT_EQ(false, rai::CheckUtf8(boundary_other, ctrl));
ASSERT_EQ(false, ctrl);
std::vector<uint8_t> boundary_other_2{
0xF4, 0x90, 0x80, 0x80 // U-00110000
};
ASSERT_EQ(true, rai::CheckUtf8(boundary_other_2, ctrl));
std::vector<uint8_t> continuation{
0x80
};
ASSERT_EQ(true, rai::CheckUtf8(continuation, ctrl));
std::vector<uint8_t> continuation_2{
0xBF
};
ASSERT_EQ(true, rai::CheckUtf8(continuation_2, ctrl));
std::vector<uint8_t> continuation_3{
0x80, 0xBF
};
ASSERT_EQ(true, rai::CheckUtf8(continuation_3, ctrl));
std::vector<uint8_t> continuation_4{
0xEF, 0xBF
};
ASSERT_EQ(true, rai::CheckUtf8(continuation_4, ctrl));
std::vector<uint8_t> lonely_start{
0xC0, 0x20, 0xC1
};
ASSERT_EQ(true, rai::CheckUtf8(lonely_start, ctrl));
std::vector<uint8_t> impossible{
0xFE
};
ASSERT_EQ(true, rai::CheckUtf8(impossible, ctrl));
std::vector<uint8_t> overlong{
0xE0, 0x80, 0xAF
};
ASSERT_EQ(true, rai::CheckUtf8(overlong, ctrl));
std::vector<uint8_t> overlong_2{
0xF0, 0x8F, 0xBF, 0xBF
};
ASSERT_EQ(true, rai::CheckUtf8(overlong_2, ctrl));
std::vector<uint8_t> illegal{
0xED, 0xAD, 0xBF
};
ASSERT_EQ(true, rai::CheckUtf8(illegal, ctrl));
std::vector<uint8_t> illegal_2{
0xED, 0xAE, 0x80, 0xED, 0xB0, 0x80
};
ASSERT_EQ(true, rai::CheckUtf8(illegal_2, ctrl));
} | 26.929825 | 60 | 0.625081 | [
"vector"
] |
09ae424633299c59e43afcf4f9b697a90fcca9db | 48,305 | cpp | C++ | kmultisplit.cpp | PlainSailing/GraduationDesignTest | cebcfcdc6d04b24c5e0ba03b962d6896694369ab | [
"MIT"
] | 1 | 2021-01-27T07:20:30.000Z | 2021-01-27T07:20:30.000Z | kmultisplit.cpp | PlainSailing/GraduationDesignTest | cebcfcdc6d04b24c5e0ba03b962d6896694369ab | [
"MIT"
] | null | null | null | kmultisplit.cpp | PlainSailing/GraduationDesignTest | cebcfcdc6d04b24c5e0ba03b962d6896694369ab | [
"MIT"
] | null | null | null | #include "kmultisplit.h"
#include "common.h"
//#define TIXML_USE_STL
#include "cpl_conv.h" // for CPLMalloc()
#include "tinyxml.h"
#include "kutility.h"
#include "kprogressbar.h"
#include "kwaitbar.h"
#include <QString>
#include <QDebug>
#include <boost/math/special_functions/powm1.hpp>
#include <cmath>
#include <iterator>
#include <algorithm>
#include <limits>
#include <utility>
#include <vector>
#include <iostream>
#include <fstream>
KMultiSplit::~KMultiSplit()
{
CPLFree(m_imgBuff);
for(int bandIndex = 0;bandIndex<m_nBand;++bandIndex){
CPLFree(m_orgImgBuff[bandIndex]);
}
CPLFree(m_orgImgBuff);
CPLFree(labels);
CPLFree(m_adfMinMax);
}
KMultiSplit::KMultiSplit(QString input, QString output, QString labelOut, KMultiSplit::K_OutTypes type):
m_sInput(input),
m_sOutPut(output),
m_sOutPutLabel(labelOut),
m_tTypeOut(type)
{
m_maxScale = (std::numeric_limits<float>::max)()/10.;
GDALAllRegister();
GDALDataset * piDataset = (GDALDataset *) GDALOpen(input.toUtf8().constData(), GA_ReadOnly );
K_OPEN_ASSERT(piDataset,input.toStdString());
m_iXSize = piDataset->GetRasterXSize();
m_iYSize = piDataset->GetRasterYSize();
m_nBand = piDataset->GetRasterCount();
if(m_nBand>3) m_nBand=3;
GDALRasterBand * piBand = NULL;
// allocate the memory
m_orgImgBuff = (float **) CPLMalloc(sizeof(float *)*m_nBand);
m_imgBuff=(float *) CPLMalloc(sizeof(float)*m_nBand*m_iXSize*m_iYSize);
for(int index = 0;index<m_nBand;++index){
m_orgImgBuff[index]=(float *) CPLMalloc(sizeof(float)*m_iXSize*m_iYSize);
}
labels = (long *) CPLMalloc(sizeof(long)*m_iXSize*m_iYSize);
// read the image
for(int index = 0; index < m_nBand; ++index)
{
piBand = piDataset->GetRasterBand(index + 1);
piBand->RasterIO( GF_Read, 0, 0, m_iXSize, m_iYSize, m_orgImgBuff[index], m_iXSize, m_iYSize
, GDT_Float32, 0, 0 );
}
// make full use of cache
long orgIndex=0;
for(long index = 0;index<m_nBand*m_iXSize*m_iYSize;index+=m_nBand,orgIndex++){
for(long temp=0;temp<m_nBand;++temp){
m_imgBuff[index+temp]=m_orgImgBuff[temp][orgIndex];
}
}
// m_tempRegionVec.clear();
memset(labels,-1,m_iXSize*m_iYSize*sizeof(long));
// // TODO:leave to be confirmed
// m_quickSplitThres=1.02;
m_sOutPut = m_sOutPut.left(m_sOutPut.lastIndexOf('.'));
m_sOutPutLabel = m_sOutPutLabel.left(m_sOutPutLabel.lastIndexOf('.'));
m_extName = m_sInput.right(m_sInput.length()-m_sInput.lastIndexOf('.'));
const char *pszFormat = piDataset->GetDriverName();
m_poDriver = GetGDALDriverManager()->GetDriverByName(pszFormat);
if( m_poDriver == NULL )
{
std::cout<<"KMultiSplit:GetGDALDriverManager failed!"<<std::endl;
exit(1);
}
if(!CSLFetchBoolean( m_poDriver->GetMetadata(), GDAL_DCAP_CREATE, FALSE ) )
{
m_poDriver = GetGDALDriverManager()->GetDriverByName("GTiff");
m_extName = ".tif";
}
m_adfMinMax = (float *) CPLMalloc(sizeof(float)*2*m_nBand);
GDALRasterBand * tempBand = NULL;
int tempSuccess;
for(int index = 0;index<m_nBand;++index){
tempBand = piDataset->GetRasterBand( index+1 );
m_adfMinMax[2*index] = tempBand->GetMinimum( &tempSuccess );
m_adfMinMax[2*index+1] = tempBand->GetMaximum( &tempSuccess );
}
GDALClose(piDataset);
}
void KMultiSplit::quickSplit(float splitThres)
{
std::unordered_map<long,KRegion> tempRegioMap;
KProgressBar progressBar("QuickSplit",m_iYSize*m_iXSize,80);
K_PROGRESS_START(progressBar);
for(int iY = 0;iY<m_iYSize;++iY){
for(int iX = 0;iX<m_iXSize;++iX){
KSLE sle(iY,iX,iX);
//long id = KUtility::getRegionIndex();
long curID = iY*m_iXSize+iX;
long leftID = -1;
long upID = -1;
std::unordered_map<long,KRegion>::iterator leftIt = tempRegioMap.end();
std::unordered_map<long,KRegion>::iterator upIt = tempRegioMap.end();
if(iY>0){
upID = labels[(iY-1)*m_iXSize+iX];
upIt = tempRegioMap.find(upID);
}
if(iX>0){
leftID = labels[curID-1];
leftIt = tempRegioMap.find(leftID);
}
KRegion reg(curID);
reg.pushLine(sle);
// left and up are the same region
if(leftID == upID){
if(-1 == leftID || getQuickColorDiff(upIt->second,reg)>splitThres){
labels[curID]=curID;
tempRegioMap.insert(std::make_pair(curID,reg));
}else{
upIt->second += reg;
labels[curID]=upID;
}
}else{
float leftDiff = 0.;
float upDiff = 0.;
if(leftID != -1 && upID != -1){
leftDiff = getQuickColorDiff(reg,leftIt->second);
upDiff = getQuickColorDiff(upIt->second,reg);
if(leftDiff>splitThres&&upDiff>splitThres){
labels[curID]=curID;
tempRegioMap.insert(std::make_pair(curID,reg));
}else{
if(leftDiff<=splitThres&&upDiff<=splitThres){
if(leftDiff>upDiff){
upIt->second += reg;
labels[curID]=upID;
}else{
if(leftDiff<upDiff){
leftIt->second += reg;
labels[curID]=leftID;
}else{
if(getQuickColorDiff(upIt->second,leftIt->second)<=splitThres){
upIt->second += leftIt->second;
upIt->second += reg;
labels[curID]=upID;
tempRegioMap.erase(leftIt);
for(int tempIndex=0;tempIndex<curID;++tempIndex){
if(labels[tempIndex]==leftID){
labels[tempIndex]=upID;
}
}
}else{
upIt->second += reg;
labels[curID]=upID;
}
}
}
}else{
if(leftDiff<=splitThres){
leftIt->second += reg;
labels[curID]=leftID;
}else{
upIt->second += reg;
labels[curID]=upID;
}
}
}
}else if(upID == -1){
//qDebug()<<leftID<<upID;
leftDiff = getQuickColorDiff(reg,leftIt->second);
if(leftDiff<=splitThres){
leftIt->second += reg;
labels[curID]=leftID;
}else{
labels[curID]=curID;
tempRegioMap.insert(std::make_pair(curID,reg));
}
}else{
upDiff = getQuickColorDiff(upIt->second,reg);
if(upDiff<=splitThres){
upIt->second += reg;
labels[curID]=upID;
}else{
labels[curID]=curID;
tempRegioMap.insert(std::make_pair(curID,reg));
}
}
}// end of not same region merge
// if(-1==labels[iY*m_iXSize+iX]){
// qDebug()<<"up"<<upID;
// qDebug()<<"left"<<leftID;
// qDebug()<<"cur"<<curID;
// }
progressBar.autoUpdate();
}
// new: move some finished region to another vector
// old: move some region to RAG
for(std::unordered_map<long,KRegion>::iterator it = tempRegioMap.begin();it != tempRegioMap.end();){
if((it->second).getMaxLine()<iY && !((it->second).isSinglePixel())){
// just copy to avoid invalid iterator
m_mapRegion.insert(*it);
it = tempRegioMap.erase(it);
}else{
++it;
}
}
// delete items in the source vector
//for(std::vector<KRegion>::iterator it = m_vecRegion.begin();it != m_vecRegion.end();++it){
// tempRegionVec.erase(std::find(tempRegionVec.begin(),tempRegionVec.end(),*it));
//}
}
K_PROGRESS_END(progressBar);
// move all region to the finish vector
for(std::unordered_map<long,KRegion>::iterator it = tempRegioMap.begin();it != tempRegioMap.end();++it){
m_mapRegion.insert(*it);
}
// merge single item
KWaitBar waitBar("MergeSingle",4,20);
K_WAITBAR_START(waitBar);
for(std::unordered_map<long,KRegion>::iterator it = m_mapRegion.begin();it != m_mapRegion.end();){
if((it->second).isSinglePixel()){
list<KSLE>::const_iterator its = ((it->second).getLists()).begin();
int lines = its->getLine();
int cols = its->getStartCol();
long leftID = -1;
long rightID = -1;
long upID = -1;
long downID = -1;
float leftDiff = (std::numeric_limits<float>::max)();
float rightDiff = (std::numeric_limits<float>::max)();
float upDiff = (std::numeric_limits<float>::max)();
float downDiff = (std::numeric_limits<float>::max)();
std::unordered_map<long,KRegion>::iterator minDiffIt = m_mapRegion.begin();
float minDiff = (std::numeric_limits<float>::max)();
if(cols>0){
leftID = labels[lines*m_iXSize+cols-1];
}
if(cols<m_iXSize-1){
rightID = labels[lines*m_iXSize+cols+1];
}
if(lines>0){
upID = labels[(lines-1)*m_iXSize+cols];
}
if(lines<m_iYSize-1){
downID = labels[(lines+1)*m_iXSize+cols];
}
if(leftID != -1){
std::unordered_map<long,KRegion>::iterator itTemp = m_mapRegion.find(leftID);
leftDiff=getQuickColorDiff(itTemp->second,it->second);
if(minDiff>leftDiff){
minDiff=leftDiff;
minDiffIt=itTemp;
}
}
if(rightID != -1){
std::unordered_map<long,KRegion>::iterator itTemp = m_mapRegion.find(rightID);
rightDiff=getQuickColorDiff(itTemp->second,it->second);
if(minDiff>rightDiff){
minDiff=rightDiff;
minDiffIt=itTemp;
}
}
if(upID != -1){
std::unordered_map<long,KRegion>::iterator itTemp = m_mapRegion.find(upID);
upDiff=getQuickColorDiff(itTemp->second,it->second);
if(minDiff>upDiff){
minDiff=upDiff;
minDiffIt=itTemp;
}
}
if(downID != -1){
std::unordered_map<long,KRegion>::iterator itTemp = m_mapRegion.find(downID);
downDiff=getQuickColorDiff(itTemp->second,it->second);
if(minDiff>downDiff){
minDiff=downDiff;
minDiffIt=itTemp;
}
}
(minDiffIt->second)+=(it->second);
labels[lines*m_iXSize+cols]=(minDiffIt->second).getID();
it = m_mapRegion.erase(it);
}else{
++it;
}
waitBar.update();
}
K_WAITBAR_END(waitBar);
// TODO:move to RAG
buildRAG();
saveSplit("0");
}
int KMultiSplit::getQuickColorMean(KRegion ®, double *colorAvr)
{
int pointSum=0;
for(int index = 0;index<m_nBand;++index){ colorAvr[index]=0.; }
list<KSLE> ltempList=reg.getLists();
for(list<KSLE>::iterator it = ltempList.begin();it != ltempList.end();++it){
int line = it->getLine();
int start = it->getStartCol();
int end = it->getEndCol();
for(int band = 0;band<m_nBand;++band){
for(int index = start;index<=end;++index){
pointSum++;
colorAvr[band]+=m_orgImgBuff[band][line*m_iXSize+index];
}
}
}
for(int band = 0;band<m_nBand;++band){
colorAvr[band]/=pointSum;
}
return pointSum;
}
float KMultiSplit::getQuickColorDiff(KRegion &lhs, KRegion &rhs)
{
int lPointSum = 0;
int rPointSum = 0;
double *lColorAvr=new double[m_nBand];
double *rColorAvr=new double[m_nBand];
lPointSum = getQuickColorMean(lhs,lColorAvr);
rPointSum = getQuickColorMean(rhs,rColorAvr);
double meanSum = 0.;
for(int band=0;band<m_nBand;++band){
double temp = lColorAvr[band]-rColorAvr[band];
temp = temp*temp;
meanSum+=temp;
}
delete [] lColorAvr;
delete [] rColorAvr;
double tempSum = meanSum*lPointSum*rPointSum/(lPointSum+rPointSum);
if(tempSum==0.) return 0.;
//qDebug()<<lPointSum<<rPointSum<<meanSum;
//qDebug()<<"tempSum"<<tempSum;
long tempInt = (boost::math::powm1(tempSum,0.5)+1.)*10000.;
return tempInt/10000.;
}
void KMultiSplit::saveSplit(QString level)
{
if(OutPic == m_tTypeOut){
float **tempImgBuff;
tempImgBuff = (float **) CPLMalloc(sizeof(float *)*m_nBand);
for(int index = 0;index<m_nBand;++index){
tempImgBuff[index]=(float *) CPLMalloc(sizeof(float)*m_iXSize*m_iYSize);
}
QString tempName = m_sOutPut+"-"+level+m_extName;
for(int index = 0;index<m_nBand;++index){
memcpy(tempImgBuff[index],m_orgImgBuff[index],sizeof(float)*m_iXSize*m_iYSize);
}
for(int iY = 0;iY<m_iYSize;++iY){
for(int iX = 0;iX<m_iXSize;++iX){
int tempIndex = iY*m_iXSize+iX;
long curID = labels[tempIndex];
long upID = curID;
long leftID = curID;
if(iX>0){
leftID = labels[tempIndex-1];
}
if(iY>0){
upID = labels[(iY-1)*m_iXSize+iX];
}
if(upID!=curID || curID!=leftID){
if(m_nBand==1){
tempImgBuff[0][tempIndex]=0.;
}else{
tempImgBuff[0][tempIndex]=0.;
tempImgBuff[1][tempIndex]=255.;
tempImgBuff[2][tempIndex]=0.;
}
}else{
if(m_nBand==1){
tempImgBuff[0][tempIndex]=tempImgBuff[0][tempIndex]*255./(m_adfMinMax[1]-m_adfMinMax[0]);
}else{
tempImgBuff[0][tempIndex]=tempImgBuff[0][tempIndex]*255./(m_adfMinMax[1]-m_adfMinMax[0]);
tempImgBuff[1][tempIndex]=tempImgBuff[1][tempIndex]*255./(m_adfMinMax[3]-m_adfMinMax[2]);
tempImgBuff[2][tempIndex]=tempImgBuff[2][tempIndex]*255./(m_adfMinMax[5]-m_adfMinMax[4]);
}
}
}
}
GDALDataset * poutDataset = m_poDriver->Create(tempName.toUtf8().data(),m_iXSize,m_iYSize,3,GDT_Byte,0);
for(int bandIndex = 0;bandIndex<m_nBand;++bandIndex){
GDALRasterBand * poutBand = poutDataset->GetRasterBand(bandIndex+1);
poutBand->RasterIO( GF_Write, 0, 0, m_iXSize,m_iYSize, tempImgBuff[bandIndex], m_iXSize,m_iYSize, GDT_Float32, 0, 0 );
poutBand->FlushCache();
poutDataset->FlushCache();
CPLFree(tempImgBuff[bandIndex]);
}
GDALClose(poutDataset);
CPLFree(tempImgBuff);
}else{
QString tempName = m_sOutPut+"-"+level+".xml";
TiXmlDocument doc;
TiXmlDeclaration* decl = new TiXmlDeclaration( "1.0", "", "" );
doc.LinkEndChild(decl);
TiXmlElement * root = new TiXmlElement( "RegionList" );
doc.LinkEndChild(root);
TiXmlComment * comment = new TiXmlComment();
QString temp = " The RegionList of file: "+m_sInput+" ";
//qDebug()<<temp;
comment->SetValue( temp.toUtf8().constData() );
root->LinkEndChild(comment);
TiXmlElement * regionDescription = new TiXmlElement("RegionDescription");
root->LinkEndChild(regionDescription);
int totalNum = boost::num_vertices(m_RAG);
regionDescription->SetAttribute("total",totalNum);
TiXmlElement * region;
vertexIterator vi, vi_end;
indexMap tempIndexMap = boost::get(boost::vertex_name_t(), m_RAG);
boost::tie(vi,vi_end) = boost::vertices(m_RAG);
std::vector<std::tuple<int,int>> tempVec;
for(;vi!=vi_end;++vi){
int idTemp = tempIndexMap[*vi];
float height=0.;
float width=0.;
std::unordered_map<long,KRegion>::iterator it = m_mapRegion.find(static_cast<long>(idTemp));
region = new TiXmlElement("Region");
regionDescription->LinkEndChild(region);
region->SetAttribute("pixels", (it->second).totalPixels());
region->SetAttribute("id", idTemp);
std::tie(height,width)=getMinArea(it->second,tempVec);
region->SetDoubleAttribute("height", height);
region->SetDoubleAttribute("width", width); // floating point attrib
}
//drawSquare(tempVec);
doc.SaveFile(tempName.toUtf8().constData());
}
// save label array
float * tempLabel=(float *) CPLMalloc(sizeof(float)*m_iXSize*m_iYSize);
for(int index = 0;index<m_iXSize*m_iYSize;++index){
tempLabel[index] = labels[index];
}
GDALDriver *tempDriver = GetGDALDriverManager()->GetDriverByName("GTiff");
QString labelName = m_sOutPutLabel+"-"+level+m_extName;
GDALDataset * poDataset = tempDriver->Create(labelName.toUtf8().data(),m_iXSize,m_iYSize,1,GDT_Int32,0);
GDALRasterBand * poBand = poDataset->GetRasterBand(1);
poBand->RasterIO( GF_Write, 0, 0, m_iXSize,m_iYSize, tempLabel, m_iXSize,m_iYSize, GDT_Float32, 0, 0 );
poBand->FlushCache();
poDataset->FlushCache();
GDALClose(poDataset);
CPLFree(tempLabel);
}
void KMultiSplit::buildRAG()
{
int * tempValid=(int *) CPLMalloc(sizeof(int)*m_iXSize*m_iYSize);
memset(tempValid,1,m_iXSize*m_iYSize*sizeof(int));
KProgressBar progressBar("buildRAG",m_mapRegion.size()*2,80);
K_PROGRESS_START(progressBar);
for(std::unordered_map<long,KRegion>::iterator it = m_mapRegion.begin();it != m_mapRegion.end();++it){
std::set<long> tempVecID;
long curID = (it->second).getID();
const list<KSLE> tempList = (it->second).getLists();
// each region
for(list<KSLE>::const_iterator itSLE = tempList.begin();itSLE != tempList.end();++itSLE){
int line = itSLE->getLine();
int start = itSLE->getStartCol();
int end = itSLE->getEndCol();
// handle each SLE
long tempID = -1;
int tempIndex = -1;
if(start!=0){
tempIndex = line*m_iXSize+start-1;
if(tempValid[tempIndex] && labels[tempIndex] != curID){
tempValid[line*m_iXSize+start]=0;
tempID = labels[tempIndex];
tempVecID.insert(tempID);
}
}
if(end!=m_iXSize-1){
tempIndex = line*m_iXSize+end+1;
if(tempValid[tempIndex] && labels[tempIndex] != curID){
tempValid[line*m_iXSize+end]=0;
tempID = labels[tempIndex];
tempVecID.insert(tempID);
}
}
for(int pixel = start+1;pixel<end;++pixel){
long downID = -1;
long upID = -1;
int tempPos = -1;
if(line==0){
if(line!=m_iYSize-1){
tempPos = (line+1)*m_iXSize+pixel;
if(tempValid[tempPos] && labels[tempPos] != curID) downID = labels[tempPos];
}
}else{
if(line==m_iYSize-1){
tempPos = (line-1)*m_iXSize+pixel;
if(tempValid[tempPos] && labels[tempPos] != curID) upID = labels[tempPos];
}else{
tempPos = (line+1)*m_iXSize+pixel;
if(tempValid[tempPos] && labels[tempPos] != curID) downID = labels[tempPos];
tempPos = (line-1)*m_iXSize+pixel;
if(tempValid[tempPos] && labels[tempPos] != curID) upID = labels[tempPos];
}
}
if(-1 != upID || -1 != downID){
tempValid[line*m_iXSize+pixel]=0;
if(-1 != upID) tempVecID.insert(upID);
if(-1 != downID) tempVecID.insert(downID);
}
}
}
progressBar.autoUpdate();
// link this region
RAGraph::vertex_descriptor v1 = getVertex((it->second).getID());
for(std::set<long>::iterator itSet = tempVecID.begin();itSet != tempVecID.end();++itSet){
std::unordered_map<long,KRegion>::iterator itReg = m_mapRegion.find(*itSet);
//qDebug()<<*itSet;
RAGraph::vertex_descriptor v2 = getVertex(*itSet);
//indexMap tempIndexMap = boost::get(boost::vertex_name_t(), m_RAG);
//qDebug()<<tempIndexMap[v1]<<tempIndexMap[v2];
boost::add_edge(v1, v2, getRegionDiff(it->second,itReg->second), m_RAG);
}
progressBar.autoUpdate();
}
K_PROGRESS_END(progressBar);
CPLFree(tempValid);
}
void KMultiSplit::mergeIn(long &des, long &src)
{
std::unordered_map<long,KRegion>::iterator itDes = m_mapRegion.find(des);
std::unordered_map<long,KRegion>::iterator itSrc = m_mapRegion.find(src);
assert(itDes != m_mapRegion.end() && itSrc != m_mapRegion.end() && itSrc != m_mapRegion.end());
vertexIterator vi, vi_end;
RAGraph::vertex_descriptor v_des,v_src;
indexMap tempIndexMap = boost::get(boost::vertex_name_t(), m_RAG);
boost::tie(vi,vi_end) = boost::vertices(m_RAG);
for(;vi!=vi_end;++vi){
if(tempIndexMap[*vi]==src){
// src point find first
v_src = *vi;
for(;vi!=vi_end;++vi){
if(tempIndexMap[*vi]==des){
v_des = *vi;
break;
}
}
break;
}else if(tempIndexMap[*vi]==des){
v_des = *vi;
for(;vi!=vi_end;++vi){
if(tempIndexMap[*vi]==src){
v_src = *vi;
break;
}
}
break;
}
}
// there's at least one point failed to locate
if(vi==vi_end){
return;
}
RAGraph::adjacency_iterator vit, vend;
std::tie(vit, vend) = boost::adjacent_vertices(v_src, m_RAG);
// change the link graph
for(;vit != vend;++vit){
boost::add_edge(v_des, *vit, 0, m_RAG);
}
boost::clear_vertex(v_src, m_RAG);
boost::remove_vertex(v_src, m_RAG);
// merge the real region
(itDes->second) += (itSrc->second);
m_mapRegion.erase(itSrc);
// change region label
for(int index = 0;index<m_iXSize*m_iYSize;++index){
if(labels[index] == src){
labels[index] = des;
}
}
// change edge's weight
tempIndexMap = boost::get(boost::vertex_name_t(), m_RAG);
{
weightMap tempWeightMap = boost::get(boost::edge_weight_t(),m_RAG);
RAGraph::out_edge_iterator eit, eend;
for(std::tie(eit, eend) = boost::out_edges(v_des, m_RAG);eit != eend;++eit){
RAGraph::vertex_descriptor v_target,v_source;
v_target = boost::target(*eit, m_RAG);
v_source = boost::source(*eit, m_RAG);
std::unordered_map<long,KRegion>::iterator itTarget = m_mapRegion.find(tempIndexMap[v_target]);
std::unordered_map<long,KRegion>::iterator itSource = m_mapRegion.find(tempIndexMap[v_source]);
tempWeightMap[*eit]=getRegionDiff(itTarget->second,itSource->second);
}
}
}
void KMultiSplit::mergeIn(RAGraph::edge_descriptor & edge)
{
RAGraph::vertex_descriptor v_des,v_src;
//std::vector<RAGraph::vertex_descriptor> tempVec;
v_des = boost::target(edge, m_RAG);
v_src = boost::source(edge, m_RAG);
indexMap tempIndexMap = boost::get(boost::vertex_name_t(), m_RAG);
long des = tempIndexMap[v_des];
long src = tempIndexMap[v_src];
std::unordered_map<long,KRegion>::iterator itDes = m_mapRegion.find(des);
std::unordered_map<long,KRegion>::iterator itSrc = m_mapRegion.find(src);
assert(itDes != m_mapRegion.end() && itSrc != m_mapRegion.end());
RAGraph::adjacency_iterator vit, vend;
//RAGraph::adjacency_iterator vdit, vdend;
std::tie(vit, vend) = boost::adjacent_vertices(v_src, m_RAG);
//std::tie(vdit, vdend) = boost::adjacent_vertices(v_des, m_RAG);
// change the link graph
// for(;vit != vend;++vit){
// qDebug()<<tempIndexMap[v_des]<<tempIndexMap[*vit];
// }
for(;vit != vend;++vit){
// default 0
//qDebug()<<tempIndexMap[v_des]<<tempIndexMap[*vit];
//if(std::find(vdit,vdend,*vit)==vdend)
//qDebug()<<v_des<<*vit;
//tempVec.push_back(*vit);
// if(10076==tempIndexMap[v_des])
// {
// qDebug()<<tempIndexMap[v_des]<<tempIndexMap[*vit];
// //if(9895==tempIndexMap[*vit]){
// std::tie(vdit, vdend) = boost::adjacent_vertices(*vit, m_RAG);
// for(;vdit!=vdend;++vdit)qDebug()<<tempIndexMap[*vdit];
// // }
// }
boost::add_edge(v_des, *vit, 0., m_RAG);
}
//for(RAGraph::vertex_descriptor & vertexs:tempVec)boost::add_edge(v_des, vertexs, 0., m_RAG);
boost::clear_vertex(v_src, m_RAG);
boost::remove_vertex(v_src, m_RAG);
// merge the real region
(itDes->second) += (itSrc->second);
m_mapRegion.erase(itSrc);
// change region label
for(int index = 0;index<m_iXSize*m_iYSize;++index){
if(labels[index] == src){
labels[index] = des;
}
}
// change edge's weight
tempIndexMap = boost::get(boost::vertex_name_t(), m_RAG);
weightMap tempWeightMap = boost::get(boost::edge_weight_t(),m_RAG);
{
RAGraph::out_edge_iterator eit, eend;
//qDebug()<<boost::num_edges(m_RAG);
for(std::tie(eit, eend) = boost::out_edges(v_des, m_RAG);eit != eend;++eit){
RAGraph::vertex_descriptor v_target,v_source;
v_target = boost::target(*eit, m_RAG);
v_source = boost::source(*eit, m_RAG);
std::unordered_map<long,KRegion>::iterator itTarget = m_mapRegion.find(tempIndexMap[v_target]);
std::unordered_map<long,KRegion>::iterator itSource = m_mapRegion.find(tempIndexMap[v_source]);
tempWeightMap[*eit]=getRegionDiff(itTarget->second,itSource->second);
}
}
}
void KMultiSplit::runMultiSplit(float startScale, float endScale, float alpha, bool beClear, RAGraph::edges_size_type minAreas)
{
static int level = 1;
if(beClear) level = 1;
float preScale = 0.;
float curScale = 0.;
float minDiff = 0.;
QString tempName = m_sOutPut+"-recorder.txt";
std::fstream fsRecorder(tempName.toUtf8().constData(),std::ios_base::out|std::ios_base::trunc);
QString tempString("");
m_maxScale = endScale;
KWaitBar waitBar("MultiSplit",4,10);
K_WAITBAR_START(waitBar);
while(true){
if(boost::num_edges(m_RAG)<minAreas) break;
std::tie(minDiff,curScale)=getGraphScale();
tempString = QString("%1\t%2\n").arg(minDiff).arg(curScale);
fsRecorder<<tempString.toStdString();
//qDebug()<<"min"<<minDiff;
//qDebug()<<"curScale"<<curScale;
if(curScale>startScale) break;
// merge
mergeCurScale(minDiff);
waitBar.update();
}
preScale = curScale;
saveSplit(QString("%1-%2").arg(level++).arg(curScale,-4));
waitBar.update();
while(true){
if(boost::num_edges(m_RAG)<minAreas){ saveSplit(QString("%1").arg(level++)); break; }
if(curScale<alpha*preScale){
std::tie(minDiff,curScale)=getGraphScale();
tempString = QString("%1\t%2\n").arg(minDiff).arg(curScale);
fsRecorder<<tempString.toStdString();
//qDebug()<<"min"<<minDiff;
//qDebug()<<"curScale"<<curScale;
// merge
mergeCurScale(minDiff);
waitBar.update();
}else{
preScale = curScale;
saveSplit(QString("%1-%2").arg(level++).arg(curScale,-4));
waitBar.update();
if(curScale>endScale){ break; }
}
if(curScale>endScale){ saveSplit(QString("%1").arg(level++)); break; }
}
fsRecorder.close();
K_WAITBAR_END(waitBar);
}
void KMultiSplit::testXMLOutput()
{
// <?xml version="1.0" ?>
// <RegionList>
// <!-- RegionList of file: C://test.jpg -->
// <RegionDescription total="10">
// <Region pixels=1000 id="1" height="5" width="123.456000" />
// </RegionDescription>
// </RegionList>
TiXmlDocument doc;
TiXmlDeclaration* decl = new TiXmlDeclaration( "1.0", "", "" );
doc.LinkEndChild(decl);
TiXmlElement * root = new TiXmlElement( "RegionList" );
doc.LinkEndChild(root);
TiXmlComment * comment = new TiXmlComment();
QString temp = " The RegionList of file: "+m_sInput+" ";
//qDebug()<<temp;
comment->SetValue( temp.toUtf8().constData() );
root->LinkEndChild(comment);
TiXmlElement * regionDescription = new TiXmlElement("RegionDescription");
root->LinkEndChild(regionDescription);
regionDescription->SetAttribute("total",10);
TiXmlElement * region;
region = new TiXmlElement("Region");
regionDescription->LinkEndChild(region);
region->SetAttribute("pixels", 1000);
region->SetAttribute("id", 1);
region->SetAttribute("height", 5);
region->SetDoubleAttribute("width", 123.456); // floating point attrib
doc.SaveFile("C://test.xml");
}
void KMultiSplit::testXMLInput()
{
// <?xml version="1.0" ?>
// <RegionList>
// <!-- RegionList of file: C://test.jpg -->
// <RegionDescription total="10">
// <Region name="nothing" id="1" height="5" weight="123.456000" />
// </RegionDescription>
// </RegionList>
TiXmlDocument doc("C://test.xml");
if (!doc.LoadFile(TIXML_ENCODING_UTF8)) return;
TiXmlHandle hRoot(&doc);
int totalRegions = 0;
double tempDouble = 0.;
int id=0;
int height = 0;
int width = 0;
int pixels = 0;
TiXmlElement* pRegionNode=hRoot.FirstChild("RegionList").FirstChild("RegionDescription").FirstChild().Element();
hRoot.FirstChild("RegionList").FirstChild("RegionDescription").Element()->QueryIntAttribute("total",&totalRegions);
qDebug()<<"totalRegions"<<totalRegions;
for( ; pRegionNode; pRegionNode=pRegionNode->NextSiblingElement())
{
// const char *pName=pRegionNode->Attribute("pixels");
// if (pName) qDebug()<<pName;
pRegionNode->QueryIntAttribute("pixels", &pixels);
pRegionNode->QueryIntAttribute("id", &id);
pRegionNode->QueryIntAttribute("height", &height);
pRegionNode->QueryDoubleAttribute("width",&tempDouble);
qDebug()<<"pixels"<<pixels<<"id"<<id<<"height"<<height<<"width"<<width<<"tempDouble"<<tempDouble;
}
}
void KMultiSplit::mergeCurScale(float minDiff)
{
std::vector<RAGraph::edge_descriptor> edges;
std::vector<RAGraph::vertex_descriptor> points;
RAGraph::edge_iterator eit, eend;
std::tie(eit, eend) = boost::edges(m_RAG);
// get all points needed to be merged
weightMap tempWeightMap = boost::get(boost::edge_weight_t(),m_RAG);
for(;eit != eend;++eit){
float temp = tempWeightMap[*eit];
RAGraph::vertex_descriptor v_target,v_source;
v_target = boost::target(*eit, m_RAG);
v_source = boost::source(*eit, m_RAG);
if(isFloatEqual(minDiff,temp)){
if(std::find(points.begin(),points.end(),v_target) == points.end()
&&std::find(points.begin(),points.end(),v_source) == points.end()){
points.push_back(v_target);
points.push_back(v_source);
edges.push_back(*eit);
}
}
}
// merge
for(RAGraph::edge_descriptor &it : edges) mergeIn(it);
}
int KMultiSplit::getColorVariance(KRegion ®, float *colorVar)
{
int pointSum=0;
float *colorAvr = new float[3];
for(int index = 0;index<m_nBand;++index){ colorVar[index]=0.; colorAvr[index]=0.; }
list<KSLE> ltempList=reg.getLists();
for(list<KSLE>::iterator it = ltempList.begin();it != ltempList.end();++it){
int line = it->getLine();
int start = it->getStartCol();
int end = it->getEndCol();
for(int band = 0;band<m_nBand;++band){
for(int index = start;index<=end;++index){
int tempIndex = line*m_iXSize+index;
pointSum++;
colorAvr[band]+=m_orgImgBuff[band][tempIndex];
colorVar[band]+=m_orgImgBuff[band][tempIndex]*m_orgImgBuff[band][tempIndex];
}
}
}
for(int band = 0;band<m_nBand;++band){
double tempAbs = (std::numeric_limits<double>::max)();
if(pointSum) tempAbs = std::fabs(colorVar[band]-colorAvr[band]*colorAvr[band])/pointSum;
if(tempAbs==0.){ colorVar[band]=0.; continue; }
//qDebug()<<"tempAbs"<<tempAbs;
colorVar[band] = boost::math::powm1(tempAbs,0.5)+1.;
}
delete [] colorAvr;
return pointSum;
}
// height, width ; left-top, left-bottom, right-top, right-bottom---original
std::tuple<float, float> KMultiSplit::getMinArea(KRegion ®,std::vector<std::tuple<int,int>>& cornerVec)
{
std::vector<std::tuple<int,int>> vecPoint;
float minArea = (std::numeric_limits<float>::max)();
std::tuple<float, float, float, float, float, float> pointAtMin;
float degreeAtMin=0.;
const float degreeStep = M_PI/20.;
list<KSLE> tempList = reg.getLists();
cornerVec.clear();
if(tempList.size()==1){
KSLE sle = *(tempList.begin());
int line=sle.getLine()+1;
int start=sle.getStartCol()+1;
int end = sle.getEndCol()+1;
cornerVec.push_back(std::make_tuple(start,line));
cornerVec.push_back(std::make_tuple(start,line));
cornerVec.push_back(std::make_tuple(end,line));
cornerVec.push_back(std::make_tuple(end,line));
//qDebug()<<"test...";
return std::make_tuple(1,end-start+1);
}
for(KSLE sle : tempList){
int line=sle.getLine()+1;
int start=sle.getStartCol()+1;
int end = sle.getEndCol()+1;
vecPoint.push_back(std::make_tuple(line,start));
vecPoint.push_back(std::make_tuple(line,end));
}
if(vecPoint.size()==0){ return std::make_tuple(0.,0.); }
for(float theta=0.;theta<M_PI/2.;theta+=degreeStep){
std::tuple<float, float, float, float, float, float> tempTuple;
tempTuple=getRotateArea(vecPoint,theta);
float area = get<0>(tempTuple)*get<1>(tempTuple);
if(area<minArea){
minArea = area;
pointAtMin = tempTuple;
degreeAtMin = theta;
}
}
std::vector<std::tuple<float,float>> vecRotatedPoint;
vecRotatedPoint.push_back(std::make_tuple(get<4>(pointAtMin),get<2>(pointAtMin)));
vecRotatedPoint.push_back(std::make_tuple(get<5>(pointAtMin),get<2>(pointAtMin)));
vecRotatedPoint.push_back(std::make_tuple(get<5>(pointAtMin),get<3>(pointAtMin)));
vecRotatedPoint.push_back(std::make_tuple(get<4>(pointAtMin),get<3>(pointAtMin)));
for(auto _point:vecRotatedPoint){
float nowTheta = 0.;
if(get<0>(_point)<=0.) nowTheta=std::atan(get<0>(_point)*-1./get<1>(_point))+M_PI/2.;
else nowTheta=std::atan(get<1>(_point)/get<0>(_point));
//qDebug()<<nowTheta;
//if(nowTheta<0) nowTheta+=M_PI;
float orgTheta = nowTheta - degreeAtMin;
float length = get<1>(_point)/std::sin(nowTheta);
float tempY = length * std::cos(orgTheta) - 1.;
if(tempY<0.) tempY = 0.;
if(tempY>m_iYSize-1) tempY=m_iYSize-1;
float tempX = length * std::sin(orgTheta) - 1.;
if(tempX<0.) tempX = 0.;
if(tempX>m_iXSize-1) tempX=m_iXSize-1;
cornerVec.push_back(std::make_tuple(static_cast<int>(tempY),static_cast<int>(tempX)));
}
// if(get<0>(pointAtMin)<0.001){
// qDebug()<<"degreeAtMin"<<degreeAtMin;
// }
//qDebug()<<get<0>(pointAtMin)<<get<1>(pointAtMin);
return std::make_tuple(get<0>(pointAtMin),get<1>(pointAtMin));
}
// height, width, left, right, top, bottom---rotated
std::tuple<float, float, float, float, float, float> KMultiSplit::getRotateArea(std::vector<std::tuple<int,int>> &points, float degree)
{
std::vector<std::tuple<float,float>> tempVecPoint;
float left = (std::numeric_limits<float>::max)();
float top = (std::numeric_limits<float>::max)();
float right = (std::numeric_limits<float>::min)();
float bottom = (std::numeric_limits<float>::min)();
for(auto _point : points){
float orgTheta =std::atan(get<1>(_point)*1./get<0>(_point));
float nowTheta = orgTheta + degree;
float length = get<1>(_point)/std::sin(orgTheta);
tempVecPoint.push_back(std::make_tuple(length*std::cos(nowTheta),length*std::sin(nowTheta)));
}
//qDebug()<<tempVecPoint.size();
for(auto _point:tempVecPoint){
float temp = get<1>(_point);
if(temp>right){
right = temp;
}
if(temp<left){
left = temp;
}
}
for(auto _point:tempVecPoint){
float temp = get<0>(_point);
if(temp>bottom){
bottom = temp;
}
if(temp<top){
top = temp;
}
}
//if(bottom==top) bottom=top+1.;
//if(right==right) right=left+1.;
//qDebug()<<"bottom"<<bottom<<"top"<<top<<"left"<<left<<"right"<<right;
return std::make_tuple(bottom-top+1.,right-left+1.,left,right,top,bottom);
}
KMultiSplit::RAGraph::vertex_descriptor KMultiSplit::getVertex(long id)
{
vertexIterator vi, vi_end;
RAGraph::vertex_descriptor v;
indexMap tempIndexMap = boost::get(boost::vertex_name_t(), m_RAG);
boost::tie(vi,vi_end) = boost::vertices(m_RAG);
for(;vi!=vi_end;++vi){
if(tempIndexMap[*vi]==id){ break; }
}
if(vi==vi_end){
v = add_vertex(m_RAG);
tempIndexMap[v]=id;
}else{ v = *vi; }
return v;
}
float KMultiSplit::getRegionDiff(KRegion &lhs, KRegion &rhs)
{
float colorDiff = 0.;
float shapeDiff = 0.;
float weightedDiff = 0.;
int lPointSum = 0;
int rPointSum = 0;
int totalPointSum = 0;
float *lColorVar=new float[m_nBand];
float *rColorVar=new float[m_nBand];
float *totalColorVar=new float[m_nBand];
std::vector<std::tuple<int,int>> tempVecCorner;
float totalHeight=0.;
float totalWidth = 0.;
float lHeight = 0.;
float lWidth = 0.;
float rHeight = 0.;
float rWidth = 0.;
KRegion tempReg = lhs;
tempReg += rhs;
lPointSum = getColorVariance(lhs,lColorVar);
//qDebug()<<"lPointSum"<<lPointSum;
rPointSum = getColorVariance(rhs,rColorVar);
//qDebug()<<"rPointSum"<<rPointSum;
totalPointSum = getColorVariance(tempReg,totalColorVar);
float varSum = 0.;
//qDebug()<<"totalPointSum"<<totalPointSum;
for(int band=0;band<m_nBand;++band){
varSum +=totalPointSum*totalColorVar[band]-lPointSum*lColorVar[band]-rPointSum*rColorVar[band];
}
//qDebug()<<"colorDiff"<<varSum;
colorDiff = std::fabs(varSum);
std::tie(lHeight,lWidth)=getMinArea(lhs,tempVecCorner);
std::tie(rHeight,rWidth)=getMinArea(rhs,tempVecCorner);
std::tie(totalHeight,totalWidth)=getMinArea(tempReg,tempVecCorner);
// if(totalWidth<0.001)qDebug()<<totalWidth;
// if(lWidth<0.001)qDebug()<<lWidth;
// if(rWidth<0.001)qDebug()<<rWidth;
shapeDiff = std::fabs(totalPointSum*totalHeight/totalWidth-lPointSum*lHeight/lWidth-rPointSum*rHeight/rWidth);
// qDebug()<<"shapeDiff"<<shapeDiff;
weightedDiff = 0.9*colorDiff + 0.1 * shapeDiff;
delete [] lColorVar;
delete [] rColorVar;
delete [] totalColorVar;
return weightedDiff;
}
std::tuple<float, float> KMultiSplit::getGraphScale()
{
float avrDiff = 0.;
float min_diff = (std::numeric_limits<float>::max)();
int edge_num = 0;
RAGraph::edge_iterator eit, eend;
std::tie(eit, eend) = boost::edges(m_RAG);
weightMap tempWeightMap = boost::get(boost::edge_weight_t(),m_RAG);
for(;eit != eend;++eit){
float temp = tempWeightMap[*eit];
//if(temp>100000.)qDebug()<<temp;
if(min_diff>temp) min_diff = temp;
avrDiff += temp;
edge_num++;
}
//qDebug()<<"avrDiff"<<avrDiff;
//qDebug()<<"edge_num"<<edge_num;
if(edge_num) avrDiff /= edge_num;
else return std::make_tuple(min_diff,m_maxScale*2.);
if(avrDiff==0.) return std::make_tuple(min_diff,0.);
return std::make_tuple(min_diff,boost::math::powm1(avrDiff,0.5)+1.);
}
void KMultiSplit::testMinArea()
{
}
void KMultiSplit::drawSquare(std::vector<std::tuple<int,int> > &src, int band)
{
static int count = 0;
GDALDataset *poSrcDS = (GDALDataset *)GDALOpen(m_sInput.toUtf8().constData(), GA_ReadOnly );
GDALDataset *dataSet;
//const char *pszFormat = poSrcDS->GetDriverName();
GDALDriver *poDriver = GetGDALDriverManager()->GetDriverByName("GTiff");
QString tempOut = m_sOutPut + QString("-square%1").arg(count++) + m_extName;
dataSet = poDriver->CreateCopy(tempOut.toUtf8().constData(), poSrcDS, FALSE, NULL, NULL, NULL );
/* Once we're done, close properly the dataset */
dataSet->FlushCache();
GDALClose((GDALDatasetH)poSrcDS);
int width = (penWidth-1)/2;
std::vector<std::pair<int,int>> temp;
m_nBand = std::min(m_nBand,3);
float *pafData = (float *) CPLMalloc(sizeof(float)*m_iXSize*m_iYSize);
GDALRasterBand * piBand = NULL;
for(int index = 0;index<m_nBand;++index){
piBand = dataSet->GetRasterBand(index + 1);
piBand->RasterIO( GF_Read, 0, 0, m_iXSize, m_iYSize, pafData, m_iXSize, m_iYSize, GDT_Float32, 0, 0 );
temp.clear();
for(unsigned int vecIndex = 0;vecIndex<src.size();){
++vecIndex;
temp.push_back(std::make_pair(std::get<1>(src[vecIndex-1]),std::get<0>(src[vecIndex-1])));
if(vecIndex%4==0){
temp.push_back(temp[0]);
for(unsigned int num = 0;num<temp.size()-1;++num){
// process each square
long cnt = 0;
if(std::abs(temp[num].first-temp[num+1].first)<std::abs(temp[num].second-temp[num+1].second)){
double dxy = 1.0 * (temp[num+1].first-temp[num].first )/(temp[num+1].second-temp[num].second);
if(temp[num].second<temp[num+1].second){
for(long pos = temp[num].second;pos<temp[num+1].second;++pos,++cnt) {
long tempX = static_cast<long>(temp[num].first + dxy*cnt);
if(pos<0||pos>m_iYSize-1||tempX<0||tempX>m_iXSize-1) continue;
for(int tempPen = std::max(tempX-width,static_cast<long>(0));tempPen<std::min(tempX+width,static_cast<long>(m_iXSize));++tempPen)
{
if(index==band) pafData[pos*m_iXSize+tempPen]=(std::numeric_limits<float>::max)();
else pafData[pos*m_iXSize+tempPen]=0;
}
}
}else{
for(long pos = temp[num+1].second;pos<temp[num].second;++pos,++cnt) {
long tempX = static_cast<long>(temp[num+1].first + dxy*cnt);
if(pos<0||pos>m_iYSize-1||tempX<0||tempX>m_iXSize-1) continue;
for(int tempPen = std::max(tempX-width,static_cast<long>(0));tempPen<std::min(tempX+width,static_cast<long>(m_iXSize));++tempPen)
{
if(index==band) pafData[pos*m_iXSize+tempPen]=(std::numeric_limits<float>::max)();
else pafData[pos*m_iXSize+tempPen]=0;
}
}
}
}else{
double dyx = 1.0 * (temp[num+1].second-temp[num].second )/(temp[num+1].first-temp[num].first);
if(temp[num].first<temp[num+1].first){
for(long pos = temp[num].first;pos<temp[num+1].first;++pos,++cnt) {
long tempY = static_cast<long>(temp[num].second + dyx*cnt);
if(pos<0||pos>m_iXSize-1||tempY<0||tempY>m_iYSize-1) continue;
//pafData[tempY*XSize+pos]=0;
for(int tempPen = std::max(tempY-width,static_cast<long>(0));tempPen<std::min(tempY+width,static_cast<long>(m_iYSize));++tempPen)
{
if(index==band) pafData[tempPen*m_iXSize+pos]=(std::numeric_limits<float>::max)();
else pafData[tempPen*m_iXSize+pos]=0;
}
}
}else{
for(long pos = temp[num+1].first;pos<temp[num].first;++pos,++cnt) {
long tempY = static_cast<long>(temp[num+1].second + dyx*cnt);
if(pos<0||pos>m_iXSize-1||tempY<0||tempY>m_iYSize-1) continue;
for(int tempPen = std::max(tempY-width,static_cast<long>(0));tempPen<std::min(tempY+width,static_cast<long>(m_iYSize));++tempPen)
{
if(index==band) pafData[tempPen*m_iXSize+pos]=(std::numeric_limits<float>::max)();
else pafData[tempPen*m_iXSize+pos]=0;
}
}
}
}
}
temp.clear();
}
}
piBand->RasterIO( GF_Write, 0, 0, m_iXSize, m_iYSize, pafData, m_iXSize, m_iYSize, GDT_Float32, 0, 0 );
piBand->FlushCache();
}
dataSet->FlushCache();
if( dataSet != NULL )
GDALClose((GDALDatasetH)dataSet);
CPLFree(pafData);
}
/*
* RAGraph::out_edge_iterator eit, eend;
std::tie(eit, eend) = boost::out_edges(v1, m_RAG);
for(;eit!=eend;++eit){
std::cout<<wei[*eit];
std::cout << name[boost::target(*eit, m_RAG)];
std::cout << name[boost::source(*eit, m_RAG)];
}
graph::adjacency_iterator vit, vend;
std::tie(vit, vend) = boost::adjacent_vertices(topLeft, g);
std::copy(vit, vend,
std::ostream_iterator<graph::vertex_descriptor>{std::cout, "\n"});
graph::out_edge_iterator eit, eend;
std::tie(eit, eend) = boost::out_edges(topLeft, g);
std::for_each(eit, eend,
[&g](graph::edge_descriptor it)
{ std::cout << boost::target(it, g) << '\n'; });
*/
| 39.888522 | 161 | 0.558286 | [
"vector"
] |
09b2b7c8674621c819c9edbd996393a706851aaf | 35,133 | cxx | C++ | com/netfx/src/framework/xsp/state/tracker.cxx | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | com/netfx/src/framework/xsp/state/tracker.cxx | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | com/netfx/src/framework/xsp/state/tracker.cxx | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | /**
* tracker
*
* Copyright (c) 1998-1999, Microsoft Corporation
*
*/
#include "precomp.h"
#include "stweb.h"
#include "ary.h"
#include "event.h"
#define FIX_RESPONSE 0
long StateItem::s_cStateItems;
TrackerList Tracker::s_TrackerList;
TrackerList Tracker::s_TrackerListenerList;
long Tracker::s_cTrackers;
HANDLE Tracker::s_eventZeroTrackers = INVALID_HANDLE_VALUE;
bool Tracker::s_bSignalZeroTrackers;
xspmrt::_StateRuntime * Tracker::s_pManagedRuntime;
CReadWriteSpinLock Tracker::s_lockManagedRuntime("Tracker::s_lockManagedRuntime");
RefCount::RefCount()
{
_refs = 1;
}
RefCount::~RefCount()
{
}
STDMETHODIMP
RefCount::QueryInterface(
REFIID iid,
void **ppvObj)
{
if (iid == IID_IUnknown)
{
*ppvObj = this;
AddRef();
return S_OK;
}
else
{
*ppvObj = NULL;
return E_NOINTERFACE;
}
}
STDMETHODIMP_(ULONG)
RefCount::AddRef() {
return InterlockedIncrement(&_refs);
}
STDMETHODIMP_(ULONG)
RefCount::Release() {
long r = InterlockedDecrement(&_refs);
if (r == 0)
{
delete this;
return 0;
}
return r;
}
TrackerCompletion::TrackerCompletion(Tracker * pTracker)
{
_pTracker = pTracker;
_pTracker->AddRef();
}
TrackerCompletion::~TrackerCompletion()
{
ReleaseInterface(_pTracker);
}
STDMETHODIMP
TrackerCompletion::ProcessCompletion(
HRESULT hrErr, int numBytes, LPOVERLAPPED pOverlapped)
{
HRESULT hr;
hr = _pTracker->ProcessCompletion(hrErr, numBytes, pOverlapped);
Release();
return hr;
}
StateItem *
StateItem::Create(int length) {
HRESULT hr = S_OK;
StateItem * psi;
psi = (StateItem *) BlockMem::Alloc(sizeof(StateItem) + length);
ON_OOM_EXIT(psi);
psi->_refs = 1;
psi->_length = length;
InterlockedIncrement(&s_cStateItems);
Cleanup:
return psi;
}
void
StateItem::Free(StateItem * psi) {
BlockMem::Free(psi);
InterlockedDecrement(&s_cStateItems);
}
ULONG
StateItem::AddRef() {
return InterlockedIncrement(&_refs);
}
ULONG
StateItem::Release() {
long r = InterlockedDecrement(&_refs);
if (r == 0)
{
Free(this);
return 0;
}
return r;
}
HRESULT
Tracker::staticInit() {
HRESULT hr = S_OK;
HANDLE eventZeroTrackers;
eventZeroTrackers = CreateEvent(NULL, FALSE, FALSE, NULL);
ON_ZERO_EXIT_WITH_LAST_ERROR(s_eventZeroTrackers);
s_eventZeroTrackers = eventZeroTrackers;
Cleanup:
return hr;
}
void
Tracker::staticCleanup() {
HRESULT hr = S_OK;
hr = DeleteManagedRuntime();
ON_ERROR_CONTINUE();
}
Tracker::Tracker() {
InterlockedIncrement(&s_cTrackers);
_acceptedSocket = INVALID_SOCKET;
_iTrackerList = -1;
}
HRESULT
Tracker::Init(bool fListener) {
HRESULT hr;
_bListener = fListener;
// If a Tracker is a listener it will be stored in s_TrackerListenerList,
// while non-listener will be stored in s_TrackerList. By putting them
// in a separate list, the listeners, which can potentially stay in the
// list for a long period if no new connection arrives, will not prevent
// s_TrackerList from shrinking if the # of non-listening Trackers are
// dropping.
//
// Please note that when a Tracker is changed from a listener to a
// non-listener (see ProcessListening), it will be moved from
// s_TrackerListenerList to s_TrackerList.
if (fListener) {
hr = s_TrackerListenerList.AddEntry(this, &_iTrackerList);
}
else {
hr = s_TrackerList.AddEntry(this, &_iTrackerList);
}
ON_ERROR_EXIT();
Cleanup:
return hr;
}
Tracker::~Tracker() {
HRESULT hr = S_OK;
int result;
LogError();
if (_iTrackerList != -1) {
if (_bListener) {
#if DBG
Tracker *pTracker =
#endif
s_TrackerListenerList.RemoveEntry(_iTrackerList);
ASSERT(pTracker == this);
}
else {
#if DBG
Tracker *pTracker =
#endif
s_TrackerList.RemoveEntry(_iTrackerList);
ASSERT(pTracker == this);
}
}
delete [] _pchProcessErrorFuncList;
if (_acceptedSocket != INVALID_SOCKET) {
result = closesocket(_acceptedSocket);
ON_SOCKET_ERROR_CONTINUE(result);
}
delete _pReadBuffer;
delete [] _wsabuf[0].buf;
if (_psi) {
_psi->Release();
}
result = InterlockedDecrement(&s_cTrackers);
if (result == 0 && s_bSignalZeroTrackers) {
s_bSignalZeroTrackers = false;
result = SetEvent(s_eventZeroTrackers);
ASSERT(result != 0);
}
}
void
Tracker::SignalZeroTrackers() {
int result;
s_bSignalZeroTrackers = true;
if (s_cTrackers == 0) {
s_bSignalZeroTrackers = false;
result = SetEvent(s_eventZeroTrackers);
ASSERT(result != 0);
}
}
HRESULT
Tracker::Listen(SOCKET listenSocket) {
HRESULT hr = S_OK;
int result;
DWORD byteCount = 0;
TrackerCompletion * pCompletion = NULL;
ASSERT(_acceptedSocket == INVALID_SOCKET);
/*
* Create accept socket.
*/
_acceptedSocket = WSASocket(AF_INET, SOCK_STREAM, IPPROTO_TCP,
NULL, 0, WSA_FLAG_OVERLAPPED);
if (_acceptedSocket == INVALID_SOCKET)
EXIT_WITH_LAST_SOCKET_ERROR();
/*
* Associate it with the completion port.
*/
hr = AttachHandleToThreadPool((HANDLE)_acceptedSocket);
ON_ERROR_EXIT();
_pmfnProcessCompletion = &Tracker::ProcessListening;
pCompletion = new TrackerCompletion(this);
ON_OOM_EXIT(pCompletion);
pCompletion->AddRef();
/*
* Issue the accept/recv/etc call.
*/
result = AcceptEx(
listenSocket, // sListenSocket
_acceptedSocket, // sAcceptSocket
_addrInfo._bufAddress, // lpOutputBuffer
0, // dwReceiveDataLength
ADDRESS_LENGTH, // dwLocalAddressLength
ADDRESS_LENGTH, // dwRemoteAddressLength
&byteCount, // lpdwBytesReceived
pCompletion->Overlapped() // lpOverlapped
);
if (result == FALSE) {
hr = GetLastWin32Error();
if (hr == HRESULT_FROM_WIN32(ERROR_IO_PENDING)) {
hr = S_OK;
}
else {
pCompletion->Release();
_pmfnProcessCompletion = NULL;
EXIT();
}
}
Cleanup:
ReleaseInterface(pCompletion);
RecordProcessError(hr, L"Listen");
return hr;
}
HRESULT
Tracker::ProcessCompletion(HRESULT hrErr, int numBytes, LPOVERLAPPED) {
HRESULT hr = S_OK;
pmfnProcessCompletion pmfn;
ASSERT(_iTrackerList != -1);
// We've set an expiry if we're not a Listener
if (!_bListener) {
// The timer might have expired us already. If that's the case,
// SetNoExpire will return FALSE, and the timer thread
// is on its way to close the socket.
if (s_TrackerList.SetNoExpire(_iTrackerList) != TRUE) {
// Release because the timer has expired and closed
// the socket already
hr = HRESULT_FROM_WIN32(ERROR_TIMEOUT);
RecordProcessError(hr, L"ProcessCompletion");
// ProcessWriting will not release the tracker's ref count
if (_pmfnProcessCompletion != &Tracker::ProcessWriting) {
Release();
}
ON_ERROR_EXIT();
}
}
// (adams) 6/26/00: Debugging code to catch ASURT 37649.
_pmfnLast = _pmfnProcessCompletion;
pmfn = _pmfnProcessCompletion;
_pmfnProcessCompletion = NULL;
ASSERT(pmfn != NULL);
hr = (this->*pmfn)(hrErr, numBytes);
if (hr) {
/* Release this tracker when an error occurs*/
RecordProcessError(hr, L"ProcessCompletion");
Release();
if (IsExpectedError(hr)) {
// Don't want expected error to be reported in
// ThreadPoolThreadProc() in threadpool.cxx
hr = S_OK;
}
else {
TRACE_ERROR(hr);
TRACE1(TAG_STATE_SERVER, L"Error occurred (%08x), releasing tracker.", hr);
}
}
Cleanup:
return hr;
}
BOOL
Tracker::IsExpectedError(HRESULT hr) {
//
// ERROR_GRACEFUL_DISCONNECT: Happens when the client closed the socket
// ERROR_OPERATION_ABORTED: Happens when we shut down
// ERROR_NETNAME_DELETED: Happens when the timer expires the socket
// WSAECONNABORTED: Happens when the client times out the connection
//
//
return (hr == HRESULT_FROM_WIN32(ERROR_GRACEFUL_DISCONNECT) ||
hr == HRESULT_FROM_WIN32(ERROR_OPERATION_ABORTED) ||
hr == HRESULT_FROM_WIN32(ERROR_NETNAME_DELETED) ||
hr == HRESULT_FROM_WIN32(WSAECONNABORTED));
}
__int64 g_LastSocketExpiryError = 0;
#define FT_SECOND ((__int64) 10000000)
void
Tracker::LogSocketExpiryError( DWORD dwEventId )
{
SYSTEMTIME st;
FILETIME ft;
WCHAR *pchOp;
__int64 now;
GetSystemTimeAsFileTime((FILETIME *) &now);
if (now - g_LastSocketExpiryError < FT_SECOND * 60) {
return;
}
FileTimeToLocalFileTime(&_IOStartTime, &ft);
FileTimeToSystemTime(&ft, &st);
if (_pmfnProcessCompletion == &Tracker::ProcessWriting) {
pchOp = L"Write";
}
else if (_pmfnProcessCompletion == &Tracker::ProcessReading) {
pchOp = L"Read";
}
else {
pchOp = L"Unknown";
}
XspLogEvent( dwEventId, L"%d^%d^%d^%d^%s^%02d^%02d^%04d^%02d^%02d^%02d",
_addrInfo._sockAddrs._addrRemote.sin_addr.S_un.S_un_b.s_b1,
_addrInfo._sockAddrs._addrRemote.sin_addr.S_un.S_un_b.s_b2,
_addrInfo._sockAddrs._addrRemote.sin_addr.S_un.S_un_b.s_b3,
_addrInfo._sockAddrs._addrRemote.sin_addr.S_un.S_un_b.s_b4,
pchOp, st.wMonth, st.wDay, st.wYear, st.wHour, st.wMinute, st.wSecond);
g_LastSocketExpiryError = now;
}
void
Tracker::LogError()
{
WCHAR * pchFunc;
HRESULT hr = S_OK;
if (_hrProcessError == S_OK)
EXIT();
if (_hrProcessError == HRESULT_FROM_WIN32(ERROR_TIMEOUT)) {
LogSocketExpiryError( IDS_EVENTLOG_STATE_SERVER_EXPIRE_CONNECTION );
}
else {
if (_pchProcessErrorFuncList) {
pchFunc = _pchProcessErrorFuncList;
}
else {
pchFunc = L"Unknown";
}
XspLogEvent( IDS_EVENTLOG_STATE_SERVER_ERROR, L"%s^0x%08x", pchFunc, _hrProcessError );
}
Cleanup:
return;
}
HRESULT
Tracker::ProcessListening(HRESULT hrCompletion, int) {
HRESULT hr;
int result;
SOCKET listenSocket;
SOCKADDR * paddrLocal;
SOCKADDR * paddrRemote;
int lengthLocal;
int lengthRemote;
hr = hrCompletion;
ON_ERROR_EXIT();
TRACE(TAG_STATE_SERVER, L"Accepted a new connection.");
/*
* Inherit socket options from listener.
*/
listenSocket = StateWebServer::Server()->ListenSocket();
result = setsockopt(_acceptedSocket, SOL_SOCKET, SO_UPDATE_ACCEPT_CONTEXT,
(char *)&listenSocket, sizeof(listenSocket));
/*
* We've accepted a connection. Accept another connection to
* replace this one.
*/
hr = StateWebServer::Server()->AcceptNewConnection();
ON_ERROR_CONTINUE();
hr = S_OK;
/*
* Get the local and remote addresses.
*/
GetAcceptExSockaddrs(
_addrInfo._bufAddress,
0,
ADDRESS_LENGTH,
ADDRESS_LENGTH,
&paddrLocal,
&lengthLocal,
&paddrRemote,
&lengthRemote);
ASSERT(lengthLocal == sizeof(_addrInfo._sockAddrs._addrLocal));
ASSERT(lengthRemote == sizeof(_addrInfo._sockAddrs._addrRemote));
_addrInfo._sockAddrs._addrLocal = * (SOCKADDR_IN *) paddrLocal;
_addrInfo._sockAddrs._addrRemote = * (SOCKADDR_IN *) paddrRemote;
/*
* This Tracker is no longer a listener. Let's remove it from
* s_TrackerListenerList and add it to s_TrackerList
*/
ASSERT(_iTrackerList != -1);
ASSERT(_bListener);
#if DBG
Tracker *pTracker =
#endif
s_TrackerListenerList.RemoveEntry(_iTrackerList);
ASSERT(pTracker == this);
_bListener = FALSE;
_iTrackerList = -1;
hr = s_TrackerList.AddEntry(this, &_iTrackerList);
ON_ERROR_EXIT();
if (!StateWebServer::Server()->AllowRemote() && !IsLocalConnection()) {
EXIT_WITH_WIN32_ERROR(ERROR_NETWORK_ACCESS_DENIED);
}
hr = StartReading();
ON_ERROR_EXIT();
Cleanup:
RecordProcessError(hr, L"ProcessListening");
return hr;
}
HRESULT
Tracker::StartReading() {
HRESULT hr = S_OK;
_pReadBuffer = new ReadBuffer;
ON_OOM_EXIT(_pReadBuffer);
hr = _pReadBuffer->Init(this, NULL, NULL);
ON_ERROR_EXIT();
hr = ProcessReading(S_OK, (DWORD) -1);
ON_ERROR_EXIT();
Cleanup:
RecordProcessError(hr, L"StartReading");
return hr;
}
HRESULT
Tracker::ContinueReading(Tracker * pTracker)
{
HRESULT hr = S_OK;
int toread;
ASSERT(pTracker->_acceptedSocket != INVALID_SOCKET);
_acceptedSocket = pTracker->_acceptedSocket;
_addrInfo._sockAddrs = pTracker->_addrInfo._sockAddrs;
pTracker->_acceptedSocket = INVALID_SOCKET;
_pReadBuffer = new ReadBuffer;
ON_OOM_EXIT(_pReadBuffer);
hr = _pReadBuffer->Init(this, pTracker->_pReadBuffer, &toread);
ON_ERROR_EXIT();
hr = ProcessReading(S_OK, toread);
ON_ERROR_EXIT();
Cleanup:
RecordProcessError(hr, L"ContinueReading");
return hr;
}
HRESULT
Tracker::ProcessReading(HRESULT hrCompletion, int numBytes) {
HRESULT hr = hrCompletion;
if (IsExpectedError(hr)) {
EXIT_WITH_SUCCESSFUL_HRESULT(hr);
}
ON_ERROR_EXIT();
hr = _pReadBuffer->ReadRequest(numBytes);
if (hr == S_OK) {
/* done reading, submit */
hr = SubmitRequest();
ON_ERROR_EXIT();
}
else if (hr == S_FALSE) {
/* OK so far, but still reading */
hr = S_OK;
}
else {
if (IsExpectedError(hr)) {
EXIT_WITH_SUCCESSFUL_HRESULT(hr);
}
ON_ERROR_EXIT();
}
Cleanup:
RecordProcessError(hr, L"ProcessReading");
return hr;
}
HRESULT
Tracker::Read(void * buf, int cb)
{
HRESULT hr = S_OK;
int err;
DWORD cbRecv;
DWORD flags;
WSABUF awsabuf[1];
TrackerCompletion * pCompletion = NULL;
ASSERT(_acceptedSocket != INVALID_SOCKET);
_pmfnProcessCompletion = &Tracker::ProcessReading;
pCompletion = new TrackerCompletion(this);
ON_OOM_EXIT(pCompletion);
pCompletion->AddRef();
awsabuf[0].len = cb;
awsabuf[0].buf = (char *) buf;
cbRecv = 0;
flags = 0;
// Set Expiry info first so that the Completion thread
// has the correct info.
s_TrackerList.SetExpire(_iTrackerList);
// For trapping ASURT 91153
GetSystemTimeAsFileTime(&_IOStartTime);
err = WSARecv(_acceptedSocket, awsabuf, 1, &cbRecv, &flags, pCompletion->Overlapped(), NULL);
if (err == SOCKET_ERROR) {
err = WSAGetLastError();
if (err != WSA_IO_PENDING) {
s_TrackerList.SetNoExpire(_iTrackerList);
_pmfnProcessCompletion = NULL;
pCompletion->Release();
EXIT_WITH_WIN32_ERROR(err);
}
}
Cleanup:
ReleaseInterface(pCompletion);
RecordProcessError(hr, L"Tracker::Read");
return hr;
}
void
Tracker::RecordProcessError(HRESULT hrProcess, WCHAR *CurrFunc)
{
WCHAR *pchCallStack;
int len;
HRESULT hr = S_OK;
// Skip success or expected error case
if (hrProcess == S_OK || IsExpectedError(hrProcess))
{
EXIT();
}
TRACE_ERROR(hrProcess);
if (_hrProcessError == S_OK) {
_hrProcessError = hrProcess;
}
len = lstrlenW(CurrFunc) + 1;
if (_pchProcessErrorFuncList) {
len += lstrlenW(_pchProcessErrorFuncList)
+ 3; // "-->"
}
pchCallStack = new WCHAR[len];
ON_OOM_EXIT(pchCallStack);
StringCchCopyW(pchCallStack, len, CurrFunc);
if (_pchProcessErrorFuncList) {
StringCchCatW(pchCallStack, len, L"-->");
StringCchCatW(pchCallStack, len, _pchProcessErrorFuncList);
}
delete [] _pchProcessErrorFuncList;
_pchProcessErrorFuncList = pchCallStack;
Cleanup:
return;
}
#define STR_HTTP_11 "HTTP/1.1 "
#define STR_CONTENT_LENGTH "Content-Length: "
#define STR_CRLFCRLF "\r\n\r\n"
void
Tracker::SendResponse(
WCHAR * status,
int statusLength,
WCHAR * headers,
int headersLength,
StateItem *psi) {
HRESULT hr = S_OK;
int result, err;
int maxLength, size;
char *pchHeaders = NULL;
char *pch;
int currentLength;
int contentLength;
int cBuffers = 1;
DWORD cbSent;
TrackerCompletion * pCompletion = NULL;
/*
* Only try to submit the response once. Reporting errors from this function
* doesn't make sense, because an error could occur during the write that
* will only be detected the completion. And if we run out of memory
* constructing the reponse, we probably won't have enough
* memory to construct another response to report the error.
*
* Also, we only use a single completion for writes, because we expect
* to write just once. We must prevent reuse of this completion.
*/
if (_responseSent)
return;
_responseSent = true;
if (psi != NULL) {
contentLength = psi->GetLength();
}
else {
contentLength = 0;
}
/*
* Create buffer to write headers.
*/
maxLength =
statusLength +
headersLength +
ARRAY_SIZE(STR_CONTENT_LENGTH) +
10 + /* max digits in a base-10 32-bit integer */
sizeof(STR_CRLFCRLF) - 1;
#if FIX_RESPONSE
maxLength += ARRAY_SIZE(STR_HTTP_11);
#endif
size = (maxLength * 2);
pchHeaders = new char[size];
ON_OOM_EXIT(pchHeaders);
currentLength = 0;
#if FIX_RESPONSE
CopyMemory(pchHeaders + currentLength, STR_HTTP_11, sizeof(STR_HTTP_11) - 1);
currentLength += sizeof(STR_HTTP_11) - 1;
#endif
currentLength += WideCharToMultiByte(CP_ACP, 0, status, statusLength, pchHeaders + currentLength, size, NULL, NULL);
#if FIX_RESPONSE
ASSERT(currentLength > sizeof(STR_HTTP_11) - 1);
#else
ASSERT(currentLength > 0);
#endif
result = WideCharToMultiByte(CP_ACP, 0, headers, headersLength, pchHeaders + currentLength, size - currentLength, NULL, NULL);
ASSERT(result > 0);
currentLength += result;
CopyMemory(pchHeaders + currentLength, STR_CONTENT_LENGTH, sizeof(STR_CONTENT_LENGTH) - 1);
currentLength += (sizeof(STR_CONTENT_LENGTH) - 1);
_itoa(contentLength, pchHeaders + currentLength, 10);
pch = pchHeaders + currentLength;
while (*pch != '\0') {
pch++;
}
currentLength = PtrToLong(pch - pchHeaders);
CopyMemory(pch, STR_CRLFCRLF, sizeof(STR_CRLFCRLF) - 1);
currentLength += sizeof(STR_CRLFCRLF) - 1;
_wsabuf[0].len = currentLength;
_wsabuf[0].buf = pchHeaders;
pchHeaders = NULL;
/*
* Write content.
*/
if (contentLength > 0) {
_psi = psi;
_psi->AddRef();
_wsabuf[1].len = contentLength;
_wsabuf[1].buf = (char *) psi->GetContent();
cBuffers = 2;
}
_pmfnProcessCompletion = &Tracker::ProcessWriting;
pCompletion = new TrackerCompletion(this);
ON_OOM_EXIT(pCompletion);
pCompletion->AddRef();
// Set Expiry info first so that the Completion thread
// has the correct info.
s_TrackerList.SetExpire(_iTrackerList);
// For trapping ASURT 91153
GetSystemTimeAsFileTime(&_IOStartTime);
ASSERT(_acceptedSocket != INVALID_SOCKET);
err = WSASend(_acceptedSocket, _wsabuf, cBuffers, &cbSent, 0, pCompletion->Overlapped(), NULL);
if (err == SOCKET_ERROR) {
err = WSAGetLastError();
if (err != WSA_IO_PENDING) {
s_TrackerList.SetNoExpire(_iTrackerList);
_pmfnProcessCompletion = NULL;
pCompletion->Release();
EXIT_WITH_WIN32_ERROR(err);
}
}
#if DBG
else {
ASSERT(cbSent == (int) (_wsabuf[0].len + _wsabuf[1].len));
}
#endif
Cleanup:
ReleaseInterface(pCompletion);
delete [] pchHeaders;
}
/*
* N.B. ProcessWriting may be called while this Tracker
* is still being used by managed code. So we can only
* refer to fields in this object that are protected in
* some way (such as the refcount is protected by interlocked
* operations).
*/
HRESULT
Tracker::ProcessWriting(HRESULT hrCompletion, int numBytes)
{
#if DBG
if (hrCompletion == S_OK) {
ASSERT(numBytes == (int) (_wsabuf[0].len + _wsabuf[1].len));
}
#else
UNREFERENCED_PARAMETER(numBytes);
#endif
RecordProcessError(hrCompletion, L"ProcessWriting");
return hrCompletion;
}
void
Tracker::EndOfRequest()
{
HRESULT hr = S_OK;
Tracker * pTracker = NULL;
if (_ended)
return;
_ended = true;
if (!_bCloseConnection) {
pTracker = new Tracker();
if (pTracker != NULL) {
hr = pTracker->Init(false);
if (hr == S_OK) {
hr = pTracker->ContinueReading(this);
}
if (hr) {
RecordProcessError(hr, L"EndOfRequest");
pTracker->Release();
}
}
}
}
BOOL
Tracker::IsClientConnected() {
return IsSocketConnected(_acceptedSocket);
}
void
Tracker::CloseConnection() {
/*
* Don't want to close the connection immediately if there
* is outstanding I/O.
*/
_bCloseConnection = true;
}
HRESULT
Tracker::CloseSocket() {
HRESULT hr = S_OK;
int result;
SOCKET socket = _acceptedSocket;
// _acceptedSocket can be INVALID_SOCKET if it still has
// a pending WSASend, but EndOfRequest has been called.
if (socket != INVALID_SOCKET) {
_acceptedSocket = INVALID_SOCKET;
result = closesocket(socket);
ON_SOCKET_ERROR_EXIT(result);
}
Cleanup:
return hr;
}
void
Tracker::GetRemoteAddress(char * buf) {
char * s;
s = inet_ntoa(_addrInfo._sockAddrs._addrRemote.sin_addr);
StringCchCopyUnsafeA(buf, s);
}
int
Tracker::GetRemotePort() {
return ntohs(_addrInfo._sockAddrs._addrRemote.sin_port);
}
void
Tracker::GetLocalAddress(char * buf) {
char * s;
s = inet_ntoa(_addrInfo._sockAddrs._addrLocal.sin_addr);
StringCchCopyUnsafeA(buf, s);
}
int
Tracker::GetLocalPort() {
return ntohs(_addrInfo._sockAddrs._addrLocal.sin_port);
}
bool
Tracker::IsLocalConnection() {
PHOSTENT phe;
if ( _addrInfo._sockAddrs._addrRemote.sin_addr.S_un.S_un_b.s_b1 == 127 &&
_addrInfo._sockAddrs._addrRemote.sin_addr.S_un.S_un_b.s_b2 == 0 &&
_addrInfo._sockAddrs._addrRemote.sin_addr.S_un.S_un_b.s_b3 == 0 &&
_addrInfo._sockAddrs._addrRemote.sin_addr.S_un.S_un_b.s_b4 == 1) {
return TRUE;
}
phe = gethostbyname(NULL);
if((phe == NULL) || (phe->h_addr_list == NULL))
return FALSE;
for(DWORD** ppAddress = (DWORD**)phe->h_addr_list; *ppAddress != NULL; ++ppAddress)
{
if(**ppAddress == _addrInfo._sockAddrs._addrRemote.sin_addr.s_addr)
return TRUE;
}
return FALSE;
}
TrackerList::TrackerList():_TrackerListLock("TrackerList::_TrackerListLock")
{
_iFreeHead = -1;
_iFreeTail = -1;
}
TrackerList::~TrackerList()
{
ASSERT(IsValid());
delete _pTLEArray;
}
HRESULT
TrackerList::AddEntry(Tracker *pTracker, int *pIndex) {
HRESULT hr = S_OK;
int index;
ASSERT(pTracker != NULL);
*pIndex = -1;
_TrackerListLock.AcquireWriterLock();
__try {
if (_cFreeElem == 0) {
hr = Grow();
ON_ERROR_EXIT();
}
index = _iFreeHead;
_iFreeHead = _pTLEArray[index]._iNext; // Point to the next free element
_cFreeElem--;
// Adjust no. of free elements in the 2nd half of the array
if (index >= _ArraySize/2) {
_cFree2ndHalf--;
}
if (_cFreeElem == 0) {
_iFreeTail = -1;
}
_pTLEArray[index]._pTracker = pTracker;
_pTLEArray[index]._ExpireTime = -1;
*pIndex = index;
}
__finally {
ASSERT(IsValid());
_TrackerListLock.ReleaseWriterLock();
}
Cleanup:
return hr;
}
Tracker *
TrackerList::RemoveEntry(int index) {
HRESULT hr = S_OK;
Tracker *pTracker = NULL;
_TrackerListLock.AcquireWriterLock();
__try {
ASSERT(index >= 0 && index < _ArraySize);
if (index < 0 || index >= _ArraySize) {
hr = ERROR_NOT_FOUND;
ON_WIN32_ERROR_EXIT(hr);
}
pTracker = _pTLEArray[index]._pTracker;
ASSERT(pTracker != NULL);
// Return the element to the free list
// Trick:
// If we want to contract the array, we can only free up consecutive
// elements at the end, because we cannot rearrange the locations
// of used elements inside the array. In order to make the contraction
// more efficient, we want to avoid an AddEntry call to pickup a free slot
// near the end of the array.
// Because AddEntry always picks up free slot from the head, when freeing
// an item, we will stick it to either the head or the tail of the free
// list, based on its index. Small index goes to head, big index goes
// to tail. This way, free slot with small index should be used first,
// and thus help out the contraction.
// Catch the boundary case
if (_iFreeHead == _iFreeTail && _iFreeHead == -1) {
_iFreeHead = index;
_iFreeTail = index;
_pTLEArray[index]._iNext = -1;
}
else if (index < _ArraySize/2) {
// Smaller half
_pTLEArray[index]._iNext = _iFreeHead;
_iFreeHead = index;
}
else {
// Larger half
_pTLEArray[_iFreeTail]._iNext = index;
_pTLEArray[index]._iNext = -1;
_iFreeTail = index;
}
_pTLEArray[index].MarkAsFree();
_cFreeElem++;
// Adjust no. of free elements in the 2nd half of the array
if (index >= _ArraySize/2) {
_cFree2ndHalf++;
}
}
__finally {
ASSERT(IsValid());
_TrackerListLock.ReleaseWriterLock();
}
Cleanup:
return pTracker;
}
void TrackerList::TryShrink() {
int NewSize, ShrinkBy, i, cFree;
TLE *pNewArray;
HRESULT hr = S_OK;
_TrackerListLock.AcquireWriterLock();
__try {
while (_ArraySize > TRACKERLIST_ALLOC_SIZE &&
_cFree2ndHalf == _ArraySize/2) {
// Shrink the array by multiples of TRACKERLIST_ALLOC_SIZE,
// up to half of _ArraySize
ShrinkBy = (_ArraySize / 2 / TRACKERLIST_ALLOC_SIZE) * TRACKERLIST_ALLOC_SIZE;
ASSERT(IsShrinkable());
// Realloc a new buffer for the elements
NewSize = _ArraySize - ShrinkBy;
pNewArray = new (_pTLEArray, NewReAlloc) TLE[NewSize];
ON_OOM_EXIT(pNewArray);
_pTLEArray = pNewArray;
_cFreeElem -= ShrinkBy;
_ArraySize = NewSize;
_iFreeHead = -1;
_iFreeTail = -1;
// Reconstruct the free list and recount _cFree2ndHalf
_cFree2ndHalf = 0;
cFree = 0;
for (i=_ArraySize-1; i >= 0; i--) {
if (_pTLEArray[i].IsFree()) {
if (_iFreeHead == -1) {
ASSERT(_iFreeTail == -1);
_iFreeHead = _iFreeTail = i;
_pTLEArray[i]._iNext = -1;
}
else {
_pTLEArray[i]._iNext = _iFreeHead;
_iFreeHead = i;
}
if (i >= _ArraySize/2) {
_cFree2ndHalf++;
}
#if DBG
cFree++;
#endif
}
}
#if DBG
_cShrink++;
#endif
ASSERT(cFree == _cFreeElem);
}
}
__finally {
ASSERT(IsValid());
_TrackerListLock.ReleaseWriterLock();
}
Cleanup:
return;
}
__int64 TrackerList::NewExpireTime() {
__int64 now;
GetSystemTimeAsFileTime((FILETIME *) &now);
// We allow 3 sec of slack time so that the thread has enough
// time between setting expiry time and make the winsock call
return now +
(__int64)(StateWebServer::Server()->SocketTimeout() + 3)*TICKS_PER_SEC;
}
void TrackerList::SetExpire(int index) {
_TrackerListLock.AcquireReaderLock();
__try {
ASSERT(index >= 0 && index < _ArraySize);
ASSERT(!_pTLEArray[index].IsFree());
// The current logic in Tracker will not set the expire time again
// without first calling SetNoExpire
ASSERT(_pTLEArray[index]._ExpireTime == -1);
_pTLEArray[index]._ExpireTime = NewExpireTime();
}
__finally {
_TrackerListLock.ReleaseReaderLock();
}
return;
}
bool
TrackerList::SetNoExpire(int index) {
bool ret = TRUE;;
_TrackerListLock.AcquireReaderLock();
__try {
ASSERT(index >= 0 && index < _ArraySize);
ASSERT(!_pTLEArray[index].IsFree());
// For each entry in the array, potentially only ONE tracker and the
// Timer can "check expire time and update it" concurrently.
// Since the Timer always acquires a Writer Lock when traversing the array,
// the Tracker only needs to acquire a Reader Lock.
if (_pTLEArray[index]._ExpireTime == -1) {
ret = FALSE; // Returning FALSE means someone has unset it already
}
else {
_pTLEArray[index]._ExpireTime = -1;
}
}
__finally {
_TrackerListLock.ReleaseReaderLock();
}
return ret;
}
HRESULT
TrackerList::Grow() {
int NewSize, i;
HRESULT hr = S_OK;
TLE *pNewArray;
_TrackerListLock.AcquireWriterLock();
__try {
// Realloc a new buffer for the elements
NewSize = _ArraySize + TRACKERLIST_ALLOC_SIZE;
pNewArray = new (_pTLEArray, NewReAlloc) TLE[NewSize];
ON_OOM_EXIT(pNewArray);
_pTLEArray = pNewArray;
ZeroMemory(&_pTLEArray[_ArraySize], TRACKERLIST_ALLOC_SIZE * sizeof(TLE));
// Initialize new free list
_iFreeHead = _ArraySize;
_iFreeTail = NewSize - 1;
for (i=_iFreeHead; i < _iFreeTail; i++) {
_pTLEArray[i]._iNext = i+1;
}
// Point the last element to -1
_pTLEArray[_iFreeTail]._iNext = -1;
_cFreeElem = TRACKERLIST_ALLOC_SIZE;
_ArraySize = NewSize;
ASSERT(_cFree2ndHalf == 0);
if (_ArraySize == TRACKERLIST_ALLOC_SIZE)
_cFree2ndHalf = TRACKERLIST_ALLOC_SIZE/2;
else
_cFree2ndHalf = TRACKERLIST_ALLOC_SIZE;
}
__finally {
ASSERT(IsValid());
_TrackerListLock.ReleaseWriterLock();
}
Cleanup:
return hr;
}
void
TrackerList::CloseExpiredSockets()
{
HRESULT hr = S_OK;
int i;
__int64 now;
Tracker *pTracker;
#if DBG
SYSTEMTIME st;
GetLocalTime(&st);
#endif
GetSystemTimeAsFileTime((FILETIME *) &now);
TRACE4(TAG_STATE_SERVER, L"CloseSockets: Shrink=%d Size=%d Free=%d 2ndHalfFre=%d", _cShrink,
_ArraySize, _cFreeElem, _cFree2ndHalf);
_TrackerListLock.AcquireWriterLock();
__try {
for (i=0; i<_ArraySize; i++) {
// Skip:
// - Free item
// - Item that has no expiry time
// - Item that hasn't expired yet
if (_pTLEArray[i].IsFree() ||
_pTLEArray[i]._ExpireTime == -1 ||
_pTLEArray[i]._ExpireTime > now) {
continue;
}
// The item has expired.
pTracker = _pTLEArray[i]._pTracker;
TRACE4(TAG_STATE_SERVER, L"Close expired socket (%p), Time (%02d:%02d:%02d)",
pTracker->AcceptedSocket(), st.wHour, st.wMinute, st.wSecond);
hr = pTracker->CloseSocket();
ON_ERROR_CONTINUE();
#if DBG
// For trapping ASURT 91153
pTracker->LogSocketExpiryError( IDS_EVENTLOG_STATE_SERVER_EXPIRE_CONNECTION_DEBUG );
#endif
// Unset the expiry time so that the owning Tracker object
// knows that we've expired it already
_pTLEArray[i]._ExpireTime = -1;
}
// We'll also try to shrink the array as part of
// flushing the list.
TryShrink();
}
__finally {
_TrackerListLock.ReleaseWriterLock();
}
return;
}
| 25.532703 | 131 | 0.576381 | [
"object"
] |
09b7f50bdbb7fb489f147ff8ff7e5983b4a7fa48 | 5,264 | cpp | C++ | Soruce/ModuleImGui.cpp | ermario/3DEngineApp | 9a6ae32ce3aba5c610c71b616743580eabcaa0d8 | [
"MIT"
] | 2 | 2021-12-02T01:31:20.000Z | 2021-12-09T17:32:02.000Z | Soruce/ModuleImGui.cpp | ermario/3DEngineApp | 9a6ae32ce3aba5c610c71b616743580eabcaa0d8 | [
"MIT"
] | null | null | null | Soruce/ModuleImGui.cpp | ermario/3DEngineApp | 9a6ae32ce3aba5c610c71b616743580eabcaa0d8 | [
"MIT"
] | null | null | null | #include "Globals.h"
#include "Application.h"
#include "ModuleImGui.h"
#include "ModuleWindow.h"
#include "ModuleProgram.h"
#include "ModuleRender.h"
#include "ModuleCamera.h"
#include "SDL.h"
#include "GL/glew.h"
#include "imgui.h"
#include "imgui_impl_sdl.h"
#include "imgui_impl_opengl3.h"
ModuleImGui::ModuleImGui()
{
}
ModuleImGui::~ModuleImGui()
{
}
// Called before render is available
bool ModuleImGui::Init()
{
EngineLOG("Created context for ImGui")
ImGui::CreateContext();
ImGuiIO& io = ImGui::GetIO(); (void)io;
io.ConfigFlags |= ImGuiConfigFlags_DockingEnable;
ImGui::StyleColorsDark();
ImGui_ImplSDL2_InitForOpenGL(App->window->window, App->renderer->context);
ImGui_ImplOpenGL3_Init(GLSL_VERSION);
ImGui::StyleColorsDark();
about.system = (unsigned char*)SDL_GetPlatform();
about.cpu = SDL_GetCPUCount();
about.ram = SDL_GetSystemRAM() / 1024.0f;
about.gpu = (unsigned char*)glGetString(GL_RENDERER);
about.gpu_vendor = (unsigned char*)glGetString(GL_VENDOR);
glGetIntegerv(GL_GPU_MEMORY_INFO_TOTAL_AVAILABLE_MEMORY_NVX, &about.vram_capacity);
glGetIntegerv(GL_GPU_MEMORY_INFO_CURRENT_AVAILABLE_VIDMEM_NVX, &about.vram_free);
SDL_GetVersion(&about.sdl_version);
return true;
}
update_status ModuleImGui::PreUpdate()
{
ImGui_ImplOpenGL3_NewFrame();
ImGui_ImplSDL2_NewFrame();
ImGui::NewFrame();
Menu();
//if (console_tab)
//debugger->Draw(&console_tab);
if (demo_tab)
ImGui::ShowDemoWindow(&demo_tab);
if (about_tab)
ImGui::ShowAboutWindow(&about_tab);
if (inspector_tab)
InspectorSidebar();
if (exit_popup)
{
bool exit = ExitPopup();
if(exit)
{
return UPDATE_STOP;
}
}
return UPDATE_CONTINUE;
}
// Called every draw update
update_status ModuleImGui::Update()
{
ImGui::Render();
ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());
return UPDATE_CONTINUE;
}
// Called before quitting
bool ModuleImGui::CleanUp()
{
ImGui_ImplOpenGL3_Shutdown();
ImGui_ImplSDL2_Shutdown();
ImGui::DestroyContext();
return true;
}
void ModuleImGui::Menu() {
if (ImGui::BeginMainMenuBar()) {
if (ImGui::BeginMenu("File")) {
ImGui::MenuItem("Save");
ImGui::MenuItem("Load");
if (ImGui::MenuItem("Quit"))
exit_popup = true;
ImGui::EndMenu();
}
if (ImGui::BeginMenu("Edit")) {
if (ImGui::MenuItem("Do")) {}
if (ImGui::MenuItem("Undo")) {}
ImGui::EndMenu();
}
if (ImGui::BeginMenu("Options")) {
ImGui::EndMenu();
}
if (ImGui::BeginMenu("Tools")) {
ImGui::MenuItem("Inspector", NULL, &inspector_tab);
ImGui::MenuItem("Console", NULL, &console_tab);
ImGui::MenuItem("Imgui Demo", NULL, &demo_tab);
ImGui::EndMenu();
}
if (ImGui::BeginMenu("Build")) {
ImGui::EndMenu();
}
if (ImGui::BeginMenu("Windows")) {
ImGui::EndMenu();
}
if (ImGui::BeginMenu("Help")) {
if (ImGui::MenuItem("GitHub")) {
BROWSER("https://github.com/ermario");
}
ImGui::MenuItem("About ImGui", NULL, &about_tab);
ImGui::EndMenu();
}
ImGui::EndMainMenuBar();
}
}
void ModuleImGui::InspectorSidebar() {
ImGuiWindowFlags window_flags = 0;
//window_flags |= ImGuiWindowFlags_MenuBar;
//window_flags |= ImGuiWindowFlags_NoMove;
//window_flags |= ImGuiWindowFlags_NoResize;
ImGui::Begin("Inspector", NULL, window_flags);
if (ImGui::CollapsingHeader("Camera"))
App->camera->ImGuiCamera();
if (ImGui::CollapsingHeader("About system"))
About();
ImGui::End();
}
void ModuleImGui::Performance() {
}
void ModuleImGui::About() {
static SDL_version version;
static const float vram_total = about.vram_capacity / 1024.0f;
glGetIntegerv(GL_GPU_MEMORY_INFO_CURRENT_AVAILABLE_VIDMEM_NVX, &about.vram_free);
float vram_free = about.vram_free / 1024.0f;
float vram_usage = vram_total - vram_free;
ImGui::Separator();
ImGui::Text("System: %s", about.system);
ImGui::Text("SDL Version: %d.%d.%d", about.sdl_version.major,
about.sdl_version.minor, about.sdl_version.patch);
ImGui::Separator();
ImGui::Text("CPUs: %d", about.cpu);
ImGui::Text("System RAM: %.1f Gb", about.ram);
ImGui::Separator();
ImGui::Text("GPU: %s", about.gpu);
ImGui::Text("Vendor: %s", about.gpu_vendor);
ImGui::Text("VRAM: %.1f Mb", vram_total);
ImGui::Text("Vram Usage: %.1f Mb", vram_usage);
ImGui::Text("Vram Available: %.1f Mb", vram_free);
}
bool ModuleImGui::ExitPopup()
{
bool exit = false;
ImGui::OpenPopup("Exit?");
// Always center this window when appearing
ImVec2 center = ImGui::GetMainViewport()->GetCenter();
ImGui::SetNextWindowPos(center, ImGuiCond_Appearing, ImVec2(0.5f, 0.5f));
if (ImGui::BeginPopupModal("Exit?", NULL, ImGuiWindowFlags_AlwaysAutoResize))
{
ImGui::Text("You are about to exit the Engine.\nUnsaved work will be lost!\n\n");
ImGui::Separator();
static bool dont_ask_me_next_time = false;
ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0, 0));
ImGui::Checkbox("Don't ask me next time", &dont_ask_me_next_time);
ImGui::PopStyleVar();
if (ImGui::Button("OK", ImVec2(120, 0)))
{
ImGui::CloseCurrentPopup();
exit_popup = false;
exit = true;
}
ImGui::SetItemDefaultFocus();
ImGui::SameLine();
if (ImGui::Button("Cancel", ImVec2(120, 0)))
{
ImGui::CloseCurrentPopup();
exit_popup = false;
}
ImGui::EndPopup();
}
return exit;
}
| 22.886957 | 84 | 0.698708 | [
"render"
] |
09bd34b76fad2c654cafa48bb2e0671080edf8ec | 5,621 | cpp | C++ | r3d/load/load_texture.cpp | ryanw3bb/r3d | 73920cd11a623d1eeb73855be5ca1be7dc4679cb | [
"MIT"
] | 3 | 2018-06-20T08:28:01.000Z | 2021-08-02T13:45:07.000Z | r3d/load/load_texture.cpp | ryanw3bb/r3d | 73920cd11a623d1eeb73855be5ca1be7dc4679cb | [
"MIT"
] | null | null | null | r3d/load/load_texture.cpp | ryanw3bb/r3d | 73920cd11a623d1eeb73855be5ca1be7dc4679cb | [
"MIT"
] | 1 | 2018-06-11T15:28:48.000Z | 2018-06-11T15:28:48.000Z | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include "load_texture.hpp"
#include "../util/file.hpp"
#define STB_IMAGE_IMPLEMENTATION
#include "../lib/stb_image.h"
GLuint r3d::load_texture(std::string image_path)
{
image_path.insert(0, get_running_dir());
printf("Reading image %s\n", image_path.c_str());
int width, height, bpp;
unsigned char* rgb_image = stbi_load(image_path.c_str(), &width, &height, &bpp, STBI_rgb);
// Create one OpenGL texture
GLuint textureID;
glGenTextures(1, &textureID);
// "Bind" the newly created texture : all future texture functions will modify this texture
glBindTexture(GL_TEXTURE_2D, textureID);
// Give the image to OpenGL
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, rgb_image);
// OpenGL has now copied the data. Free our own version
stbi_image_free(rgb_image);
// trilinear filtering
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
// which requires mipmaps. Generate them automatically.
glGenerateMipmap(GL_TEXTURE_2D);
return textureID;
}
GLuint r3d::load_cubemap(std::vector<std::string> faces)
{
unsigned int textureID;
glGenTextures(1, &textureID);
glBindTexture(GL_TEXTURE_CUBE_MAP, textureID);
int width, height, bpp;
for(unsigned int i = 0; i < faces.size(); i++)
{
// use full directory
faces[i].insert(0, get_running_dir());
unsigned char* image = stbi_load(faces[i].c_str(), &width, &height, &bpp, 0);
if(image)
{
glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i,
0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, image);
stbi_image_free(image);
}
else
{
printf("Cubemap texture failed to load: %s\n", faces[i].c_str());
stbi_image_free(image);
}
}
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
return textureID;
}
#define FOURCC_DXT1 0x31545844 // Equivalent to "DXT1" in ASCII
#define FOURCC_DXT3 0x33545844 // Equivalent to "DXT3" in ASCII
#define FOURCC_DXT5 0x35545844 // Equivalent to "DXT5" in ASCII
GLuint r3d::load_dds(std::string image_path)
{
image_path.insert(0, get_running_dir());
unsigned char header[124];
FILE* fp;
/* try to open the file */
fp = fopen(image_path.c_str(), "rb");
if(fp == NULL)
{
printf("%s could not be opened.\n", image_path.c_str());
getchar();
return 0;
}
/* verify the type of file */
char filecode[4];
fread(filecode, 1, 4, fp);
if(strncmp(filecode, "DDS ", 4) != 0)
{
fclose(fp);
return 0;
}
/* get the surface desc */
fread(&header, 124, 1, fp);
unsigned int height = *(unsigned int*) &(header[8]);
unsigned int width = *(unsigned int*) &(header[12]);
unsigned int linearSize = *(unsigned int*) &(header[16]);
unsigned int mipMapCount = *(unsigned int*) &(header[24]);
unsigned int fourCC = *(unsigned int*) &(header[80]);
unsigned char* buffer;
unsigned int bufsize;
/* how big is it going to be including all mipmaps? */
bufsize = mipMapCount > 1 ? linearSize * 2 : linearSize;
buffer = (unsigned char*) malloc(bufsize * sizeof(unsigned char));
fread(buffer, 1, bufsize, fp);
/* close the file pointer */
fclose(fp);
unsigned int components = (fourCC == FOURCC_DXT1) ? 3 : 4;
unsigned int format;
switch(fourCC)
{
case FOURCC_DXT1:
format = GL_COMPRESSED_RGBA_S3TC_DXT1_EXT;
break;
case FOURCC_DXT3:
format = GL_COMPRESSED_RGBA_S3TC_DXT3_EXT;
break;
case FOURCC_DXT5:
format = GL_COMPRESSED_RGBA_S3TC_DXT5_EXT;
break;
default:
free(buffer);
return 0;
}
// Create one OpenGL texture
GLuint texture_id;
glGenTextures(1, &texture_id);
// "Bind" the newly created texture : all future texture functions will modify this texture
glBindTexture(GL_TEXTURE_2D, texture_id);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
// anisotropic filtering
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, 2);
unsigned int blockSize = (format == GL_COMPRESSED_RGBA_S3TC_DXT1_EXT) ? 8 : 16;
unsigned int offset = 0;
/* load the mipmaps */
for(unsigned int level = 0; level < mipMapCount && (width || height); ++level)
{
unsigned int size = ((width + 3) / 4) * ((height + 3) / 4) * blockSize;
glCompressedTexImage2D(GL_TEXTURE_2D, level, format, width, height, 0, size, buffer + offset);
offset += size;
width /= 2;
height /= 2;
// Deal with Non-Power-Of-Two textures. This code is not included in the webpage to reduce clutter.
if(width < 1)
{ width = 1; }
if(height < 1)
{ height = 1; }
}
free(buffer);
return texture_id;
} | 30.383784 | 107 | 0.649173 | [
"vector"
] |
09c0123207b4737001e5921ddd68491caaea39aa | 6,344 | cpp | C++ | project_code/GALabs/src/ofApp.cpp | nykwil/devart-template | 6d9ab9757fbb6cfd36354090d1821184989a5d1b | [
"Apache-2.0"
] | null | null | null | project_code/GALabs/src/ofApp.cpp | nykwil/devart-template | 6d9ab9757fbb6cfd36354090d1821184989a5d1b | [
"Apache-2.0"
] | null | null | null | project_code/GALabs/src/ofApp.cpp | nykwil/devart-template | 6d9ab9757fbb6cfd36354090d1821184989a5d1b | [
"Apache-2.0"
] | null | null | null | #include "ofApp.h"
#include "ofxSimpleGuiToo.h"
#include "TestProblem.h"
#include "rbMath.h"
//#include "ofxFatLine.h"
#include "ofEasyCam.h"
#include "LineStrip.h"
#include "ColorLook.h"
// @TODO clear button
static ofEasyCam mCam;
static bool bRun = false;
static bool bDebug = false;
static bool bDrawAll = true;
static ofImage imgComp;
static ofImage imgWork;
static ofImage imgFinal;
static int width;
static int height;
static ofPixels pixResult;
static ofImage baseImage;
static bool terrible = false;
static LineStrip strip;
static int mWeiStart = 10;
static float mWeiScale = 10.f;
static float mWeiDist = 1.f;
static float mWeiEnd = 0.1f;
static string rootDir;
static string algorithm;
//--------------------------------------------------------------
void ofApp::update(){
}
//--------------------------------------------------------------
void ofApp::keyReleased(int key){
}
//--------------------------------------------------------------
void ofApp::mouseMoved(int x, int y ){
}
//--------------------------------------------------------------
void ofApp::mouseDragged(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mousePressed(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mouseReleased(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::windowResized(int w, int h){
}
//--------------------------------------------------------------
void ofApp::gotMessage(ofMessage msg){
}
//--------------------------------------------------------------
void ofApp::dragEvent(ofDragInfo dragInfo){
}
ofApp::ofApp(const std::vector<std::string>& args)
{
algorithm = args.size() > 1 ? args[1] : "";
rootDir = args.size() > 2 ? args[2] : "cats";
}
void ofApp::setup() {
gui.addToggle("Run", bRun);
gui.addToggle("Debug", bDebug);
gui.addToggle("DrawAll", bDrawAll);
ofSetFrameRate(30);
if (terrible) {
gui.addToggle("DrawMesh", strip.bDrawMesh);
gui.addToggle("DrawWire", strip.bDrawWire);
gui.addToggle("DrawLine", strip.bDrawLine);
gui.addToggle("DrawNormal", strip.bDrawNormal);
gui.addToggle("DrawTangeant", strip.bDrawTangeant);
gui.addToggle("DrawPoints", strip.bDrawPoints);
gui.addToggle("DrawOutline", strip.bDrawOutline);
gui.addToggle("DrawLinePoints", strip.bDrawLinePoints);
gui.addToggle("DrawOrigLine", strip.bDrawOrigLine);
gui.addSlider("DefaultWidth", strip.mDefaultWidth, 1.f, 100.f);
gui.addSlider("SmoothingSize", strip.mSmoothingSize, 0.f, 1.f);
gui.addSlider("Spacing", strip.mSpacing, 0, 100.f);
gui.addSlider("SmoothingShape", strip.mSmoothingShape, 0.f, 1.f);
gui.addSlider("OutSmoothingSize", strip.mOutSmoothingSize, 0.f, 1.f);
gui.addSlider("OutSpacing", strip.mOutSpacing, 0, 100.f);
gui.addSlider("AngStep", strip.mAngStep, 0.01f, TWO_PI);
gui.addSlider("WeiNum", mWeiStart, 3, 30);
gui.addSlider("WeiScale", mWeiScale, 0.f, 100.f);
gui.addSlider("WeiAdd", mWeiDist, 0.f, 2.f);
gui.addSlider("WeiNoise ", mWeiEnd , 0.001f, 2.f);
strip.addVertex(ofVec3f(100, 500, 0));
strip.addVertex(ofVec3f(300, 100, 0));
strip.addVertex(ofVec3f(600, 400, 0));
strip.addVertex(ofVec3f(800, 150, 0));
}
else {
if (algorithm == "collage") {
mDna = new CollageProblem();
}
else if (algorithm == "strip") {
mDna = new StripProblem();
}
else {
mDna = new StrokeProblem();
}
}
gui.setup();
gui.loadFromXML();
gui.setDefaultKeys(true);
gui.setDraw(true);
if (!terrible) {
mDna->mRootDir = ofToDataPath(rootDir);
mDna->setup();
width = mDna->mWorkingWidth;
height = mDna->mWorkingHeight;
ofSetWindowShape(width * 2, height * 2);
}
}
void ofApp::draw() {
ofBackground(0);
if (false) {
ofFbo mFbo;
ofFbo::Settings sett;
sett.width = width;
sett.height = height;
mFbo.allocate(sett);
mFbo.begin();
ofEnableBlendMode(OF_BLENDMODE_ALPHA);
ofSetColor(255, 0, 255, 255);
ofRect(10, 10, 800, 800);
ofSetColor(0,250, 255, 100);
ofRect(10, 10, 100, 100);
ofSetColor(0, 250, 255, 1);
ofRect(110, 110, 100, 100);
// end draw
mFbo.end();
mFbo.readToPixels(pixResult);
baseImage.setFromPixels(pixResult);
baseImage.draw(0,0);
}
else if (terrible) {
mCam.begin();
ofEnableDepthTest();
strip.draw();
mCam.end();
}
else {
if (bRun && !mDna->isThreadRunning()) {
mDna->go();
if (bDrawAll) {
mDna->getCompImg(imgComp);
if (imgComp.getWidth() > 0) {
ofDisableBlendMode();
ofSetColor(255, 255, 255 ,255);
imgComp.draw(0, 0, width, height);
ofDrawBitmapString("Comp", 0, 10);
}
mDna->getWorkImg(imgWork);
if (imgWork.getWidth() > 0) {
ofEnableBlendMode(OF_BLENDMODE_DISABLED);
ofSetColor(255);
imgWork.draw(width, 0, width, height);
ofDrawBitmapString("Work", width, 10);
}
ofEnableBlendMode(OF_BLENDMODE_DISABLED);
ofSetColor(255);
mDna->mImgOrig.draw(0, height, width, height + 10);
ofDrawBitmapString("Orig", 0, height);
mDna->getFinalImg(imgFinal);
if (imgFinal.getWidth() > 0) {
ofEnableBlendMode(OF_BLENDMODE_DISABLED);
ofSetColor(255);
imgFinal.draw(width, height, width, height);
ofDrawBitmapString("Final", width, height + 10);
}
}
else {
mDna->getFinalImg(imgFinal);
if (imgFinal.getWidth() > 0) {
ofEnableBlendMode(OF_BLENDMODE_DISABLED);
ofSetColor(255);
imgFinal.draw(0, 0, mDna->mFinalWidth, mDna->mFinalHeight);
}
}
}
else if (bDebug) {
ofBackground(50);
mDna->debugDraw();
}
}
gui.draw();
}
void ofApp::keyPressed(int key) {
if (key == 'u') {
bRun = !bRun;
}
else if (key == 'd') {
bDebug = !bDebug;
}
else if (key == 's') {
ofSaveImage(pixResult, "output.png", OF_IMAGE_QUALITY_BEST);
// mDna->startThread(true, false);
}
else if (key == 'p') {
strip.clear();
for (int i = 0; i < 5; ++i) {
strip.addVertex(ofVec3f(ofRandom(50, 800), ofRandom(50, 800), 0));
}
}
else if (key == 'o') {
strip.mWeight.clear();
float f = ofRandom(1.f);
for (int i = 0; i < mWeiStart; ++i) {
strip.mWeight.push_back((mWeiDist + ofRandom(1.f)) * mWeiScale);
}
}
else if (key == 'i') {
mCam.setVFlip(!mCam.isVFlipped());
}
}
void ofApp::exit()
{
// mDna->waitForThread(true);
}
| 23.496296 | 71 | 0.598834 | [
"vector"
] |
09c1bfceffa78fec699bf0b3d730e020fe2d4ee5 | 5,391 | cpp | C++ | Blue-Flame-Engine/Sandbox/Sandbox/Hello_Triangle.cpp | FantasyVII/Blue-Flame-Engine | b0e44ccffdd41539fa9075e5d6a2b3c1cc811d96 | [
"MIT"
] | 2 | 2020-10-12T13:40:05.000Z | 2021-09-17T08:37:03.000Z | Blue-Flame-Engine/Sandbox/Sandbox/Hello_Triangle.cpp | FantasyVII/Blue-Flame-Engine | b0e44ccffdd41539fa9075e5d6a2b3c1cc811d96 | [
"MIT"
] | null | null | null | Blue-Flame-Engine/Sandbox/Sandbox/Hello_Triangle.cpp | FantasyVII/Blue-Flame-Engine | b0e44ccffdd41539fa9075e5d6a2b3c1cc811d96 | [
"MIT"
] | null | null | null | #include "Hello_Triangle.h"
namespace Hello_Triangle
{
using namespace BF;
using namespace BF::AI;
using namespace BF::Application;
using namespace BF::Graphics;
using namespace BF::Graphics::API;
using namespace BF::Graphics::Renderers;
using namespace BF::Graphics::Materials;
using namespace BF::ECS;
using namespace BF::Math;
using namespace BF::System;
using namespace BF::Scripting;
Hello_Triangle::Hello_Triangle()
{
}
Hello_Triangle::~Hello_Triangle()
{
}
void Hello_Triangle::Initialize()
{
scene = new Scene(*this);
BF::Input::Mouse::ShowMouseCursor(true);
BF::Engine::GetContext().EnableDepthBuffer(true);
BF::Engine::GetContext().EnableVsync(false);
//BF::Engine::LimitFrameRate(60.0f);
BF::Engine::GetContext().SetPrimitiveType(PrimitiveType::TriangleList);
BF::Engine::GetContext().SetWindingOrder(WindingOrder::Clockwise);
BF::Engine::GetContext().CullFace(CullingType::Back);
//camera.Initialize(Matrix4::Orthographic(-((int)Engine::GetWindow().GetClientWidth() / 2), (int)(Engine::GetWindow().GetClientWidth() / 2), ((int)Engine::GetWindow().GetClientHeight() / 2), -(int)(Engine::GetWindow().GetClientHeight() / 2), -1.0f, 1.0f));
App::Initialize();
GameObject* cameraGameObject = scene->AddGameObject(new GameObject("Camera"));
Camera* camera = (Camera*)cameraGameObject->AddComponent(new Camera(Matrix4::Orthographic(-5, 5, 5, -5, -10.0f, 10.0f)));
camera->gameObject->GetTransform()->SetPosition(Vector3f(0, 0, -1));
camera->SetClearType(BufferClearType::ColorAndDepth);
camera->SetClearColor(Color(0.5, 0.0f, 0.0f, 1.0f));
//-------------------------------------------------------- 3D Model --------------------------------------------------------
Model* model = new Model();
//------------------------------------ Materials ------------------------------------------
BF::Graphics::API::Shader* shader = new Shader();
shader->LoadStandardShader(BF::Graphics::API::ShaderType::P);
MeshMaterialColorBuffer meshAMaterialColorBuffer;
meshAMaterialColorBuffer.ambientColor = Color(0.0f, 0.0f, 1.0f, 1.0f);
meshAMaterialColorBuffer.diffuseColor = Color(0.0f, 0.0f, 1.0f, 1.0f);
meshAMaterialColorBuffer.specularColor = Color(0.0f, 0.0f, 1.0f, 1.0f);
meshAMaterialColorBuffer.shininess = 256;
model->AddMaterial(MeshMaterial(shader, meshAMaterialColorBuffer));
MeshMaterialColorBuffer meshBMaterialColorBuffer;
meshBMaterialColorBuffer.ambientColor = Color(1.0f, 0.0f, 0.0f, 1.0f);
meshBMaterialColorBuffer.diffuseColor = Color(1.0f, 0.0f, 0.0f, 1.0f);
meshBMaterialColorBuffer.specularColor = Color(1.0f, 0.0f, 0.0f, 1.0f);
meshBMaterialColorBuffer.shininess = 256;
model->AddMaterial(MeshMaterial(shader, meshBMaterialColorBuffer));
//------------------------------------ Materials ------------------------------------------
//------------------------------------ Mesh A ------------------------------------------
std::vector<BF::Graphics::MeshData::PVertexData>* meshAVertices = new std::vector<BF::Graphics::MeshData::PVertexData>();
std::vector<unsigned int>* meshAIndices = new std::vector<unsigned int>();
meshAVertices->emplace_back(BF::Graphics::MeshData::PVertexData(Vector3f(-0.5, 0.5, 0)));
meshAVertices->emplace_back(BF::Graphics::MeshData::PVertexData(Vector3f(0.5, 0.5, 0)));
meshAVertices->emplace_back(BF::Graphics::MeshData::PVertexData(Vector3f(0.5, -0.5, 0)));
meshAIndices->emplace_back(0);
meshAIndices->emplace_back(1);
meshAIndices->emplace_back(2);
MeshData* meshAData = new MeshData(meshAVertices, meshAIndices, 0, BF::Graphics::MeshData::VertexStructVersion::P);
//------------------------------------ Mesh A ------------------------------------------
//------------------------------------ Mesh B ------------------------------------------
std::vector <BF::Graphics::MeshData::PVertexData>* meshBVertices = new std::vector<BF::Graphics::MeshData::PVertexData>();
std::vector<unsigned int>* meshBIndices = new std::vector<unsigned int>();
meshBVertices->emplace_back(BF::Graphics::MeshData::PVertexData(Vector3f(0.5, -0.5, 0)));
meshBVertices->emplace_back(BF::Graphics::MeshData::PVertexData(Vector3f(-0.5, -0.5, 0)));
meshBVertices->emplace_back(BF::Graphics::MeshData::PVertexData(Vector3f(-0.5, 0.5, 0)));
meshBIndices->emplace_back(0);
meshBIndices->emplace_back(1);
meshBIndices->emplace_back(2);
MeshData* meshBData = new MeshData(meshBVertices, meshBIndices, 1, BF::Graphics::MeshData::VertexStructVersion::P);
//------------------------------------ Mesh B ------------------------------------------
model->AddMesh(Mesh(meshAData));
model->AddMesh(Mesh(meshBData));
//-------------------------------------------------------- 3D Model --------------------------------------------------------
GameObject* planeGameObject = scene->AddGameObject(new GameObject("Plane"));
planeModel = (Model*)planeGameObject->AddComponent(model);
planeModel->gameObject->GetTransform()->SetPosition(Vector3f(0, -1, 5));
planeModel->gameObject->GetTransform()->SetScale(Vector3f(3, 3, 3));
}
void Hello_Triangle::Load()
{
App::Load();
}
void Hello_Triangle::PostLoad()
{
App::PostLoad();
App::RunScene(*scene);
}
void Hello_Triangle::Update(double deltaTime)
{
App::Update(deltaTime);
}
void Hello_Triangle::Render()
{
position.y += 0.0001f;
App::Render();
}
} | 39.350365 | 258 | 0.629939 | [
"mesh",
"render",
"vector",
"model",
"3d"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.