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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
a06b9c5f4ced36f2560b40b3877df7668a4b95c2 | 17,190 | cpp | C++ | src/cppspice.cpp | skrimpon/cpp_spice | fc7e3d418df7ae95799f48201bd3f1a11002a363 | [
"MIT"
] | null | null | null | src/cppspice.cpp | skrimpon/cpp_spice | fc7e3d418df7ae95799f48201bd3f1a11002a363 | [
"MIT"
] | null | null | null | src/cppspice.cpp | skrimpon/cpp_spice | fc7e3d418df7ae95799f48201bd3f1a11002a363 | [
"MIT"
] | null | null | null | /*
* Panagiotis Skrimponis
*/
#include "cs_dc_sweep.h"
#include "cs_ac_sweep.h"
#include "cs_component.h"
#include "cs_transient.h"
#include "cs_headerdef.h"
int main(int argc, char * argv[])
{
std::ifstream iFile;
std::ofstream oFile;
std::stringstream iLine;
std::string token, line, component_name, component_plus_node, component_minus_node, analysis_sweep;
std::vector < std::unique_ptr<Component> > ComponentVector;
std::vector <TransientComponent> TransientComponentVector;
std::vector <ACComponent> ACComponentVector;
std::vector < std::unique_ptr<DCSweepAnalysis>> DCSweepAnalysisVector;
std::vector < std::unique_ptr<ACSweepAnalysis>> ACSweepAnalysisVector;
std::vector < std::unique_ptr<TransientAnalysis>> TransientAnalysisVector;
std::unordered_map < std::string, int > nodeHash, ctrlHash, componentHash;
std::unordered_map < int, std::string > nodeHash_reverse;
std::size_t last, found;
char component_type;
unsigned int i=0, j=0, k=0, nodeID=1, componentID=0, component_branch=0, branchID=0, nonZero=0, vectorSize=0, tranZero=0;
bool spd=false, iter=false, sparse=false, method=false, ac=false;
double analysis_start=0.0, analysis_stop=0.0, analysis_step=0.0, component_value=0.0, component_mag=0.0, component_phase=0.0, itol = 1e-3, g=0.0;
// Initialize Hash-Tables
nodeHash["0"] = nodeHash["GND"] = -1;
ctrlHash[".DC"] = DC;
ctrlHash[".AC"] = AC;
ctrlHash[".TRAN"] = TRAN;
ctrlHash[".OPTIONS"] = OPTIONS;
ctrlHash[".PLOT"] = PLOT;
ctrlHash[".PRINT"] = PRINT;
ctrlHash["SPD"] = SPD;
ctrlHash["ITER"] = ITER;
ctrlHash["SPARSE"] = SPARSE;
ctrlHash["METHOD"] = METHOD;
ctrlHash["ITOL"] = ITOL;
// Check if there are enough arguments
if (argc != 2)
{
std::cout << "\033[1;31mERROR: not enough arguments\033[0m\n";
return -1;
}
// Check if you can open the input file
iFile.open(argv[1]);
if (!iFile.is_open())
{
std::cout << "\033[1;31mERROR: cannot open the file\033[0m" << argv[1] << "for reading\n";
return -1;
}
iFile >> token;
str_toupper(token)
do {
switch(token[0])
{
case('V'):
case('I'):
case('R'):
case('C'):
case('L'):
component_type = token[0];
component_name = token;
iFile >> component_plus_node >> component_minus_node;
str_toupper(component_plus_node)
str_toupper(component_minus_node)
componentHash[component_name] = componentID++;
if (!nodeHash[component_plus_node])
{
nodeHash[component_plus_node] = nodeID;
nodeHash_reverse[nodeID++] = component_plus_node;
}
if (!nodeHash[component_minus_node])
{
nodeHash[component_minus_node] = nodeID;
nodeHash_reverse[nodeID++] = component_minus_node;
}
if(token[0]=='R')
{
nonZero += (((nodeHash[component_plus_node] != -1) & (nodeHash[component_minus_node] != -1)) << 1) + (nodeHash[component_plus_node] != -1) + (nodeHash[component_minus_node] != -1);
}
else if ((token[0]=='V') || (token[0]=='L'))
{
nonZero += ((nodeHash[component_plus_node] != -1) << 1) + ((nodeHash[component_minus_node] != -1) << 1);
component_branch = branchID++;
tranZero += (token[0]=='L');
}
else if (token[0]=='C')
{
tranZero += (((nodeHash[component_plus_node] != -1) & (nodeHash[component_minus_node] != -1)) << 1) + (nodeHash[component_plus_node] != -1) + (nodeHash[component_minus_node] != -1);
}
getline(iFile, token);
break;
case('.'):
switch(ctrlHash[token])
{
case(DC): // Create a new DC Anaylsis
iFile >> token >> analysis_start >> analysis_stop >> analysis_step;
str_toupper(token)
component_type = token[0];
component_name = token;
DCSweepAnalysisVector.push_back(std::unique_ptr<DCSweepAnalysis> (new DCSweepAnalysis(component_type, component_name, analysis_start, analysis_step, analysis_stop)));
break;
case(AC): // Create a new AC Anaylsis
iFile >> analysis_sweep >> analysis_step >> analysis_start >> analysis_stop;
ACSweepAnalysisVector.push_back(std::unique_ptr <ACSweepAnalysis> (new ACSweepAnalysis(analysis_sweep, analysis_start, analysis_step, analysis_stop)));
break;
case(TRAN): // Create a new Transient Anaylsis
iFile >> analysis_step >> analysis_stop;
TransientAnalysisVector.push_back(std::unique_ptr <TransientAnalysis> (new TransientAnalysis(analysis_step, analysis_stop)));
break;
case(OPTIONS):
iFile.seekg(- token.size(), iFile.cur);
read_line()
iLine.str(token); iLine.clear();
while(!iLine.eof())
{
iLine >> token;
if(ctrlHash[token] == SPD) spd = true;
else if(ctrlHash[token] == SPARSE) sparse = true;
else if(ctrlHash[token] == ITER) iter = true;
else if(ctrlHash[token] == ITOL) iLine >> itol;
else if(ctrlHash[token] == METHOD) { iLine >> token; method = (token == "BE"); }
}
break;
case(PRINT):
case(PLOT):
iFile >> token;
switch(token[0])
{
case('D'):
if (DCSweepAnalysisVector.size() == 0) break;
read_line();
iLine.str(token); iLine.clear();
do {
iLine >> token >> component_name;
DCSweepAnalysisVector[DCSweepAnalysisVector.size()-1]->add_node(component_name);
} while(!iLine.eof());
break;
case('T'):
if (TransientAnalysisVector.size() == 0) break;
read_line();
iLine.str(token); iLine.clear();
do {
iLine >> token >> component_name;
TransientAnalysisVector[TransientAnalysisVector.size()-1]->add_node(component_name);
} while(!iLine.eof());
break;
case('A'):
if (ACSweepAnalysisVector.size() == 0) break;
read_line();
iLine.str(token); iLine.clear();
do {
iLine >> token >> component_name;
ACSweepAnalysisVector[ACSweepAnalysisVector.size()-1]->add_node(component_name);
} while(!iLine.eof());
break;
default:
read_line();
iLine.str(token); iLine.clear();
do {
iLine >> token >> component_name;
if ( DCSweepAnalysisVector.size() != 0) DCSweepAnalysisVector[DCSweepAnalysisVector.size()-1]->add_node(component_name);
if (TransientAnalysisVector.size() != 0) TransientAnalysisVector[TransientAnalysisVector.size()-1]->add_node(component_name);
if ( ACSweepAnalysisVector.size() != 0) ACSweepAnalysisVector[ACSweepAnalysisVector.size()-1]->add_node(component_name);
} while(!iLine.eof());
break;
}
break;
}
break;
default: getline(iFile, token);
}
iFile >> token;
str_toupper(token)
} while(!iFile.eof());
iFile.clear();
iFile.seekg(0, iFile.beg);
nodeHash["0"] = nodeHash["GND"] = 0;
nodeHash_reverse[0] = "0";
vectorSize = nodeID + branchID;
if(sparse)
{
int idx=0, tdx=0;
double * CS_b,* CS_x;
CS_b = new double[vectorSize-1]; for(i = 0; i < (vectorSize - 1); ++i) CS_b[i] = 0.0;
CS_x = new double[vectorSize-1]; for(i = 0; i < (vectorSize - 1); ++i) CS_x[i] = 0.0;
std::complex<double>* MNA_AC_b = new std::complex<double>[vectorSize];
SparseMatrix<double> CS_A("Sparse MNA DC Matrix", nodeID, branchID, nonZero);
SparseMatrix<double> CS_C("Sparse MNA Transient Matrix", nodeID, branchID, tranZero);
branchID = 0;
iFile >> token;
str_toupper(token)
while (!iFile.eof())
{
switch (token[0])
{
case('V'):
case('I'):
case('R'):
case('C'):
case('L'):
component_type = token[0];
component_name = token.substr(1);
read_line()
ac = ((found = token.find(" AC ")) != std::string::npos);
iLine.str(token.substr(0, found)); iLine.clear();
iLine >> component_plus_node >> component_minus_node >> component_value;
str_toupper(component_plus_node)
str_toupper(component_minus_node)
if(ac)
{
iLine.str(token.substr(found, std::string::npos));
iLine >> token >> component_mag >> component_phase;
ACComponentVector.push_back(ACComponent(component_type, component_name, component_value, component_mag, component_phase, nodeHash[component_plus_node], nodeHash[component_minus_node], branchID));
}
i = nodeHash[component_plus_node] - 1;
j = nodeHash[component_minus_node] - 1;
if (!iLine.eof())
{
TransientComponentVector.push_back(TransientComponent(component_type, component_name, iLine, component_value, nodeHash[component_plus_node], nodeHash[component_minus_node], branchID));
}
switch (component_type)
{
case('V'):
ComponentVector.push_back(std::unique_ptr <Component> (new Component(component_type, component_name, nodeHash[component_plus_node], nodeHash[component_minus_node], component_value)));
k = (branchID + nodeID - 1);
ComponentVector[ComponentVector.size()-1]->set_branch(branchID++);
CS_b[k] += component_value;
if((i != -1) && (j != -1))
{
CS_A(idx++, k, i, 1);
CS_A(idx++, i, k, 1);
CS_A(idx++, k, j, -1);
CS_A(idx++, j, k, -1);
}
else if(i != -1)
{
CS_A(idx++, k, i, 1);
CS_A(idx++, i, k, 1);
}
else if(j != -1)
{
CS_A(idx++, k, j, -1);
CS_A(idx++, j, k, -1);
}
break;
case('I'):
ComponentVector.push_back(std::unique_ptr <Component> (new Component(component_type, component_name, nodeHash[component_plus_node], nodeHash[component_minus_node], component_value)));
if (i != -1) CS_b[i] -= component_value;
if (j != -1) CS_b[j] += component_value;
break;
case('R'):
g = (double) 1.0/component_value;
if((i != -1) && (j != -1))
{
CS_A(idx++, j, j, g);
CS_A(idx++, i, i, g);
CS_A(idx++, i, j, -g);
CS_A(idx++, j, i, -g);
}
else if(i != -1)
{
CS_A(idx++, i, i, g);
}
else if(j != -1)
{
CS_A(idx++, j, j, g);
}
break;
case('C'):
if((i != -1) && (j != -1))
{
CS_C(tdx++, j, j, component_value);
CS_C(tdx++, i, i, component_value);
CS_C(tdx++, i, j, -component_value);
CS_C(tdx++, j, i, -component_value);
}
else if(i != -1)
{
CS_C(tdx++, i, i, component_value);
}
else if(j != -1)
{
CS_C(tdx++, j, j, component_value);
}
break;
case('L'):
k = (branchID + nodeID - 1); branchID++;
if((i != -1) && (j != -1))
{
CS_C(tdx++, k, k, -component_value);
CS_A(idx++, k, i, 1);
CS_A(idx++, i, k, 1);
CS_A(idx++, k, j, -1);
CS_A(idx++, j, k, -1);
}
else if(i != -1)
{
CS_C(tdx++, k, k, -component_value);
CS_A(idx++, k, i, 1);
CS_A(idx++, i, k, 1);
}
else if(j != -1)
{
CS_C(tdx++, k, k, -component_value);
CS_A(idx++, k, j, -1);
CS_A(idx++, j, k, -1);
}
break;
}
break;
default: getline(iFile, token);
}
iFile >> token;
str_toupper(token)
}
CS_A.compressMatrix();
CS_C.compressMatrix();
if(ac)
{
cs_ci * csi_miami = cs_ci_add(cs_i_complex(CS_A.matrix(), true), cs_i_complex(CS_C.matrix(), false), 1.0, 1.0);
ComplexSparseMatrix<std::complex<double>> CS_AC ("MNA AC Matrix", nodeID, branchID, csi_miami);
for(auto &it : ACComponentVector)
{
if (it.type() == 'V')
MNA_AC_b[it.branch() + nodeID] = it.value();
else
{
if(it.plus () != 0)
MNA_AC_b[it.plus ()-1] -= it.value();
if(it.minus () != 0)
MNA_AC_b[it.minus()-1] += it.value();
}
}
for(auto &it : ACSweepAnalysisVector)
{
it->update(nodeHash);
it->sp_analyse(CS_AC, MNA_AC_b, itol, iter, spd, ACComponentVector);
}
}
for(auto &it : TransientAnalysisVector)
{
it->update(nodeHash);
it->sp_analyse(CS_A, CS_C, CS_x, CS_b, itol, iter, spd, method, TransientComponentVector);
}
if(iter)
{
spd ? CS_A.CG(CS_x, CS_b, itol) : CS_A.BiCG(CS_x, CS_b, itol);
}
else
{
spd ? CS_A.Cholesky() : CS_A.LU();
spd ? CS_A.solveSPD(CS_x, CS_b) : CS_A.solve(CS_x, CS_b);
}
oFile.open("DC_Operating_Point_Analysis.txt");
for(i=0;i<(vectorSize-1-branchID);++i) oFile << nodeHash_reverse[i+1] << " " << CS_x[i] << "\n";
oFile.close();
for(auto &it : DCSweepAnalysisVector)
{
it->update(ComponentVector[componentHash[it->name()]]->plus(), ComponentVector[componentHash[it->name()]]->minus(), ComponentVector[componentHash[it->name()]]->branch(), ComponentVector[componentHash[it->name()]]->value(), nodeHash);
it->sp_analyse(CS_A, CS_b, itol, iter, spd);
}
}
else
{
Matrix <std::complex<double>> MNA_AC("MNA AC Matrix", nodeID, branchID);
Matrix <double> MNA_DC ("MNA DC Matrix", nodeID, branchID);
Matrix <double> MNA_TRAN ("MNA Transient Matrix", nodeID, branchID);
double * MNA_b = new double[vectorSize];
double * MNA_x = new double[vectorSize];
std::complex<double>* MNA_AC_b = new std::complex<double>[vectorSize];
for(i = 0; i < vectorSize; ++i) MNA_x[i] = 0.0;
branchID = 0;
iFile >> token;
str_toupper(token)
do {
switch (token[0])
{
case('V'):
case('I'):
case('R'):
case('C'):
case('L'):
component_type = token[0];
component_name = token.substr(1);
read_line()
ac = ((found = token.find(" AC ")) != std::string::npos);
iLine.str(token.substr(0, found)); iLine.clear();
iLine >> component_plus_node >> component_minus_node >> component_value;
str_toupper(component_plus_node)
str_toupper(component_minus_node)
if(ac)
{
iLine.str(token.substr(found, std::string::npos));
iLine >> token >> component_mag >> component_phase;
ACComponentVector.push_back(ACComponent(component_type, component_name, component_value, component_mag, component_phase, nodeHash[component_plus_node], nodeHash[component_minus_node], branchID));
}
ComponentVector.push_back(std::unique_ptr <Component> (new Component(component_type, component_name, nodeHash[component_plus_node], nodeHash[component_minus_node], component_value)));
if (!iLine.eof())
{
TransientComponentVector.push_back(TransientComponent(component_type, component_name, iLine, component_value, nodeHash[component_plus_node], nodeHash[component_minus_node], branchID));
}
if ((component_type=='V') || (component_type=='L'))
{
ComponentVector[ComponentVector.size()-1]->set_branch(branchID++);
}
break;
default: getline(iFile, token);
}
iFile >> token;
str_toupper(token)
} while (!iFile.eof());
for (auto &it : ComponentVector)
{
i = it->plus();
j = it->minus();
component_value = it->value();
switch ( it->type() ) {
case ('R'):
g = (double) 1.0/component_value;
MNA_DC(j, j) += g;
MNA_DC(i, i) += g;
MNA_DC(i, j) -= g;
MNA_DC(j, i) -= g;
break;
case('V'):
k = ( it->branch() + nodeID);
MNA_b[k] += component_value;
MNA_DC(j, k) -= 1;
MNA_DC(k, j) -= 1;
MNA_DC(i, k) += 1;
MNA_DC(k, i) += 1;
break;
case('I'):
MNA_b[j] += component_value;
MNA_b[i] -= component_value;
break;
case('L'):
k = ( it->branch() + nodeID);
MNA_DC(j, k) -= 1;
MNA_DC(k, j) -= 1;
MNA_DC(i, k) += 1;
MNA_DC(k, i) += 1;
MNA_TRAN(k, k) -= component_value;
break;
case('C'):
MNA_TRAN(j, j) += component_value;
MNA_TRAN(i, i) += component_value;
MNA_TRAN(i, j) -= component_value;
MNA_TRAN(j, i) -= component_value;
default: break;
}
}
for(i=1; i < vectorSize; i++)
for(j=1; j < vectorSize; j++)
MNA_AC(i, j) = MNA_DC(i,j) + std::complex<double>(0.0, MNA_TRAN(i,j));
for(auto &it : ACComponentVector)
{
if (it.type() == 'V')
MNA_AC_b[it.branch() + MNA_DC.nodeID()] = it.value();
else
{
MNA_AC_b[it.plus ()] -= it.value();
MNA_AC_b[it.minus()] += it.value();
}
}
for(auto &it : ACSweepAnalysisVector)
{
it->update(nodeHash);
it->analyse(MNA_AC, MNA_AC_b, itol, iter, spd, ACComponentVector);
}
for(auto &it : TransientAnalysisVector)
{
it->update(nodeHash);
it->analyse(MNA_DC, MNA_TRAN, MNA_x, MNA_b, itol, iter, spd, method, TransientComponentVector);
}
if(iter)
{
spd ? MNA_DC.CG(MNA_x, MNA_b, itol) : MNA_DC.BiCG(MNA_x, MNA_b, itol);
}
else
{
spd ? MNA_DC.Cholesky(): MNA_DC.LU();
spd ? MNA_DC.solveSPD(MNA_x, MNA_b) : MNA_DC.solve(MNA_x, MNA_b);
}
oFile.open("DC_Operating_Point_Analysis.txt");
for(i=1 ; i < nodeID; ++i) oFile << nodeHash_reverse[i] << " " << MNA_x[i] << "\n";
oFile.close();
for(auto &it : DCSweepAnalysisVector)
{
it->update(ComponentVector[componentHash[it->name()]]->plus(), ComponentVector[componentHash[it->name()]]->minus(), ComponentVector[componentHash[it->name()]]->branch(), ComponentVector[componentHash[it->name()]]->value(), nodeHash);
it->analyse(MNA_DC, MNA_b, itol, iter, spd);
}
delete [] MNA_b, MNA_x;
}
return 0;
} | 32.680608 | 236 | 0.602269 | [
"vector"
] |
a06bd9d5c7e4a3ca4e9f8c27371fce8fc5132007 | 682 | cc | C++ | third_party/OpenMesh-8.1/Doc/Examples/iterators.cc | hporro/grafica_cpp | 1427bb6e8926b44be474b906e9f52cca77b3df9d | [
"MIT"
] | 216 | 2018-09-09T11:53:56.000Z | 2022-03-19T13:41:35.000Z | third_party/OpenMesh-8.1/Doc/Examples/iterators.cc | hporro/grafica_cpp | 1427bb6e8926b44be474b906e9f52cca77b3df9d | [
"MIT"
] | 13 | 2018-10-23T08:29:09.000Z | 2021-09-08T06:45:34.000Z | third_party/OpenMesh-8.1/Doc/Examples/iterators.cc | hporro/grafica_cpp | 1427bb6e8926b44be474b906e9f52cca77b3df9d | [
"MIT"
] | 41 | 2018-09-13T08:50:41.000Z | 2022-02-23T00:33:54.000Z | MyMesh mesh;
// iterate over all vertices
for (MyMesh::VertexIter v_it=mesh.vertices_begin(); v_it!=mesh.vertices_end(); ++v_it)
...; // do something with *v_it, v_it->, or *v_it
// iterate over all halfedges
for (MyMesh::HalfedgeIter h_it=mesh.halfedges_begin(); h_it!=mesh.halfedges_end(); ++h_it)
...; // do something with *h_it, h_it->, or *h_it
// iterate over all edges
for (MyMesh::EdgeIter e_it=mesh.edges_begin(); e_it!=mesh.edges_end(); ++e_it)
...; // do something with *e_it, e_it->, or *e_it
// iterator over all faces
for (MyMesh::FaceIter f_it=mesh.faces_begin(); f_it!=mesh.faces_end(); ++f_it)
...; // do something with *f_it, f_it->, or *f_it
| 35.894737 | 91 | 0.671554 | [
"mesh"
] |
a06f34ad3f742fb67161aafcfdc0d2f41ca6da67 | 1,262 | cpp | C++ | Solutions/FARIDA.cpp | GouravKhunger/SPOJ | a2a67c20bbd8d26e1c1736d76431b778c319c752 | [
"MIT"
] | 4 | 2020-10-22T17:01:23.000Z | 2020-10-24T16:42:17.000Z | Solutions/FARIDA.cpp | GouravKhunger/SPOJ | a2a67c20bbd8d26e1c1736d76431b778c319c752 | [
"MIT"
] | 8 | 2020-10-23T09:22:03.000Z | 2020-10-31T12:45:22.000Z | Solutions/FARIDA.cpp | GouravKhunger/SPOJ | a2a67c20bbd8d26e1c1736d76431b778c319c752 | [
"MIT"
] | 7 | 2020-10-22T18:03:44.000Z | 2020-10-31T10:47:40.000Z | // https://www.spoj.com/problems/FARIDA/
// FARIDA - Princess Farida
// File Creation Date: 22-Oct-2020
// Author: Lucas Pavanelli (https://github.com/pavalucas)
#include <bits/stdc++.h>
using namespace std;
int main() {
int test;
cin >> test;
for (int t = 1; t <= test; t++) {
int n;
cin >> n;
if (n == 0) {
// if there are no monsters, just return 0
cout << "Case " << t << ": 0"<< '\n';
continue;
}
long long result = 0;
vector<long long> monsters(n);
// dp[i] -> answer using first i monsters
vector<long long> dp(n, 0);
for (int i = 0; i < n; i++) {
cin >> monsters[i];
}
// base case: initiliaze dp with value of the first monster
dp[0] = monsters[0];
result = dp[0];
for (int i = 1; i < n; i++) {
// recursive case:
// maximum between using only monster[i] and the last known answer
dp[i] = max(monsters[i], dp[i-1]);
if (i - 2 >= 0) {
// maximum between using value already stored and dp[i-2] + monsters[i]
dp[i] = max(dp[i], dp[i-2] + monsters[i]);
}
// store in result maximum value for every dp[i]
result = max(dp[i], result);
}
cout << "Case " << t << ": " << result << '\n';
}
return 0;
}
| 26.851064 | 79 | 0.533281 | [
"vector"
] |
a06fbcb6de16d4915b0548a446870b4f5f7eb5ae | 568 | cpp | C++ | C++/0982-Triples-With-Bitwise-AND-Equal-to-Zero/soln-2.cpp | wyaadarsh/LeetCode-Solutions | 3719f5cb059eefd66b83eb8ae990652f4b7fd124 | [
"MIT"
] | 5 | 2020-07-24T17:48:59.000Z | 2020-12-21T05:56:00.000Z | C++/0982-Triples-With-Bitwise-AND-Equal-to-Zero/soln-2.cpp | zhangyaqi1989/LeetCode-Solutions | 2655a1ffc8678ad1de6c24295071308a18c5dc6e | [
"MIT"
] | null | null | null | C++/0982-Triples-With-Bitwise-AND-Equal-to-Zero/soln-2.cpp | zhangyaqi1989/LeetCode-Solutions | 2655a1ffc8678ad1de6c24295071308a18c5dc6e | [
"MIT"
] | 2 | 2020-07-24T17:49:01.000Z | 2020-08-31T19:57:35.000Z | class Solution {
public:
int countTriplets(vector<int>& A) {
vector<int> memo(1 << 16, -1);
int ans = 0;
for(int a : A) {
for(int b : A) {
int ab = a & b;
if (memo[ab] != -1) ans += memo[ab];
else {
int cnt = 0;
for(int c : A) {
if ((ab & c) == 0) ++cnt;
}
memo[ab] = cnt;
ans += cnt;
}
}
}
return ans;
}
};
| 24.695652 | 52 | 0.285211 | [
"vector"
] |
a0770dd93c349d5b3a1acfe6d7cbff0e57410cfa | 17,435 | cpp | C++ | export/windows/cpp/obj/src/flixel/FlxBasic.cpp | TinyPlanetStudios/Project-Crash-Land | 365f196be4212602d32251566f26b53fb70693f6 | [
"MIT"
] | null | null | null | export/windows/cpp/obj/src/flixel/FlxBasic.cpp | TinyPlanetStudios/Project-Crash-Land | 365f196be4212602d32251566f26b53fb70693f6 | [
"MIT"
] | null | null | null | export/windows/cpp/obj/src/flixel/FlxBasic.cpp | TinyPlanetStudios/Project-Crash-Land | 365f196be4212602d32251566f26b53fb70693f6 | [
"MIT"
] | null | null | null | // Generated by Haxe 3.3.0
#include <hxcpp.h>
#ifndef INCLUDED_flixel_FlxBasic
#include <flixel/FlxBasic.h>
#endif
#ifndef INCLUDED_flixel_FlxCamera
#include <flixel/FlxCamera.h>
#endif
#ifndef INCLUDED_flixel_util_FlxPool_flixel_util_LabelValuePair
#include <flixel/util/FlxPool_flixel_util_LabelValuePair.h>
#endif
#ifndef INCLUDED_flixel_util_FlxStringUtil
#include <flixel/util/FlxStringUtil.h>
#endif
#ifndef INCLUDED_flixel_util_IFlxDestroyable
#include <flixel/util/IFlxDestroyable.h>
#endif
#ifndef INCLUDED_flixel_util_IFlxPool
#include <flixel/util/IFlxPool.h>
#endif
#ifndef INCLUDED_flixel_util_LabelValuePair
#include <flixel/util/LabelValuePair.h>
#endif
namespace flixel{
void FlxBasic_obj::__construct(){
HX_STACK_FRAME("flixel.FlxBasic","new",0x9d630540,"flixel.FlxBasic.new","flixel/FlxBasic.hx",10,0xd8d6cfcf)
HX_STACK_THIS(this)
HXLINE( 58) this->flixelType = (int)0;
HXLINE( 43) this->exists = true;
HXLINE( 39) this->alive = true;
HXLINE( 34) this->visible = true;
HXLINE( 30) this->active = true;
HXLINE( 26) this->ID = (int)-1;
}
Dynamic FlxBasic_obj::__CreateEmpty() { return new FlxBasic_obj; }
hx::ObjectPtr< FlxBasic_obj > FlxBasic_obj::__new()
{
hx::ObjectPtr< FlxBasic_obj > _hx_result = new FlxBasic_obj();
_hx_result->__construct();
return _hx_result;
}
Dynamic FlxBasic_obj::__Create(hx::DynamicArray inArgs)
{
hx::ObjectPtr< FlxBasic_obj > _hx_result = new FlxBasic_obj();
_hx_result->__construct();
return _hx_result;
}
static ::flixel::util::IFlxDestroyable_obj _hx_flixel_FlxBasic__hx_flixel_util_IFlxDestroyable= {
( void (hx::Object::*)())&::flixel::FlxBasic_obj::destroy,
};
void *FlxBasic_obj::_hx_getInterface(int inHash) {
switch(inHash) {
case (int)0xd4fe2fcd: return &_hx_flixel_FlxBasic__hx_flixel_util_IFlxDestroyable;
}
#ifdef HXCPP_SCRIPTABLE
return super::_hx_getInterface(inHash);
#else
return 0;
#endif
}
void FlxBasic_obj::destroy(){
HX_STACK_FRAME("flixel.FlxBasic","destroy",0xc50151da,"flixel.FlxBasic.destroy","flixel/FlxBasic.hx",69,0xd8d6cfcf)
HX_STACK_THIS(this)
HXLINE( 70) this->set_exists(false);
HXLINE( 71) this->_cameras = null();
}
HX_DEFINE_DYNAMIC_FUNC0(FlxBasic_obj,destroy,(void))
void FlxBasic_obj::kill(){
HX_STACK_FRAME("flixel.FlxBasic","kill",0x1748eebe,"flixel.FlxBasic.kill","flixel/FlxBasic.hx",79,0xd8d6cfcf)
HX_STACK_THIS(this)
HXLINE( 80) this->set_alive(false);
HXLINE( 81) this->set_exists(false);
}
HX_DEFINE_DYNAMIC_FUNC0(FlxBasic_obj,kill,(void))
void FlxBasic_obj::revive(){
HX_STACK_FRAME("flixel.FlxBasic","revive",0xb3f01175,"flixel.FlxBasic.revive","flixel/FlxBasic.hx",89,0xd8d6cfcf)
HX_STACK_THIS(this)
HXLINE( 90) this->set_alive(true);
HXLINE( 91) this->set_exists(true);
}
HX_DEFINE_DYNAMIC_FUNC0(FlxBasic_obj,revive,(void))
void FlxBasic_obj::update(Float elapsed){
HX_STACK_FRAME("flixel.FlxBasic","update",0x307e9d29,"flixel.FlxBasic.update","flixel/FlxBasic.hx",99,0xd8d6cfcf)
HX_STACK_THIS(this)
HX_STACK_ARG(elapsed,"elapsed")
}
HX_DEFINE_DYNAMIC_FUNC1(FlxBasic_obj,update,(void))
void FlxBasic_obj::draw(){
HX_STACK_FRAME("flixel.FlxBasic","draw",0x12af3b24,"flixel.FlxBasic.draw","flixel/FlxBasic.hx",110,0xd8d6cfcf)
HX_STACK_THIS(this)
}
HX_DEFINE_DYNAMIC_FUNC0(FlxBasic_obj,draw,(void))
::String FlxBasic_obj::toString(){
HX_STACK_FRAME("flixel.FlxBasic","toString",0x03b3efcc,"flixel.FlxBasic.toString","flixel/FlxBasic.hx",118,0xd8d6cfcf)
HX_STACK_THIS(this)
HXLINE( 119) ::Dynamic value = this->active;
HXDLIN( 119) HX_VARI( ::flixel::util::LabelValuePair,_this) = ::flixel::util::LabelValuePair_obj::_pool->get();
HXDLIN( 119) _this->label = HX_("active",c6,41,46,16);
HXDLIN( 119) _this->value = value;
HXLINE( 120) ::Dynamic value1 = this->visible;
HXDLIN( 120) HX_VARI_NAME( ::flixel::util::LabelValuePair,_this1,"_this") = ::flixel::util::LabelValuePair_obj::_pool->get();
HXDLIN( 120) _this1->label = HX_("visible",72,78,24,a3);
HXDLIN( 120) _this1->value = value1;
HXLINE( 121) ::Dynamic value2 = this->alive;
HXDLIN( 121) HX_VARI_NAME( ::flixel::util::LabelValuePair,_this2,"_this") = ::flixel::util::LabelValuePair_obj::_pool->get();
HXDLIN( 121) _this2->label = HX_("alive",cd,63,91,21);
HXDLIN( 121) _this2->value = value2;
HXLINE( 122) ::Dynamic value3 = this->exists;
HXDLIN( 122) HX_VARI_NAME( ::flixel::util::LabelValuePair,_this3,"_this") = ::flixel::util::LabelValuePair_obj::_pool->get();
HXDLIN( 122) _this3->label = HX_("exists",dc,1d,e0,bf);
HXDLIN( 122) _this3->value = value3;
HXLINE( 118) return ::flixel::util::FlxStringUtil_obj::getDebugString(::Array_obj< ::Dynamic>::__new(4)->init(0,_this)->init(1,_this1)->init(2,_this2)->init(3,_this3));
}
HX_DEFINE_DYNAMIC_FUNC0(FlxBasic_obj,toString,return )
Bool FlxBasic_obj::set_visible(Bool Value){
HX_STACK_FRAME("flixel.FlxBasic","set_visible",0x942af475,"flixel.FlxBasic.set_visible","flixel/FlxBasic.hx",127,0xd8d6cfcf)
HX_STACK_THIS(this)
HX_STACK_ARG(Value,"Value")
HXLINE( 127) return (this->visible = Value);
}
HX_DEFINE_DYNAMIC_FUNC1(FlxBasic_obj,set_visible,return )
Bool FlxBasic_obj::set_active(Bool Value){
HX_STACK_FRAME("flixel.FlxBasic","set_active",0x086e7723,"flixel.FlxBasic.set_active","flixel/FlxBasic.hx",132,0xd8d6cfcf)
HX_STACK_THIS(this)
HX_STACK_ARG(Value,"Value")
HXLINE( 132) return (this->active = Value);
}
HX_DEFINE_DYNAMIC_FUNC1(FlxBasic_obj,set_active,return )
Bool FlxBasic_obj::set_exists(Bool Value){
HX_STACK_FRAME("flixel.FlxBasic","set_exists",0xb2085339,"flixel.FlxBasic.set_exists","flixel/FlxBasic.hx",137,0xd8d6cfcf)
HX_STACK_THIS(this)
HX_STACK_ARG(Value,"Value")
HXLINE( 137) return (this->exists = Value);
}
HX_DEFINE_DYNAMIC_FUNC1(FlxBasic_obj,set_exists,return )
Bool FlxBasic_obj::set_alive(Bool Value){
HX_STACK_FRAME("flixel.FlxBasic","set_alive",0x59c1c910,"flixel.FlxBasic.set_alive","flixel/FlxBasic.hx",142,0xd8d6cfcf)
HX_STACK_THIS(this)
HX_STACK_ARG(Value,"Value")
HXLINE( 142) return (this->alive = Value);
}
HX_DEFINE_DYNAMIC_FUNC1(FlxBasic_obj,set_alive,return )
::flixel::FlxCamera FlxBasic_obj::get_camera(){
HX_STACK_FRAME("flixel.FlxBasic","get_camera",0xa636dd8e,"flixel.FlxBasic.get_camera","flixel/FlxBasic.hx",147,0xd8d6cfcf)
HX_STACK_THIS(this)
HXLINE( 147) Bool _hx_tmp;
HXDLIN( 147) Bool _hx_tmp1 = hx::IsNotNull( this->_cameras );
HXDLIN( 147) if (_hx_tmp1) {
HXLINE( 147) _hx_tmp = (this->_cameras->length == (int)0);
}
else {
HXLINE( 147) _hx_tmp = true;
}
HXDLIN( 147) if (_hx_tmp) {
HXLINE( 147) return ::flixel::FlxCamera_obj::defaultCameras->__get((int)0).StaticCast< ::flixel::FlxCamera >();
}
else {
HXLINE( 147) return this->_cameras->__get((int)0).StaticCast< ::flixel::FlxCamera >();
}
HXDLIN( 147) return null();
}
HX_DEFINE_DYNAMIC_FUNC0(FlxBasic_obj,get_camera,return )
::flixel::FlxCamera FlxBasic_obj::set_camera( ::flixel::FlxCamera Value){
HX_STACK_FRAME("flixel.FlxBasic","set_camera",0xa9b47c02,"flixel.FlxBasic.set_camera","flixel/FlxBasic.hx",151,0xd8d6cfcf)
HX_STACK_THIS(this)
HX_STACK_ARG(Value,"Value")
HXLINE( 152) Bool _hx_tmp = hx::IsNull( this->_cameras );
HXDLIN( 152) if (_hx_tmp) {
HXLINE( 153) this->_cameras = ::Array_obj< ::Dynamic>::__new(1)->init(0,Value);
}
else {
HXLINE( 155) this->_cameras[(int)0] = Value;
}
HXLINE( 156) return Value;
}
HX_DEFINE_DYNAMIC_FUNC1(FlxBasic_obj,set_camera,return )
::Array< ::Dynamic> FlxBasic_obj::get_cameras(){
HX_STACK_FRAME("flixel.FlxBasic","get_cameras",0xc9caff25,"flixel.FlxBasic.get_cameras","flixel/FlxBasic.hx",161,0xd8d6cfcf)
HX_STACK_THIS(this)
HXLINE( 161) Bool _hx_tmp = hx::IsNull( this->_cameras );
HXDLIN( 161) if (_hx_tmp) {
HXLINE( 161) return ::flixel::FlxCamera_obj::defaultCameras;
}
else {
HXLINE( 161) return this->_cameras;
}
HXDLIN( 161) return null();
}
HX_DEFINE_DYNAMIC_FUNC0(FlxBasic_obj,get_cameras,return )
::Array< ::Dynamic> FlxBasic_obj::set_cameras(::Array< ::Dynamic> Value){
HX_STACK_FRAME("flixel.FlxBasic","set_cameras",0xd4380631,"flixel.FlxBasic.set_cameras","flixel/FlxBasic.hx",166,0xd8d6cfcf)
HX_STACK_THIS(this)
HX_STACK_ARG(Value,"Value")
HXLINE( 166) return (this->_cameras = Value);
}
HX_DEFINE_DYNAMIC_FUNC1(FlxBasic_obj,set_cameras,return )
FlxBasic_obj::FlxBasic_obj()
{
}
void FlxBasic_obj::__Mark(HX_MARK_PARAMS)
{
HX_MARK_BEGIN_CLASS(FlxBasic);
HX_MARK_MEMBER_NAME(ID,"ID");
HX_MARK_MEMBER_NAME(active,"active");
HX_MARK_MEMBER_NAME(visible,"visible");
HX_MARK_MEMBER_NAME(alive,"alive");
HX_MARK_MEMBER_NAME(exists,"exists");
HX_MARK_MEMBER_NAME(flixelType,"flixelType");
HX_MARK_MEMBER_NAME(_cameras,"_cameras");
HX_MARK_END_CLASS();
}
void FlxBasic_obj::__Visit(HX_VISIT_PARAMS)
{
HX_VISIT_MEMBER_NAME(ID,"ID");
HX_VISIT_MEMBER_NAME(active,"active");
HX_VISIT_MEMBER_NAME(visible,"visible");
HX_VISIT_MEMBER_NAME(alive,"alive");
HX_VISIT_MEMBER_NAME(exists,"exists");
HX_VISIT_MEMBER_NAME(flixelType,"flixelType");
HX_VISIT_MEMBER_NAME(_cameras,"_cameras");
}
hx::Val FlxBasic_obj::__Field(const ::String &inName,hx::PropertyAccess inCallProp)
{
switch(inName.length) {
case 2:
if (HX_FIELD_EQ(inName,"ID") ) { return hx::Val( ID); }
break;
case 4:
if (HX_FIELD_EQ(inName,"kill") ) { return hx::Val( kill_dyn()); }
if (HX_FIELD_EQ(inName,"draw") ) { return hx::Val( draw_dyn()); }
break;
case 5:
if (HX_FIELD_EQ(inName,"alive") ) { return hx::Val( alive); }
break;
case 6:
if (HX_FIELD_EQ(inName,"active") ) { return hx::Val( active); }
if (HX_FIELD_EQ(inName,"exists") ) { return hx::Val( exists); }
if (HX_FIELD_EQ(inName,"camera") ) { if (inCallProp == hx::paccAlways) return hx::Val(get_camera()); }
if (HX_FIELD_EQ(inName,"revive") ) { return hx::Val( revive_dyn()); }
if (HX_FIELD_EQ(inName,"update") ) { return hx::Val( update_dyn()); }
break;
case 7:
if (HX_FIELD_EQ(inName,"visible") ) { return hx::Val( visible); }
if (HX_FIELD_EQ(inName,"cameras") ) { if (inCallProp == hx::paccAlways) return hx::Val(get_cameras()); }
if (HX_FIELD_EQ(inName,"destroy") ) { return hx::Val( destroy_dyn()); }
break;
case 8:
if (HX_FIELD_EQ(inName,"_cameras") ) { return hx::Val( _cameras); }
if (HX_FIELD_EQ(inName,"toString") ) { return hx::Val( toString_dyn()); }
break;
case 9:
if (HX_FIELD_EQ(inName,"set_alive") ) { return hx::Val( set_alive_dyn()); }
break;
case 10:
if (HX_FIELD_EQ(inName,"flixelType") ) { return hx::Val( flixelType); }
if (HX_FIELD_EQ(inName,"set_active") ) { return hx::Val( set_active_dyn()); }
if (HX_FIELD_EQ(inName,"set_exists") ) { return hx::Val( set_exists_dyn()); }
if (HX_FIELD_EQ(inName,"get_camera") ) { return hx::Val( get_camera_dyn()); }
if (HX_FIELD_EQ(inName,"set_camera") ) { return hx::Val( set_camera_dyn()); }
break;
case 11:
if (HX_FIELD_EQ(inName,"set_visible") ) { return hx::Val( set_visible_dyn()); }
if (HX_FIELD_EQ(inName,"get_cameras") ) { return hx::Val( get_cameras_dyn()); }
if (HX_FIELD_EQ(inName,"set_cameras") ) { return hx::Val( set_cameras_dyn()); }
}
return super::__Field(inName,inCallProp);
}
hx::Val FlxBasic_obj::__SetField(const ::String &inName,const hx::Val &inValue,hx::PropertyAccess inCallProp)
{
switch(inName.length) {
case 2:
if (HX_FIELD_EQ(inName,"ID") ) { ID=inValue.Cast< Int >(); return inValue; }
break;
case 5:
if (HX_FIELD_EQ(inName,"alive") ) { if (inCallProp == hx::paccAlways) return hx::Val( set_alive(inValue) );alive=inValue.Cast< Bool >(); return inValue; }
break;
case 6:
if (HX_FIELD_EQ(inName,"active") ) { if (inCallProp == hx::paccAlways) return hx::Val( set_active(inValue) );active=inValue.Cast< Bool >(); return inValue; }
if (HX_FIELD_EQ(inName,"exists") ) { if (inCallProp == hx::paccAlways) return hx::Val( set_exists(inValue) );exists=inValue.Cast< Bool >(); return inValue; }
if (HX_FIELD_EQ(inName,"camera") ) { if (inCallProp == hx::paccAlways) return hx::Val( set_camera(inValue) ); }
break;
case 7:
if (HX_FIELD_EQ(inName,"visible") ) { if (inCallProp == hx::paccAlways) return hx::Val( set_visible(inValue) );visible=inValue.Cast< Bool >(); return inValue; }
if (HX_FIELD_EQ(inName,"cameras") ) { if (inCallProp == hx::paccAlways) return hx::Val( set_cameras(inValue) ); }
break;
case 8:
if (HX_FIELD_EQ(inName,"_cameras") ) { _cameras=inValue.Cast< ::Array< ::Dynamic> >(); return inValue; }
break;
case 10:
if (HX_FIELD_EQ(inName,"flixelType") ) { flixelType=inValue.Cast< Int >(); return inValue; }
}
return super::__SetField(inName,inValue,inCallProp);
}
void FlxBasic_obj::__GetFields(Array< ::String> &outFields)
{
outFields->push(HX_HCSTRING("ID","\xdb","\x3f","\x00","\x00"));
outFields->push(HX_HCSTRING("active","\xc6","\x41","\x46","\x16"));
outFields->push(HX_HCSTRING("visible","\x72","\x78","\x24","\xa3"));
outFields->push(HX_HCSTRING("alive","\xcd","\x63","\x91","\x21"));
outFields->push(HX_HCSTRING("exists","\xdc","\x1d","\xe0","\xbf"));
outFields->push(HX_HCSTRING("camera","\xa5","\x46","\x8c","\xb7"));
outFields->push(HX_HCSTRING("cameras","\x2e","\x8a","\x31","\xe3"));
outFields->push(HX_HCSTRING("flixelType","\x36","\xbf","\x78","\x58"));
outFields->push(HX_HCSTRING("_cameras","\xaf","\xe3","\xe9","\x1c"));
super::__GetFields(outFields);
};
#if HXCPP_SCRIPTABLE
static hx::StorageInfo FlxBasic_obj_sMemberStorageInfo[] = {
{hx::fsInt,(int)offsetof(FlxBasic_obj,ID),HX_HCSTRING("ID","\xdb","\x3f","\x00","\x00")},
{hx::fsBool,(int)offsetof(FlxBasic_obj,active),HX_HCSTRING("active","\xc6","\x41","\x46","\x16")},
{hx::fsBool,(int)offsetof(FlxBasic_obj,visible),HX_HCSTRING("visible","\x72","\x78","\x24","\xa3")},
{hx::fsBool,(int)offsetof(FlxBasic_obj,alive),HX_HCSTRING("alive","\xcd","\x63","\x91","\x21")},
{hx::fsBool,(int)offsetof(FlxBasic_obj,exists),HX_HCSTRING("exists","\xdc","\x1d","\xe0","\xbf")},
{hx::fsInt,(int)offsetof(FlxBasic_obj,flixelType),HX_HCSTRING("flixelType","\x36","\xbf","\x78","\x58")},
{hx::fsObject /*Array< ::Dynamic >*/ ,(int)offsetof(FlxBasic_obj,_cameras),HX_HCSTRING("_cameras","\xaf","\xe3","\xe9","\x1c")},
{ hx::fsUnknown, 0, null()}
};
static hx::StaticInfo *FlxBasic_obj_sStaticStorageInfo = 0;
#endif
static ::String FlxBasic_obj_sMemberFields[] = {
HX_HCSTRING("ID","\xdb","\x3f","\x00","\x00"),
HX_HCSTRING("active","\xc6","\x41","\x46","\x16"),
HX_HCSTRING("visible","\x72","\x78","\x24","\xa3"),
HX_HCSTRING("alive","\xcd","\x63","\x91","\x21"),
HX_HCSTRING("exists","\xdc","\x1d","\xe0","\xbf"),
HX_HCSTRING("flixelType","\x36","\xbf","\x78","\x58"),
HX_HCSTRING("_cameras","\xaf","\xe3","\xe9","\x1c"),
HX_HCSTRING("destroy","\xfa","\x2c","\x86","\x24"),
HX_HCSTRING("kill","\x9e","\xdf","\x09","\x47"),
HX_HCSTRING("revive","\x55","\xfa","\x76","\x0a"),
HX_HCSTRING("update","\x09","\x86","\x05","\x87"),
HX_HCSTRING("draw","\x04","\x2c","\x70","\x42"),
HX_HCSTRING("toString","\xac","\xd0","\x6e","\x38"),
HX_HCSTRING("set_visible","\x95","\xdf","\x8b","\x33"),
HX_HCSTRING("set_active","\x03","\x50","\x4b","\x0a"),
HX_HCSTRING("set_exists","\x19","\x2c","\xe5","\xb3"),
HX_HCSTRING("set_alive","\x30","\xac","\x8b","\x48"),
HX_HCSTRING("get_camera","\x6e","\xb6","\x13","\xa8"),
HX_HCSTRING("set_camera","\xe2","\x54","\x91","\xab"),
HX_HCSTRING("get_cameras","\x45","\xea","\x2b","\x69"),
HX_HCSTRING("set_cameras","\x51","\xf1","\x98","\x73"),
::String(null()) };
static void FlxBasic_obj_sMarkStatics(HX_MARK_PARAMS) {
HX_MARK_MEMBER_NAME(FlxBasic_obj::__mClass,"__mClass");
};
#ifdef HXCPP_VISIT_ALLOCS
static void FlxBasic_obj_sVisitStatics(HX_VISIT_PARAMS) {
HX_VISIT_MEMBER_NAME(FlxBasic_obj::__mClass,"__mClass");
};
#endif
hx::Class FlxBasic_obj::__mClass;
void FlxBasic_obj::__register()
{
hx::Static(__mClass) = new hx::Class_obj();
__mClass->mName = HX_HCSTRING("flixel.FlxBasic","\x4e","\xa5","\x2f","\x34");
__mClass->mSuper = &super::__SGetClass();
__mClass->mConstructEmpty = &__CreateEmpty;
__mClass->mConstructArgs = &__Create;
__mClass->mGetStaticField = &hx::Class_obj::GetNoStaticField;
__mClass->mSetStaticField = &hx::Class_obj::SetNoStaticField;
__mClass->mMarkFunc = FlxBasic_obj_sMarkStatics;
__mClass->mStatics = hx::Class_obj::dupFunctions(0 /* sStaticFields */);
__mClass->mMembers = hx::Class_obj::dupFunctions(FlxBasic_obj_sMemberFields);
__mClass->mCanCast = hx::TCanCast< FlxBasic_obj >;
#ifdef HXCPP_VISIT_ALLOCS
__mClass->mVisitFunc = FlxBasic_obj_sVisitStatics;
#endif
#ifdef HXCPP_SCRIPTABLE
__mClass->mMemberStorageInfo = FlxBasic_obj_sMemberStorageInfo;
#endif
#ifdef HXCPP_SCRIPTABLE
__mClass->mStaticStorageInfo = FlxBasic_obj_sStaticStorageInfo;
#endif
hx::_hx_RegisterClass(__mClass->mName, __mClass);
}
} // end namespace flixel
| 39.445701 | 169 | 0.684657 | [
"object"
] |
a07d9d24edd872df02db2e817ea3dde93dca6098 | 7,324 | cpp | C++ | Source/Renderer/Resources/Shader.cpp | lucho1/AGPEngine | ffc3c48689ce77539a24035f90be1ecd8a65f337 | [
"Apache-2.0"
] | null | null | null | Source/Renderer/Resources/Shader.cpp | lucho1/AGPEngine | ffc3c48689ce77539a24035f90be1ecd8a65f337 | [
"Apache-2.0"
] | null | null | null | Source/Renderer/Resources/Shader.cpp | lucho1/AGPEngine | ffc3c48689ce77539a24035f90be1ecd8a65f337 | [
"Apache-2.0"
] | null | null | null | #include "Shader.h"
#include "Renderer/Utils/RendererUtils.h"
#include "Core/Utils/FileStringUtils.h"
#include <glm/gtc/type_ptr.hpp>
#include <filesystem>
#include <fstream>
// ------------------------------------------------------------------------------
Shader::Shader(const std::string& name, const std::string& vertex_src, const std::string& fragment_src)
{
// -- Set source for Shader --
std::unordered_map<GLenum, std::string> sources;
sources[GL_VERTEX_SHADER] = vertex_src;
sources[GL_FRAGMENT_SHADER] = fragment_src;
// -- Compile Shader --
CompileShader(sources);
}
Shader::Shader(const std::string& filepath)
{
// -- Compile Shader --
CompileShader(PreProcessShader(ReadShaderFile(filepath)));
// -- Shader name from filepath --
//size_t lastSlash = filepath.find_last_of("/\\");
//size_t lastDot = filepath.rfind('.');
//
//lastSlash = lastSlash == std::string::npos ? 0 : lastSlash + 1;
//lastDot = (lastDot == std::string::npos ? filepath.size() : lastDot) - lastSlash;
//m_Name = filepath.substr(lastSlash, lastDot);
// This is better:
std::filesystem::path path = filepath;
m_Name = path.stem().string(); // Returns the file's name stripped of the extension
// -- File Last Modification Time --
m_LastModificationTimestamp = FileUtils::GetFileLastWriteTimestamp(filepath.c_str()); // If problems, try: std::filesystem::last_write_time(path);
m_Path = filepath;
}
Shader::~Shader()
{
glDeleteProgram(m_ID);
}
void Shader::Bind() const
{
glUseProgram(m_ID);
}
void Shader::Unbind() const
{
glUseProgram(0);
}
void Shader::CheckLastModification()
{
uint64 last_time = FileUtils::GetFileLastWriteTimestamp(m_Path.c_str());
if (last_time > m_LastModificationTimestamp)
{
CompileShader(PreProcessShader(ReadShaderFile(m_Path)));
m_LastModificationTimestamp = last_time; // If problems, try: std::filesystem::last_write_time(path);
}
}
// ------------------------------------------------------------------------------
int Shader::GetUniformLocation(const std::string& uniform_name) const
{
if (m_UniformLocationCache.find(uniform_name) != m_UniformLocationCache.end())
return m_UniformLocationCache[uniform_name];
int loc = glGetUniformLocation(m_ID, uniform_name.c_str());
if (loc == -1)
ENGINE_LOG("Warning! Uniform '%s' doesn't exist! (loc == -1)", uniform_name.c_str());
m_UniformLocationCache[uniform_name] = loc;
return loc;
}
void Shader::SetUniformInt(const std::string& uniform_name, int value)
{
glUniform1i(GetUniformLocation(uniform_name), value);
}
void Shader::SetUniformFloat(const std::string& uniform_name, float value)
{
glUniform1f(GetUniformLocation(uniform_name), value);
}
void Shader::SetUniformVec3(const std::string& uniform_name, const glm::vec3& value)
{
glUniform3f(GetUniformLocation(uniform_name), value.r, value.g, value.b);
}
void Shader::SetUniformVec4(const std::string& uniform_name, const glm::vec4& value)
{
glUniform4f(GetUniformLocation(uniform_name), value.r, value.g, value.b, value.a);
}
void Shader::SetUniformMat4(const std::string& uniform_name, const glm::mat4& matrix)
{
glUniformMatrix4fv(GetUniformLocation(uniform_name), 1, GL_FALSE, glm::value_ptr(matrix));
}
// ------------------------------------------------------------------------------
void Shader::CompileShader(const std::unordered_map<GLenum, std::string>& shader_sources)
{
// -- Create Program --
GLuint program = glCreateProgram();
std::vector<GLenum> glShaderIDs;
glShaderIDs.reserve(shader_sources.size());
// Instead, you could create an array, which is much better than a vector:
//std::array<GLenum, 2> glShaderIDs;
// int glShaderIDIndex = 0; // In this case, the glShaderIDs.push_back() - downwards -, should be substituted by a glShaderIDs[glShaderIDIndex++] = shader;
for (auto&& [key, value] : shader_sources)
{
GLenum type = key;
const std::string& source = value;
// -- Create empty Shader handle --
GLuint shader = glCreateShader(type);
// -- Send Shader to OGL --
const GLchar* GLShaderSource = source.c_str();
glShaderSource(shader, 1, &GLShaderSource, 0);
// -- Compile Shader --
glCompileShader(shader);
// -- Check for Compilation Errors --
GLint isCompiled = 0;
glGetShaderiv(shader, GL_COMPILE_STATUS, &isCompiled);
if (isCompiled == GL_FALSE)
{
GLint maxLength = 0;
glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &maxLength);
std::vector<GLchar> infoLog(maxLength);
glGetShaderInfoLog(shader, maxLength, &maxLength, &infoLog[0]);
glDeleteShader(shader);
ENGINE_LOG("%s Shader Compilation Error: %s", RendererUtils::StringFromShaderType(type), infoLog.data());
ASSERT(false, "Shader Compilation Failure!");
break;
}
// Attach our shaders to our program
glAttachShader(program, shader);
glShaderIDs.push_back(shader);
}
// -- Link --
m_ID = program;
glLinkProgram(program);
// -- Check for Link Errors --
GLint isLinked = 0;
glGetProgramiv(program, GL_LINK_STATUS, (int*)&isLinked);
if (isLinked == GL_FALSE)
{
GLint maxLength = 0;
glGetProgramiv(program, GL_INFO_LOG_LENGTH, &maxLength);
std::vector<GLchar> infoLog(maxLength);
glGetProgramInfoLog(program, maxLength, &maxLength, &infoLog[0]);
glDeleteProgram(program);
for (auto id : glShaderIDs)
glDeleteShader(id);
ENGINE_LOG("Shader Linking Error: %s", infoLog.data());
ASSERT(false, "Shader Program Link Failure!");
return;
}
// -- Detach Shaders after successful link --
for (auto id : glShaderIDs)
{
glDetachShader(program, id);
glDeleteShader(id);
}
}
const std::unordered_map<GLenum, std::string> Shader::PreProcessShader(const std::string& source)
{
std::unordered_map<GLenum, std::string> ret;
// -- Token #type for Shader Type --
const char* typeToken = "#type";
size_t typeTokenLength = strlen(typeToken);
size_t pos = source.find(typeToken, 0);
// -- Iterate all the string --
while (pos != std::string::npos)
{
size_t eol = source.find_first_of("\r\n", pos); // End of token line
size_t begin = pos + typeTokenLength + 1; // Start of Shader Type Name (after '#type' token)
std::string shader_type = source.substr(begin, eol - begin);
ASSERT(RendererUtils::ShaderTypeFromString(shader_type), "Invalid ShaderType specification or not supported");
size_t next_line_pos = source.find_first_not_of("\r\n", eol); // Start of shader code after token
pos = source.find(typeToken, next_line_pos); // Start of next shader token
ret[RendererUtils::ShaderTypeFromString(shader_type)] = (pos == std::string::npos) ? source.substr(next_line_pos) : source.substr(next_line_pos, pos - next_line_pos);
}
return ret;
}
const std::string Shader::ReadShaderFile(const std::string& filepath)
{
std::ifstream file(filepath, std::ios::in | std::ios::binary);
std::string ret;
if (file)
{
// -- File Size --
file.seekg(0, std::ios::end);
size_t file_size = file.tellg();
if (file_size != -1)
{
// -- String as big as file size & Load file into string --
ret.resize(file_size);
file.seekg(0, std::ios::beg); // Cursor at file beginning
file.read(&ret[0], file_size);
return ret;
}
else
ENGINE_LOG("Couldn't read Shader file at path '%s'", filepath.c_str());
}
else
ENGINE_LOG("Couldn't open Shader file at path '%s'", filepath.c_str());
return ret;
} | 29.296 | 168 | 0.687602 | [
"vector"
] |
a081679c7c76f49d6d1eba1e7fe09bff61a03a61 | 2,034 | cc | C++ | RecoVertex/ConfigurableVertexReco/src/ReconstructorFromFitter.cc | ckamtsikis/cmssw | ea19fe642bb7537cbf58451dcf73aa5fd1b66250 | [
"Apache-2.0"
] | 852 | 2015-01-11T21:03:51.000Z | 2022-03-25T21:14:00.000Z | RecoVertex/ConfigurableVertexReco/src/ReconstructorFromFitter.cc | ckamtsikis/cmssw | ea19fe642bb7537cbf58451dcf73aa5fd1b66250 | [
"Apache-2.0"
] | 30,371 | 2015-01-02T00:14:40.000Z | 2022-03-31T23:26:05.000Z | RecoVertex/ConfigurableVertexReco/src/ReconstructorFromFitter.cc | ckamtsikis/cmssw | ea19fe642bb7537cbf58451dcf73aa5fd1b66250 | [
"Apache-2.0"
] | 3,240 | 2015-01-02T05:53:18.000Z | 2022-03-31T17:24:21.000Z | #include "RecoVertex/ConfigurableVertexReco/interface/ReconstructorFromFitter.h"
#include "FWCore/MessageLogger/interface/MessageLogger.h"
using namespace std;
ReconstructorFromFitter::ReconstructorFromFitter(std::unique_ptr<AbstractConfFitter>&& f) : theFitter(f.release()) {}
vector<TransientVertex> ReconstructorFromFitter::vertices(const vector<reco::TransientTrack>& t) const {
vector<TransientVertex> ret;
// cout << "[ReconstructorFromFitter] debug: fitting without bs!" << endl;
try {
CachingVertex<5> tmp = theFitter->vertex(t);
if (tmp.isValid())
ret.push_back(tmp);
} catch (VertexException& e) {
edm::LogWarning("ReconstructorFromFitter") << "exception caught: " << e.what();
}
return ret;
}
vector<TransientVertex> ReconstructorFromFitter::vertices(const vector<reco::TransientTrack>& t,
const reco::BeamSpot& s) const {
vector<TransientVertex> ret;
try {
/*
cout << "[ReconstructorFromFitter] debug: fitting with s: " << s.BeamWidth()
<< " sz=" << s.sigmaZ() << endl;
*/
CachingVertex<5> tmp = theFitter->vertex(t, s);
if (tmp.isValid())
ret.push_back(tmp);
} catch (VertexException& e) {
edm::LogWarning("ReconstructorFromFitter") << "exception caught: " << e.what();
}
return ret;
}
ReconstructorFromFitter::~ReconstructorFromFitter() { delete theFitter; }
ReconstructorFromFitter::ReconstructorFromFitter(const ReconstructorFromFitter& o) : theFitter(o.theFitter->clone()) {}
edm::ParameterSet ReconstructorFromFitter::defaults() const { return theFitter->defaults(); }
void ReconstructorFromFitter::configure(const edm::ParameterSet& s) {
//this looks better than changing the data member to be non-const ptr and allow changes in all calls
const_cast<AbstractConfFitter*>(theFitter)->configure(s);
}
ReconstructorFromFitter* ReconstructorFromFitter::clone() const { return new ReconstructorFromFitter(*this); }
| 40.68 | 120 | 0.688791 | [
"vector"
] |
a084b14c9e1bb2ab4c86d86bf92f9ba0738129e9 | 731 | cpp | C++ | pvl/abridged/math/algebra/poly-long-div.cpp | bullybutcher/progvar-library | 4d4b351c8a2540c522d00138e1bcf0edc528b540 | [
"MIT"
] | 3 | 2021-10-16T13:22:58.000Z | 2021-10-29T22:03:44.000Z | pvl/abridged/math/algebra/poly-long-div.cpp | bullybutcher/progvar-library | 4d4b351c8a2540c522d00138e1bcf0edc528b540 | [
"MIT"
] | 19 | 2021-11-27T14:40:00.000Z | 2022-03-30T07:14:59.000Z | pvl/abridged/math/algebra/poly-long-div.cpp | bullybutcher/progvar-library | 4d4b351c8a2540c522d00138e1bcf0edc528b540 | [
"MIT"
] | 2 | 2022-03-11T20:53:41.000Z | 2022-03-20T07:08:46.000Z | typedef vector<double> Poly;
Poly Q, R; // quotient and remainder
void trim(Poly& A) { // remove trailing zeroes
while (!A.empty() && abs(A.back()) < EPS)
A.pop_back();
}
void divide(Poly A, Poly B) {
if (B.size() == 0) throw exception();
if (A.size() < B.size()) {Q.clear(); R=A; return;}
Q.assign(A.size() - B.size() + 1, 0);
Poly part;
while (A.size() >= B.size()) {
int As = A.size(), Bs = B.size();
part.assign(As, 0);
for (int i = 0; i < Bs; i++)
part[As-Bs+i] = B[i];
double scale = Q[As-Bs] = A[As-1] / part[As-1];
for (int i = 0; i < As; i++)
A[i] -= part[i] * scale;
trim(A);
} R = A; trim(Q); }
| 33.227273 | 56 | 0.463748 | [
"vector"
] |
a087e64138ce30f0850b0208d891891c124e3e09 | 5,095 | cpp | C++ | modules/task_2/rodionov_n_broadcast_message/main.cpp | Gekata-2/pp_2021_autumn | caeac9a213e9b0c9fe1ed877d43d1eae5a1bb2cf | [
"BSD-3-Clause"
] | 1 | 2021-12-09T17:20:25.000Z | 2021-12-09T17:20:25.000Z | modules/task_2/rodionov_n_broadcast_message/main.cpp | Gekata-2/pp_2021_autumn | caeac9a213e9b0c9fe1ed877d43d1eae5a1bb2cf | [
"BSD-3-Clause"
] | null | null | null | modules/task_2/rodionov_n_broadcast_message/main.cpp | Gekata-2/pp_2021_autumn | caeac9a213e9b0c9fe1ed877d43d1eae5a1bb2cf | [
"BSD-3-Clause"
] | 3 | 2022-02-23T14:20:50.000Z | 2022-03-30T09:00:02.000Z | // Copyright 2021 TexHik620953
#include <mpi.h>
#include <gtest/gtest.h>
#include <vector>
#include <gtest-mpi-listener.hpp>
#include "../../../modules/task_2/rodionov_n_broadcast_message/broadcast_message.h"
int length = 1000;
int root = 0;
int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
MPI_Init(&argc, &argv);
::testing::AddGlobalTestEnvironment(new GTestMPIListener::MPIEnvironment);
::testing::TestEventListeners& listeners =
::testing::UnitTest::GetInstance()->listeners();
listeners.Release(listeners.default_result_printer());
listeners.Release(listeners.default_xml_generator());
listeners.Append(new GTestMPIListener::MPIMinimalistPrinter);
return RUN_ALL_TESTS();
}
TEST(BroadCastTest, DoubleSum) {
int commSize, rank;
MPI_Comm_size(MPI_COMM_WORLD, &commSize);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
// Create matrix
double* linear_matrix = nullptr;
double seq_sum = 0;
double mpi_result = 0;
if (rank == root) {
linear_matrix = new double[commSize * length];
for (int i = 0; i < commSize * length; i++) {
linear_matrix[i] = static_cast<double>(randint(0, 100)) / 100;
seq_sum += linear_matrix[i];
}
}
BroadcastSum(linear_matrix, &mpi_result, length, root, MPI_SUM, MPI_DOUBLE);
if (rank == root) {
EXPECT_NEAR(mpi_result, seq_sum, 1e-2);
delete[] linear_matrix;
}
}
TEST(BroadCastTest, DoubleMax) {
int commSize, rank;
MPI_Comm_size(MPI_COMM_WORLD, &commSize);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
// Create matrix
double* linear_matrix = nullptr;
double seq_max = 0;
double mpi_result = 0;
if (rank == root) {
linear_matrix = new double[commSize * length];
for (int i = 0; i < commSize * length; i++) {
linear_matrix[i] = static_cast<double>(randint(0, 100)) / 100;
if (linear_matrix[i] > seq_max) {
seq_max = linear_matrix[i];
}
}
}
BroadcastSum(linear_matrix, &mpi_result, length, root, MPI_MAX, MPI_DOUBLE);
if (rank == root) {
EXPECT_NEAR(mpi_result, seq_max, 1e-2);
delete[] linear_matrix;
}
}
TEST(BroadCastTest, FloatSum) {
int commSize, rank;
MPI_Comm_size(MPI_COMM_WORLD, &commSize);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
// Create matrix
float* linear_matrix = nullptr;
float seq_sum = 0;
float mpi_result = 0;
if (rank == root) {
linear_matrix = new float[commSize * length];
for (int i = 0; i < commSize * length; i++) {
linear_matrix[i] = static_cast<float>(randint(0, 100)) / 100;
seq_sum += linear_matrix[i];
}
}
BroadcastSum(linear_matrix, &mpi_result, length, root, MPI_SUM, MPI_FLOAT);
if (rank == root) {
EXPECT_NEAR(mpi_result, seq_sum, 1e-1);
delete[] linear_matrix;
}
}
TEST(BroadCastTest, FloatMax) {
int commSize, rank;
MPI_Comm_size(MPI_COMM_WORLD, &commSize);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
// Create matrix
float* linear_matrix = nullptr;
float seq_max = 0;
float mpi_result = 0;
if (rank == root) {
linear_matrix = new float[commSize * length];
for (int i = 0; i < commSize * length; i++) {
linear_matrix[i] = static_cast<float>(randint(0, 100)) / 100;
if (linear_matrix[i] > seq_max) {
seq_max = linear_matrix[i];
}
}
}
BroadcastSum(linear_matrix, &mpi_result, length, root, MPI_MAX, MPI_FLOAT);
if (rank == root) {
EXPECT_NEAR(mpi_result, seq_max, 1e-1);
delete[] linear_matrix;
}
}
TEST(BroadCastTest, IntSum) {
int commSize, rank;
MPI_Comm_size(MPI_COMM_WORLD, &commSize);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
// Create matrix
int* linear_matrix = nullptr;
int seq_sum = 0;
int mpi_result = 0;
if (rank == root) {
linear_matrix = new int[commSize * length];
for (int i = 0; i < commSize * length; i++) {
linear_matrix[i] = randint(0, 100);
seq_sum += linear_matrix[i];
}
}
BroadcastSum(linear_matrix, &mpi_result, length, root, MPI_SUM, MPI_INT);
if (rank == root) {
EXPECT_EQ(mpi_result, seq_sum);
delete[] linear_matrix;
}
}
TEST(BroadCastTest, IntMax) {
int commSize, rank;
MPI_Comm_size(MPI_COMM_WORLD, &commSize);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
// Create matrix
int* linear_matrix = nullptr;
int seq_max = 0;
int mpi_result = 0;
if (rank == root) {
linear_matrix = new int[commSize * length];
for (int i = 0; i < commSize * length; i++) {
linear_matrix[i] = randint(0, 100);
if (linear_matrix[i] > seq_max) {
seq_max = linear_matrix[i];
}
}
}
BroadcastSum(linear_matrix, &mpi_result, length, root, MPI_MAX, MPI_INT);
if (rank == root) {
EXPECT_EQ(mpi_result, seq_max);
delete[] linear_matrix;
}
}
| 31.450617 | 83 | 0.612169 | [
"vector"
] |
90b70507113a708505e8ff353b6fd1dde98ea15a | 19,483 | cpp | C++ | BGE/PhysicsFactory.cpp | PocketRocketRoche/GamesEngines1Assignment | 2b402cb45387eb64f34c8a648fd68c3cd1df0118 | [
"MIT"
] | null | null | null | BGE/PhysicsFactory.cpp | PocketRocketRoche/GamesEngines1Assignment | 2b402cb45387eb64f34c8a648fd68c3cd1df0118 | [
"MIT"
] | null | null | null | BGE/PhysicsFactory.cpp | PocketRocketRoche/GamesEngines1Assignment | 2b402cb45387eb64f34c8a648fd68c3cd1df0118 | [
"MIT"
] | null | null | null | #include "PhysicsFactory.h"
#include "Game.h"
#include "Sphere.h"
#include "Box.h"
#include "Cylinder.h"
#include "Capsule.h"
#include "Ground.h"
#include "Content.h"
#include "PhysicsCamera.h"
#include "Model.h"
#include "dirent.h"
#include "Utils.h"
using namespace BGE;
PhysicsFactory::PhysicsFactory(btDiscreteDynamicsWorld * dynamicsWorld)
{
this->dynamicsWorld = dynamicsWorld;
}
PhysicsFactory::~PhysicsFactory(void)
{
}
void PhysicsFactory::CreateWall(glm::vec3 startAt, float width, float height, float blockWidth, float blockHeight, float blockDepth)
{
float z = startAt.z;
float gap = 1;
for (int w = 0 ; w < width ; w ++)
{
for (int h = 0 ; h < height ; h ++)
{
float x = startAt.x + ((blockWidth + 2) * w);
float y = ((blockHeight + gap) / 2.0f) + ((blockHeight + gap) * h);
CreateBox(blockWidth, blockHeight, blockDepth, glm::vec3(x, y, z), glm::quat());
}
}
}
shared_ptr<PhysicsController> PhysicsFactory::CreateFromModel(string name, glm::vec3 pos, glm::quat quat, glm::vec3 scale)
{
shared_ptr<GameComponent> component = make_shared<GameComponent>();
component->tag = name;
component->scale = scale;
Game::Instance()->Attach(component);
shared_ptr<Model> model = Content::LoadModel(name);
component->specular = glm::vec3(1.2f, 1.2f, 1.2f);
model->Initialise();
component->Attach(model);
std::vector<glm::vec3>::iterator it = model->vertices.begin();
btConvexHullShape * tetraShape = new btConvexHullShape();
while (it != model->vertices.end())
{
glm::vec4 point = glm::vec4(* it, 0) * glm::scale(glm::mat4(1), scale);
tetraShape->addPoint(GLToBtVector(glm::vec3(point)));
it ++;
}
btScalar mass = 1;
btVector3 inertia(0,0,0);
tetraShape->calculateLocalInertia(mass,inertia);
btDefaultMotionState * motionState = new btDefaultMotionState(btTransform(GLToBtQuat(quat)
,GLToBtVector(pos)));
btRigidBody::btRigidBodyConstructionInfo rigidBodyCI(mass,motionState, tetraShape, inertia);
btRigidBody * body = new btRigidBody(rigidBodyCI);
body->setCollisionFlags(body->getCollisionFlags() | btCollisionObject::CF_CUSTOM_MATERIAL_CALLBACK);
dynamicsWorld->addRigidBody(body);
shared_ptr<PhysicsController> controller =make_shared<PhysicsController>(tetraShape, body, motionState);
body->setUserPointer(controller.get());
component->Attach(controller);
controller->tag = "Model";
return controller;
}
shared_ptr<PhysicsController> PhysicsFactory::CreateSphere(float radius, glm::vec3 pos, glm::quat quat)
{
shared_ptr<GameComponent> sphere (new Sphere(radius));
Game::Instance()->Attach(sphere);
btDefaultMotionState * sphereMotionState = new btDefaultMotionState(btTransform(GLToBtQuat(quat)
,GLToBtVector(pos)));
btScalar mass = 1;
btVector3 sphereInertia(0,0,0);
btCollisionShape * sphereShape = new btSphereShape(radius);
sphereShape->calculateLocalInertia(mass,sphereInertia);
btRigidBody::btRigidBodyConstructionInfo fallRigidBodyCI(mass,sphereMotionState, sphereShape, sphereInertia);
btRigidBody * body = new btRigidBody(fallRigidBodyCI);
body->setCollisionFlags(body->getCollisionFlags() | btCollisionObject::CF_CUSTOM_MATERIAL_CALLBACK);
dynamicsWorld->addRigidBody(body);
shared_ptr<PhysicsController> sphereController (new PhysicsController(sphereShape, body, sphereMotionState));
body->setUserPointer(sphereController.get());
sphere->Attach(sphereController);
sphereController->tag = "Sphere";
return sphereController;
}
shared_ptr<PhysicsController> PhysicsFactory::CreateBox(float width, float height, float depth, glm::vec3 pos, glm::quat quat)
{
// Create the shape
btCollisionShape * boxShape = new btBoxShape(btVector3(width, height, depth) * 0.5);
btScalar mass = 1;
btVector3 boxInertia(0,0,0);
boxShape->calculateLocalInertia(mass,boxInertia);
// This is a container for the box model
shared_ptr<Box> box = make_shared<Box>(width, height, depth);
box->worldMode = GameComponent::from_child;
box->position = pos;
Game::Instance()->Attach(box);
// Create the rigid body
btDefaultMotionState * boxMotionState = new btDefaultMotionState(btTransform(GLToBtQuat(quat)
,GLToBtVector(pos)));
btRigidBody::btRigidBodyConstructionInfo fallRigidBodyCI(mass, boxMotionState, boxShape, boxInertia);
btRigidBody * body = new btRigidBody(fallRigidBodyCI);
body->setFriction(567);
dynamicsWorld->addRigidBody(body);
// Create the physics component and add it to the box
shared_ptr<PhysicsController> boxController = make_shared<PhysicsController>(PhysicsController(boxShape, body, boxMotionState));
boxController->tag = "Box";
body->setUserPointer(boxController.get());
body->setCollisionFlags(body->getCollisionFlags() | btCollisionObject::CF_CUSTOM_MATERIAL_CALLBACK);
box->Attach(boxController);
return boxController;
}
shared_ptr<PhysicsController> PhysicsFactory::CreateWall(float width, float height, float depth, glm::vec3 pos, glm::quat quat)
{
// Create the shape
btCollisionShape * boxShape = new btBoxShape(btVector3(width, height, depth) * 0.5);
btScalar mass = 100;
btVector3 boxInertia(0,0,0);
boxShape->calculateLocalInertia(mass,boxInertia);
// This is a container for the box model
shared_ptr<Box> box = make_shared<Box>(width, height, depth);
box->worldMode = GameComponent::from_child;
box->position = pos;
Game::Instance()->Attach(box);
// Create the rigid body
btDefaultMotionState * boxMotionState = new btDefaultMotionState(btTransform(GLToBtQuat(quat)
,GLToBtVector(pos)));
btRigidBody::btRigidBodyConstructionInfo fallRigidBodyCI(mass, boxMotionState, boxShape, boxInertia);
btRigidBody * body = new btRigidBody(fallRigidBodyCI);
body->setFriction(567);
dynamicsWorld->addRigidBody(body);
// Create the physics component and add it to the box
shared_ptr<PhysicsController> boxController = make_shared<PhysicsController>(PhysicsController(boxShape, body, boxMotionState));
boxController->tag = "Wall";
body->setUserPointer(boxController.get());
body->setCollisionFlags(body->getCollisionFlags() | btCollisionObject::CF_CUSTOM_MATERIAL_CALLBACK);
box->Attach(boxController);
return boxController;
}
shared_ptr<PhysicsController> PhysicsFactory::CreateCylinder(float radius, float height, glm::vec3 pos, glm::quat quat)
{
// Create the shape
btCollisionShape * shape = new btCylinderShape(btVector3(radius, height * 0.5f, radius));
btScalar mass = 100;
btVector3 inertia(0,0,0);
shape->calculateLocalInertia(mass,inertia);
// This is a container for the box model
shared_ptr<GameComponent> cyl = make_shared<GameComponent>(Cylinder(radius, height));
cyl->position = pos;
Game::Instance()->Attach(cyl);
// Create the rigid body
btDefaultMotionState * motionState = new btDefaultMotionState(btTransform(GLToBtQuat(quat)
,GLToBtVector(pos)));
btRigidBody::btRigidBodyConstructionInfo rigidBodyCI(mass, motionState, shape, inertia);
btRigidBody * body = new btRigidBody(rigidBodyCI);
body->setCollisionFlags(body->getCollisionFlags() | btCollisionObject::CF_CUSTOM_MATERIAL_CALLBACK);
dynamicsWorld->addRigidBody(body);
// Create the physics component and add it to the box
shared_ptr<PhysicsController> component = make_shared<PhysicsController>(PhysicsController(shape, body, motionState));
body->setUserPointer(component.get());
component->tag = "Cylinder";
cyl->Attach(component);
return component;
}
shared_ptr<PhysicsController> PhysicsFactory::CreateCapsule(float radius, float height, glm::vec3 pos, glm::quat quat)
{
// Create the shape
btCollisionShape * shape = new btCapsuleShape(radius,height);
btScalar mass = 1;
btVector3 inertia(0,0,0);
shape->calculateLocalInertia(mass,inertia);
// This is a container for the box model
shared_ptr<GameComponent> capsule = make_shared<GameComponent>(Capsule(radius, height));
capsule->position = pos;
Game::Instance()->Attach(capsule);
// Create the rigid body
btDefaultMotionState * motionState = new btDefaultMotionState(btTransform(GLToBtQuat(quat)
,GLToBtVector(pos)));
btRigidBody::btRigidBodyConstructionInfo rigidBodyCI(mass, motionState, shape, inertia);
btRigidBody * body = new btRigidBody(rigidBodyCI);
body->setCollisionFlags(body->getCollisionFlags() | btCollisionObject::CF_CUSTOM_MATERIAL_CALLBACK);
dynamicsWorld->addRigidBody(body);
// Create the physics component and add it to the box
shared_ptr<PhysicsController> component = make_shared<PhysicsController>(PhysicsController(shape, body, motionState));
body->setUserPointer(component.get());
component->tag = "Capsule";
capsule->Attach(component);
return component;
}
shared_ptr<PhysicsController> PhysicsFactory::CreateCameraPhysics()
{
btVector3 inertia;
// Now add physics to the camera
btCollisionShape * cameraCyl = new btCylinderShape(btVector3(0.5f, 5.0f, 2.5f));
cameraCyl->calculateLocalInertia(1, inertia);
shared_ptr<PhysicsCamera> physicsCamera = make_shared<PhysicsCamera>(this);
shared_ptr<Camera> camera = Game::Instance()->camera;
camera->Attach(physicsCamera);
btRigidBody::btRigidBodyConstructionInfo cameraCI(10,physicsCamera.get(), cameraCyl, inertia);
btRigidBody * body = new btRigidBody(cameraCI);
physicsCamera->SetPhysicsStuff(cameraCyl, body, physicsCamera.get());
body->setCollisionFlags(body->getCollisionFlags() | btCollisionObject::CF_KINEMATIC_OBJECT);
body->setActivationState(DISABLE_DEACTIVATION);
dynamicsWorld->addRigidBody(body);
return physicsCamera;
}
shared_ptr<PhysicsController> PhysicsFactory::CreateVehicle(glm::vec3 position)
{
float width = 15;
float height = 2;
float length = 5;
float wheelWidth = 1;
float wheelRadius = 2;
float wheelOffset = 2.0f;
shared_ptr<PhysicsController> chassis = CreateBox(width, height, length, position, glm::quat());
shared_ptr<PhysicsController> wheel;
glm::quat q = glm::angleAxis(glm::half_pi<float>(), glm::vec3(1, 0, 0));
glm::vec3 offset;
btHingeConstraint * hinge;
offset = glm::vec3(- (width / 2 - wheelRadius), 0, - (length / 2 + wheelOffset));
wheel = CreateCylinder(wheelRadius, wheelWidth, position + offset, q);
hinge = new btHingeConstraint(* chassis->rigidBody, * wheel->rigidBody, GLToBtVector(offset),btVector3(0,0, 0), btVector3(0,0,1), btVector3(0,1,0), true);
dynamicsWorld->addConstraint(hinge);
offset = glm::vec3(+ (width / 2 - wheelRadius), 0, - (length / 2 + wheelOffset));
wheel = CreateCylinder(wheelRadius, wheelWidth, glm::vec3(position.x + (width / 2) - wheelRadius, position.y, position.z - (length / 2) - wheelWidth), q);
hinge = new btHingeConstraint(* chassis->rigidBody, * wheel->rigidBody, GLToBtVector(offset),btVector3(0,0, 0), btVector3(0,0,1), btVector3(0,1,0), true);
dynamicsWorld->addConstraint(hinge);
offset = glm::vec3(- (width / 2 - wheelRadius), 0, + (length / 2 + wheelOffset));
wheel = CreateCylinder(wheelRadius, wheelWidth, position + offset, q);
hinge = new btHingeConstraint(* chassis->rigidBody, * wheel->rigidBody, GLToBtVector(offset),btVector3(0,0, 0), btVector3(0,0,1), btVector3(0,1,0), true);
dynamicsWorld->addConstraint(hinge);
offset = glm::vec3(+ (width / 2 - wheelRadius), 0, + (length / 2 + wheelOffset));
wheel = CreateCylinder(wheelRadius, wheelWidth, position + offset, q);
hinge = new btHingeConstraint(* chassis->rigidBody, * wheel->rigidBody, GLToBtVector(offset),btVector3(0,0, 0), btVector3(0,0,1), btVector3(0,1,0), true);
dynamicsWorld->addConstraint(hinge);
return chassis;
}
//Creation Inca Pyramid of boxes
void PhysicsFactory::CreateIncaPyramid(glm::vec3 startAt, int baseWidth ,float blockWidth, float blockHeight, float blockDepth)
{
//var to hold the x axis/width.
float xPos;
//var to hold the y axis/height.
float yPos;
//var to hold the z axis/depth.
float zPos;
//for loop to control how the column moves upwards on the Y axis.
for(int i = 0; i < baseWidth; i++)
{
//var to hold hieght gotten by getting starting y point + block height * number of times looped
yPos = startAt.y + (blockHeight * i);
//for loop to control how pyramid moves across the X axis, i is taken away from baseWidth to keep in line with the number of blocks created.
for(int j = 0; j < baseWidth - i; j++)
{
//like yPos, var to hold width is gotten by getting starting x point + block widht * number of times looped
xPos = startAt.x + (blockWidth * j);
// Finally this for loop covers Z axis movement. i is taken away from k to keep in line with the number of blocks created.
//last for loop to control pyramid depth
for(int k = 0; k < baseWidth - i; k++)
{
zPos = startAt.z + (blockDepth * k);
//box is created with the correct X, Y, Z axis measurements
CreateBox(blockWidth, blockHeight, blockDepth, glm::vec3(xPos, yPos, zPos), glm::quat());
}
}
//starting pos of x and z must be divided in half to center the origin in the center of the created boxes, essentially inca pyramid shape
startAt.x += blockWidth / 2;
startAt.z += blockDepth / 2;
}
}
//Creation of RagDoll
shared_ptr<PhysicsController> PhysicsFactory::CreateRagDoll(glm::vec3 position)
{
// Creation of body
// Torso - This acts as the default position. Every other body part is relative to this co-ordinate.
shared_ptr<PhysicsController> torso = CreateBox(3,6,1, glm::vec3(position.x, position.y, position.z), glm::quat());
// LEGS
// Right leg
shared_ptr<PhysicsController> lowerRightLeg = CreateBox(1,3,1, glm::vec3(position.x + 1, position.y - 10, position.z), glm::quat());
shared_ptr<PhysicsController> upperRightLeg = CreateBox(1,2,1, glm::vec3(position.x + 1, position.y - 5, position.z), glm::quat());
// Left leg
shared_ptr<PhysicsController> lowerLeftLeg = CreateBox(1,3,1, glm::vec3(position.x - 1, position.y - 10, position.z), glm::quat());
shared_ptr<PhysicsController> upperLeftLeg = CreateBox(1,3,1, glm::vec3(position.x - 1, position.y - 5, position.z), glm::quat());
// ARMS
// Right arm.
shared_ptr<PhysicsController> lowerRightArm = CreateBox(1,3,1, glm::vec3(position.x + 3, position.y - 4, position.z), glm::quat());
shared_ptr<PhysicsController> upperRightArm = CreateBox(1,3,1, glm::vec3(position.x + 3, position.y + 1, position.z), glm::quat());
// Left arm.
shared_ptr<PhysicsController> lowerLeftArm = CreateBox(1,3,1, glm::vec3(position.x - 3, position.y -4, position.z), glm::quat());
shared_ptr<PhysicsController> upperLeftArm = CreateBox(1,3,1, glm::vec3(position.x - 3, position.y + 1, position.z), glm::quat());
// Head
shared_ptr<PhysicsController> head = CreateBox(1,1,1, glm::vec3(position.x, position.y + 5, position.z), glm::quat());
//**********************************************
// Creation of hinge joints
// Legs
//Connect lower left leg to top part of leg with hinge joint
btHingeConstraint * hinge = new btHingeConstraint(*lowerLeftLeg->rigidBody, *upperLeftLeg->rigidBody, btVector3(0,2.5f,0),btVector3(0,-2.5f,0), btVector3(1,0,0), btVector3(1,0,0), true);
dynamicsWorld->addConstraint(hinge);
//Connect lower right leg to top part of right with hinge joint
hinge = new btHingeConstraint(*lowerRightLeg->rigidBody, *upperRightLeg->rigidBody, btVector3(0,2.5f,0),btVector3(0,-2.5f,0), btVector3(1,0,0), btVector3(1,0,0), true);
dynamicsWorld->addConstraint(hinge);
// Arms
//Connect lower left arm to top part of arm with hinge joint
hinge = new btHingeConstraint(*lowerLeftArm->rigidBody, *upperLeftArm->rigidBody, btVector3(0,2.5f,0),btVector3(0,-2.5f,0), btVector3(1,0,0), btVector3(1,0,0), true);
dynamicsWorld->addConstraint(hinge);
//Connect lower left arm to top part of top right arm with hinge joint
hinge = new btHingeConstraint(*lowerRightArm->rigidBody, *upperRightArm->rigidBody, btVector3(0,2.5f,0),btVector3(0,-2.5f,0), btVector3(1,0,0), btVector3(1,0,0), true);
dynamicsWorld->addConstraint(hinge);
// Torso
//Connect torso to top part of left leg with ball & socket hinge joint
btPoint2PointConstraint * ptpConstraint = new btPoint2PointConstraint(*torso->rigidBody, *upperLeftLeg->rigidBody, btVector3(-1,-2.75f,0),btVector3(0,3,0));
dynamicsWorld->addConstraint(ptpConstraint);
//Connect torso to top part of right leg with ball & socket hinge joint
ptpConstraint = new btPoint2PointConstraint(*torso->rigidBody, *upperRightLeg->rigidBody, btVector3(1,-2.75f,0),btVector3(0,3,0));
dynamicsWorld->addConstraint(ptpConstraint);
//Connect torso to top part of left arm with ball & socket hinge joint
ptpConstraint = new btPoint2PointConstraint(*torso->rigidBody, *upperLeftArm->rigidBody, btVector3(-2.5f,2.5f,0),btVector3(0,2.5f,0));
dynamicsWorld->addConstraint(ptpConstraint);
//Connect torso to top part of right arm with ball & socket hinge joint
ptpConstraint = new btPoint2PointConstraint(*torso->rigidBody, *upperRightArm->rigidBody, btVector3(2.5f,2.5f,0),btVector3(0,2.5f,0));
dynamicsWorld->addConstraint(ptpConstraint);
// Head
//Connect torso to head
ptpConstraint = new btPoint2PointConstraint(*torso->rigidBody, *head->rigidBody, btVector3(0, 2.75f,0),btVector3(0,-1.5f,0));
dynamicsWorld->addConstraint(ptpConstraint);
return torso;
}
shared_ptr<PhysicsController> PhysicsFactory::CreateGroundPhysics()
{
shared_ptr<Ground> ground = make_shared<Ground>();
btCollisionShape * groundShape = new btStaticPlaneShape(btVector3(0,1,0),1);
btDefaultMotionState * groundMotionState = new btDefaultMotionState(btTransform(btQuaternion(0,0,0,1),btVector3(0,-1,0)));
btRigidBody::btRigidBodyConstructionInfo groundRigidBodyCI(0,groundMotionState,groundShape,btVector3(0,0,0));
btRigidBody* body = new btRigidBody(groundRigidBodyCI);
body->setFriction(100);
dynamicsWorld->addRigidBody(body);
body->setUserPointer(ground.get());
body->setCollisionFlags(body->getCollisionFlags() | btCollisionObject::CF_CUSTOM_MATERIAL_CALLBACK);
shared_ptr<PhysicsController> groundComponent (new PhysicsController(groundShape, body, groundMotionState));
groundComponent->tag = "Ground";
ground->Attach(groundComponent);
Game::Instance()->SetGround(ground);
return groundComponent;
}
shared_ptr<PhysicsController> PhysicsFactory::CreateRandomObject(glm::vec3 point, glm::quat q)
{
vector<string> names;
DIR * dir;
struct dirent * ent;
dir = opendir (Content::prefix.c_str());
if (dir != NULL)
{
/* print all the files and directories within directory */
while ((ent = readdir (dir)) != NULL)
{
string fname = string(ent->d_name);
int fpos = fname.find("objm");
if (fpos != string::npos)
{
if ((fname.find("cube") == string::npos) && (fname.find("cyl") == string::npos) && (fname.find("sphere") == string::npos))
{
names.push_back(fname.substr(0, fpos - 1));
}
}
}
closedir (dir);
}
else
{
throw BGE::Exception("Could not list obj files in content folder");
}
int which = rand() % names.size();
string name = names[which];
return CreateFromModel(name, point, q, glm::vec3(3,3,3));
}
| 42.354348 | 194 | 0.715958 | [
"shape",
"vector",
"model"
] |
90b72b6d56cf93d00e09d0d3372f6d587303dae6 | 25,488 | cpp | C++ | tests/stress/ParameterSweepTest.cpp | fkhan1337/glow | 9f6326266aedd2c9fad061807dc5128961ea0d70 | [
"Apache-2.0"
] | null | null | null | tests/stress/ParameterSweepTest.cpp | fkhan1337/glow | 9f6326266aedd2c9fad061807dc5128961ea0d70 | [
"Apache-2.0"
] | 1 | 2020-01-06T09:14:32.000Z | 2020-01-06T09:14:32.000Z | tests/stress/ParameterSweepTest.cpp | fkhan1337/glow | 9f6326266aedd2c9fad061807dc5128961ea0d70 | [
"Apache-2.0"
] | null | null | null | /**
* Copyright (c) Glow Contributors. See CONTRIBUTORS file.
*
* 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 "BackendTestUtils.h"
#include "glow/ExecutionEngine/ExecutionEngine.h"
#include "glow/Graph/Graph.h"
#include "glow/Graph/PlaceholderBindings.h"
#include "glow/Optimizer/GraphOptimizer/GraphOptimizer.h"
#include "glow/Support/Random.h"
#include "gtest/gtest.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Signals.h"
#include <functional>
using namespace glow;
using llvm::cast;
/// This matches the signature that is used for the parameterized tests here,
/// i.e. those passing three parameters via a single ::testing::Combine() into
/// GLOW_INSTANTIATE_TEST_SUITE_P_FOR_BACKEND_COMBINED_TEST().
using ThreeIntTupleConfig = std::tuple<std::string, std::tuple<int, int, int>>;
using FourIntTupleConfig =
std::tuple<std::string, std::tuple<int, int, int, int>>;
#define SET_BACKEND_KIND_AND_THREE_INT_PARAMS(CONFIG, BACKEND_NAME, PARAM1, \
PARAM2, PARAM3) \
std::tuple<int, int, int> threeIntTupleParams; \
std::tie(BACKEND_NAME, threeIntTupleParams) = CONFIG; \
std::tie(PARAM1, PARAM2, PARAM3) = threeIntTupleParams;
#define SET_BACKEND_KIND_AND_FOUR_INT_PARAMS(CONFIG, BACKEND_KIND, PARAM1, \
PARAM2, PARAM3, PARAM4) \
std::tuple<int, int, int, int> fourIntTupleParams; \
std::tie(BACKEND_KIND, fourIntTupleParams) = CONFIG; \
std::tie(PARAM1, PARAM2, PARAM3, PARAM4) = fourIntTupleParams;
//===--------------------------------------------------------------------===//
// Convolution Parameter Sweep Tests
//===--------------------------------------------------------------------===//
/// Create a simple network that has a single fp convolution.
static FunctionTensorPair
createAndInitConvNet(glow::PlaceholderBindings &bindings,
glow::ExecutionEngine &EE, dim_t size, dim_t convDepth,
dim_t kernel, dim_t stride, dim_t pad) {
PseudoRNG PRNG;
auto &mod = EE.getModule();
Function *F = mod.createFunction("main");
auto *var = mod.createPlaceholder(ElemKind::FloatTy,
{1, size, size, convDepth}, "var", false);
bindings.allocate(var)->getHandle().initXavier(1, PRNG);
auto *conv =
F->createConv(bindings, "conv", var, convDepth, kernel, stride, pad, 1);
bindings.get(cast<Placeholder>(conv->getFilter()))->getHandle().clear(0.1);
bindings.get(cast<Placeholder>(conv->getBias()))->getHandle().clear(0.1);
auto *result = F->createSave("ret", conv);
auto *resultTensor = bindings.allocate(result->getPlaceholder());
convertPlaceholdersToConstants(F, bindings, {var, result->getPlaceholder()});
return std::make_pair(F, resultTensor);
}
/// Helper to test sweeping across a variety of configurations of a convolution
/// by comparing the results to the Interpreter given some \p allowedError.
/// \p config contains the backend to compare the Interpreter against, plus the
/// specific configuration to run for this test. \p interpElemKind and \p
/// backendElemKind are the element kinds to use for the Interpreter and
/// backend, respectively.
static void testParamSweepConv(ThreeIntTupleConfig config,
ElemKind interpElemKind,
ElemKind backendElemKind, float allowedError) {
std::string backend;
size_t size, depth, kernel;
SET_BACKEND_KIND_AND_THREE_INT_PARAMS(config, backend, size, depth, kernel)
LOG(INFO) << "Testing Conv with size: " << size << "; depth: " << depth
<< "; kernel: " << kernel << "\n";
auto boundF = std::bind(createAndInitConvNet, std::placeholders::_1,
std::placeholders::_2, size, depth, kernel,
/* stride */ 1, /* pad */ 0);
compareAgainstInterpreter(backend, boundF, interpElemKind, backendElemKind,
allowedError, parCloneCountOpt);
}
DECLARE_STATELESS_BACKEND_TEST(ConvSweepTest, ThreeIntTupleConfig);
GLOW_INSTANTIATE_TEST_SUITE_P_FOR_BACKEND_COMBINED_TEST(
SweepTest, ConvSweepTest,
::testing::Combine(/* size */ ::testing::Values(5, 7, 15),
/* depth */ ::testing::Values(8, 64),
/* kernel */ ::testing::Values(1, 3)));
/// Compare backend against the interpreter in Float.
TEST_P(ConvSweepTest, ConvTest_Float) {
ENABLED_BACKENDS(CPU, OpenCL, NNPI);
testParamSweepConv(GetParam(), ElemKind::FloatTy, ElemKind::FloatTy, 0.0001f);
}
/// Compare backend against the interpreter in Int8.
TEST_P(ConvSweepTest, ConvTest_Int8) {
ENABLED_BACKENDS(Interpreter, CPU, OpenCL, NNPI);
testParamSweepConv(GetParam(), ElemKind::FloatTy, ElemKind::Int8QTy, 0.045f);
}
/// Compare backend against the interpreter in FP16.
TEST_P(ConvSweepTest, ConvTest_Float16) {
ENABLED_BACKENDS(Interpreter, NNPI);
testParamSweepConv(GetParam(), ElemKind::FloatTy, ElemKind::Float16Ty,
0.005f);
}
//===--------------------------------------------------------------------===//
// BatchMatMul Parameter Sweep Tests
//===--------------------------------------------------------------------===//
/// Create a simple network that has a single fp batch mat mul.
static FunctionTensorPair
createAndInitBatchMatMulNet(glow::PlaceholderBindings &bindings,
glow::ExecutionEngine &EE, dim_t N, dim_t A,
dim_t Z, dim_t B) {
PseudoRNG PRNG;
auto &mod = EE.getModule();
Function *F = mod.createFunction("main");
auto *LHS = mod.createPlaceholder(ElemKind::FloatTy, {N, A, Z}, "LHS", false);
auto *RHS = mod.createPlaceholder(ElemKind::FloatTy, {N, Z, B}, "RHS", false);
bindings.allocate(LHS)->getHandle().initXavier(10, PRNG);
bindings.allocate(RHS)->getHandle().initXavier(10, PRNG);
auto *R = F->createBatchMatMul("BMM", LHS, RHS);
auto *save = F->createSave("save", R);
auto *resultTensor = bindings.allocate(save->getPlaceholder());
return std::make_pair(F, resultTensor);
}
/// Helper to test sweeping across a variety of configurations of a BatchMatMul
/// by comparing the results to the Interpreter given some \p allowedError.
/// \p config contains the backend to compare the Interpreter against, plus the
/// specific configuration to run for this test. \p interpElemKind and \p
/// backendElemKind are the element kinds to use for the Interpreter and
/// backend, respectively.
static void testParamSweepBatchMatMul(ThreeIntTupleConfig config,
ElemKind interpElemKind,
ElemKind backendElemKind,
float allowedError) {
std::string backend;
size_t N, A, Z;
SET_BACKEND_KIND_AND_THREE_INT_PARAMS(config, backend, N, A, Z);
size_t B = A;
LOG(INFO) << "\n\tTesting BatchMatMul with N: " << N << "; A: " << A
<< "; Z: " << Z << "; B: " << B << "\n";
// Multiplying LHS {N, A, Z} by RHS {N, Z, B} to get result {N, A, B}.
auto boundF = std::bind(createAndInitBatchMatMulNet, std::placeholders::_1,
std::placeholders::_2, N, A, Z, B);
compareAgainstInterpreter(backend, boundF, interpElemKind, backendElemKind,
allowedError, parCloneCountOpt);
}
DECLARE_STATELESS_BACKEND_TEST(BatchMatMulSweepTest, ThreeIntTupleConfig);
GLOW_INSTANTIATE_TEST_SUITE_P_FOR_BACKEND_COMBINED_TEST(
SweepTest, BatchMatMulSweepTest,
::testing::Combine(/* N */ ::testing::Values(1, 4, 16, 24),
/* A */ ::testing::Range(10, 16),
/* Z */ ::testing::Values(32, 64, 128, 256)));
/// Compare backend against the interpreter in Float.
TEST_P(BatchMatMulSweepTest, BatchMatMulTest_Float) {
ENABLED_BACKENDS(CPU, OpenCL, NNPI);
testParamSweepBatchMatMul(GetParam(), ElemKind::FloatTy, ElemKind::FloatTy,
0.0001f);
}
/// Compare backend against the interpreter in Int8.
TEST_P(BatchMatMulSweepTest, BatchMatMulTest_Int8) {
ENABLED_BACKENDS(Interpreter, CPU, OpenCL, NNPI);
testParamSweepBatchMatMul(GetParam(), ElemKind::FloatTy, ElemKind::Int8QTy,
0.06f);
}
/// Compare backend against the interpreter in FP16.
TEST_P(BatchMatMulSweepTest, BatchMatMulTest_Float16) {
ENABLED_BACKENDS(Interpreter, NNPI);
testParamSweepBatchMatMul(GetParam(), ElemKind::FloatTy, ElemKind::Float16Ty,
0.005f);
}
//===--------------------------------------------------------------------===//
// FullyConnected Parameter Sweep Tests
//===--------------------------------------------------------------------===//
/// Create a simple network that has a single fp FC.
static FunctionTensorPair
createAndInitFCNet(glow::PlaceholderBindings &bindings,
glow::ExecutionEngine &EE, dim_t A, dim_t Z, dim_t B) {
PseudoRNG PRNG;
auto &mod = EE.getModule();
Function *F = mod.createFunction("main");
auto *IP = mod.createPlaceholder(ElemKind::FloatTy, {A, Z}, "input", false);
auto *WC = mod.createConstant(ElemKind::FloatTy, {Z, B}, "weights");
auto *BC = mod.createConstant(ElemKind::FloatTy, {B}, "bias");
bindings.allocate(IP)->getHandle().randomize(-0.2, 0.2, mod.getPRNG());
BC->getPayloadMutable().getHandle().randomize(0, 0.000005, mod.getPRNG());
WC->getPayloadMutable().getHandle().randomize(-0.4, 0.4, mod.getPRNG());
auto *FC = F->createFullyConnected("FC", IP, WC, BC);
auto *save = F->createSave("save", FC);
auto *resultTensor = bindings.allocate(save->getPlaceholder());
return std::make_pair(F, resultTensor);
}
/// Helper to test sweeping across a variety of configurations of a FC by
/// comparing the results to the Interpreter given some \p allowedError.
/// \p config contains the backend to compare the Interpreter against, plus the
/// specific configuration to run for this test. \p interpElemKind and \p
/// backendElemKind are the element kinds to use for the Interpreter and
/// backend, respectively.
static void testParamSweepFC(ThreeIntTupleConfig config,
ElemKind interpElemKind, ElemKind backendElemKind,
float allowedError) {
std::string backend;
size_t A, Z, B;
SET_BACKEND_KIND_AND_THREE_INT_PARAMS(config, backend, A, Z, B);
LOG(INFO) << "\n\tTesting FC with A: " << A << "; Z: " << Z << "; B: " << B
<< "\n";
auto boundF = std::bind(createAndInitFCNet, std::placeholders::_1,
std::placeholders::_2, A, Z, B);
compareAgainstInterpreter(backend, boundF, interpElemKind, backendElemKind,
allowedError, parCloneCountOpt);
}
DECLARE_STATELESS_BACKEND_TEST(FCSweepTest, ThreeIntTupleConfig);
GLOW_INSTANTIATE_TEST_SUITE_P_FOR_BACKEND_COMBINED_TEST(
SweepTest, FCSweepTest,
::testing::Combine(
/* A */ ::testing::Values(1, 4, 16, 64),
/* Z */ ::testing::Values(16, 128, 256, 512, 1024, 2048, 4096),
/* B */ ::testing::Values(1, 48, 64, 256, 1024)));
/// Compare backend against the interpreter in Float.
TEST_P(FCSweepTest, FCTest_Float) {
ENABLED_BACKENDS(CPU, OpenCL, NNPI);
testParamSweepFC(GetParam(), ElemKind::FloatTy, ElemKind::FloatTy, 0.0001f);
}
/// Compare backend against the interpreter in Int8.
TEST_P(FCSweepTest, FCTest_Int8) {
ENABLED_BACKENDS(Interpreter, CPU, OpenCL, NNPI);
testParamSweepFC(GetParam(), ElemKind::FloatTy, ElemKind::Int8QTy, 0.065f);
}
/// Compare backend against the interpreter in FP16.
TEST_P(FCSweepTest, FCTest_Float16) {
ENABLED_BACKENDS(Interpreter, NNPI);
testParamSweepFC(GetParam(), ElemKind::FloatTy, ElemKind::Float16Ty, 0.005f);
}
//===--------------------------------------------------------------------===//
// Concat Parameter Sweep Tests
//===--------------------------------------------------------------------===//
/// Create a simple network that has a single fp Concat.
static FunctionTensorPair
createAndInitConcatNet(glow::PlaceholderBindings &bindings,
glow::ExecutionEngine &EE, size_t numInputs,
size_t numDims, size_t maxLength, size_t axis) {
PseudoRNG PRNG;
auto &mod = EE.getModule();
Function *F = mod.createFunction("main");
// Make leading dimensions smaller than trailing. Reduces size of tests and is
// also in line with typical tests.
std::vector<dim_t> dims(numDims, maxLength);
for (size_t i = 0; i < numDims; i++) {
dims[numDims - 1 - i] /= std::pow(2, i);
}
std::vector<NodeValue> inputs(numInputs);
for (size_t i = 0; i < numInputs; i++) {
auto *IP = mod.createPlaceholder(ElemKind::FloatTy, dims, "input", false);
bindings.allocate(IP)->getHandle().randomize(-0.2, 0.2, mod.getPRNG());
assert(IP);
inputs[i] = IP->getOutput();
}
auto *concat = F->createConcat("concat", inputs, axis);
auto *save = F->createSave("save", concat);
auto *resultTensor = bindings.allocate(save->getPlaceholder());
return std::make_pair(F, resultTensor);
}
/// Helper to test sweeping across a variety of configurations of a Concat by
/// comparing the results to the Interpreter given some \p allowedError.
/// \p config contains the backend to compare the Interpreter against, plus the
/// specific configuration to run for this test. \p interpElemKind and \p
/// backendElemKind are the element kinds to use for the Interpreter and
/// backend, respectively.
static void testParamSweepConcat(FourIntTupleConfig config,
ElemKind interpElemKind,
ElemKind backendElemKind, float allowedError) {
std::string backend;
size_t numInputs, numDims, maxLength, axis;
SET_BACKEND_KIND_AND_FOUR_INT_PARAMS(config, backend, numInputs, numDims,
maxLength, axis);
// Exit if axis outside of numDims.
if (axis >= numDims) {
return;
}
LOG(INFO) << "\n\tTesting Concat with numInputs: " << numInputs
<< "; numDims: " << numDims << "; maxLength: " << maxLength
<< "; axis: " << axis << "\n";
auto boundF =
std::bind(createAndInitConcatNet, std::placeholders::_1,
std::placeholders::_2, numInputs, numDims, maxLength, axis);
compareAgainstInterpreter(backend, boundF, interpElemKind, backendElemKind,
allowedError, parCloneCountOpt);
}
DECLARE_STATELESS_BACKEND_TEST(ConcatSweepTest, FourIntTupleConfig);
GLOW_INSTANTIATE_TEST_SUITE_P_FOR_BACKEND_COMBINED_TEST(
SweepTest, ConcatSweepTest,
::testing::Combine(/* numInputs */ ::testing::Values(1, 2, 4, 8, 16, 32, 64,
128, 192, 256),
/* numDims */ ::testing::Range(1, 4),
/* maxLength */ ::testing::Values(16, 32, 64, 128),
/* axis */ ::testing::Range(0, 3)));
/// Compare backend against the interpreter in Float.
TEST_P(ConcatSweepTest, ConcatTest_Float) {
ENABLED_BACKENDS(CPU, OpenCL, NNPI);
testParamSweepConcat(GetParam(), ElemKind::FloatTy, ElemKind::FloatTy, 0.0f);
}
/// Compare backend against the interpreter in Int8. Note that we do not use the
/// same ElemKind for the Interpreter; this is because the backend will
/// quantize/dequantize the input/result anyway, so the comparison wouldn't be
/// purely on data movement.
TEST_P(ConcatSweepTest, ConcatTest_Int8) {
ENABLED_BACKENDS(Interpreter, CPU, OpenCL, NNPI);
testParamSweepConcat(GetParam(), ElemKind::FloatTy, ElemKind::Int8QTy,
0.002f);
}
/// Compare backend against the interpreter in Float16. Note that we do not use
/// the same ElemKind for the Interpreter; this is because the backend will
/// down/up convert the input/result anyway, so the comparison wouldn't be
/// purely on data movement.
TEST_P(ConcatSweepTest, ConcatTest_Float16) {
ENABLED_BACKENDS(Interpreter, NNPI);
testParamSweepConcat(GetParam(), ElemKind::FloatTy, ElemKind::Float16Ty,
0.0001f);
}
//===--------------------------------------------------------------------===//
// SLWS Parameter Sweep Tests
//===--------------------------------------------------------------------===//
/// Create a simple network that has a single fp SLWS.
static FunctionTensorPair
createAndInitSLWSNet(glow::PlaceholderBindings &bindings,
glow::ExecutionEngine &EE, dim_t embeddingRows,
dim_t embeddingDim, dim_t numLengths, bool rowwiseQuantize,
bool fused, bool FP16, bool accumFP16) {
PseudoRNG PRNG;
auto &mod = EE.getModule();
Function *F = mod.createFunction("main");
// Initialize lengths according to the number provided by the test. Note that
// we arbitrarily set them between [80,120].
auto *lengths =
mod.createPlaceholder(ElemKind::Int32ITy, {numLengths}, "lengths", false);
auto LH = bindings.allocate(lengths)->getHandle<int32_t>();
LH.randomize(80, 120, mod.getPRNG());
// Get the sum of the lengths to then use as the size for indices and weights.
dim_t sumOfLengths = 0;
for (const int32_t &e : LH) {
sumOfLengths += e;
}
// Initialize indices to size of sum of lengths. Randomly set them to point
// somewhere inside the embedding.
auto *indices =
mod.createPlaceholder(IndexElemKind, {sumOfLengths}, "indices", false);
bindings.allocate(indices)->getHandle<sdim_t>().randomize(
0, embeddingRows - 1, mod.getPRNG());
// Xavier initialize the weights with the correct data type.
Constant *weights;
if (FP16) {
weights =
mod.createConstant(ElemKind::Float16Ty, {sumOfLengths}, "weights");
weights->getPayloadMutable().getHandle<float16_t>().initXavier(
weights->getType()->size() * 2, mod.getPRNG());
} else {
weights = mod.createConstant(ElemKind::FloatTy, {sumOfLengths}, "weights");
weights->getPayloadMutable().getHandle<float>().initXavier(
weights->getType()->size() * 2, mod.getPRNG());
}
// Create the embedding; non-RWQ versions will simply create a Constant with
// it, while RWQ versions will use its data to create a RWQ Constant
// internally in the Node constructor.
Tensor embeddingT(ElemKind::FloatTy, {embeddingRows, embeddingDim});
embeddingT.getHandle().initXavier(embeddingT.size() * 2, mod.getPRNG());
// Create the SLWS based on provided options.
Node *SLWS;
if (!rowwiseQuantize) {
auto *embeddingC = mod.createConstant("embedding", std::move(embeddingT));
SLWS = F->createSparseLengthsWeightedSum("SLWS", embeddingC, weights,
indices, lengths);
} else {
if (fused) {
const ElemKind precision =
FP16 ? ElemKind::UInt8FusedFP16QTy : ElemKind::UInt8FusedQTy;
SLWS = F->createFusedRowwiseQuantizedSparseLengthsWeightedSum(
"FRQSLWS", embeddingT, weights, indices, lengths, precision,
accumFP16);
} else {
const ElemKind precision = FP16 ? ElemKind::Float16Ty : ElemKind::FloatTy;
SLWS = F->createRowwiseQuantizedSparseLengthsWeightedSum(
"RQSLWS", embeddingT, weights, indices, lengths,
quantization::Schema::Asymmetric, precision, accumFP16);
}
}
auto *save = F->createSave("save", SLWS);
auto *resultTensor = bindings.allocate(save->getPlaceholder());
return std::make_pair(F, resultTensor);
}
/// Helper to test sweeping across a variety of configurations of a SLWS by
/// comparing the results to the Interpreter given some \p allowedError.
/// \p config contains the backend to compare the Interpreter against, plus the
/// specific configuration to run for this test. \p interpElemKind and \p
/// backendElemKind are the element kinds to use for the Interpreter and
/// backend, respectively. Pass in options for the test \p rowwiseQuantize,
/// \p fused, \p FP16, and \p accumFP16.
static void testParamSweepSLWS(ThreeIntTupleConfig config,
ElemKind interpElemKind,
ElemKind backendElemKind, float allowedError,
bool rowwiseQuantize, bool fused, bool FP16,
bool accumFP16) {
std::string backend;
size_t embeddingRows, embeddingDim, numLengths;
SET_BACKEND_KIND_AND_THREE_INT_PARAMS(config, backend, embeddingRows,
embeddingDim, numLengths);
LOG(INFO) << "\n\tTesting SLWS with embeddingRows: " << embeddingRows
<< "; embeddingDim: " << embeddingDim
<< "; numLengths: " << numLengths << "\n";
auto boundF = std::bind(createAndInitSLWSNet, std::placeholders::_1,
std::placeholders::_2, embeddingRows, embeddingDim,
numLengths, rowwiseQuantize, fused, FP16, accumFP16);
compareAgainstInterpreter(backend, boundF, interpElemKind, backendElemKind,
allowedError, parCloneCountOpt);
}
DECLARE_STATELESS_BACKEND_TEST(SLWSSweepTest, ThreeIntTupleConfig);
GLOW_INSTANTIATE_TEST_SUITE_P_FOR_BACKEND_COMBINED_TEST(
SweepTest, SLWSSweepTest,
::testing::Combine(
/* embeddingRows */ ::testing::Values(100, 1000, 10000, 100000),
/* embeddingDim */ ::testing::Values(32, 64, 96, 128),
/* numLengths */ ::testing::Values(16, 32, 64, 128, 256)));
/// Compare backend against the interpreter.
TEST_P(SLWSSweepTest, SLWS_Float) {
ENABLED_BACKENDS(CPU, NNPI);
testParamSweepSLWS(GetParam(), ElemKind::FloatTy, ElemKind::FloatTy,
0.000001f,
/* rowwiseQuantize */ false,
/* fused */ false, /* FP16 */ false,
/* accumFP16 */ false);
}
/// Compare backend against the interpreter in Float.
TEST_P(SLWSSweepTest, RWQSLWS_Float) {
ENABLED_BACKENDS(CPU, NNPI);
testParamSweepSLWS(GetParam(), ElemKind::FloatTy, ElemKind::FloatTy,
0.000001f,
/* rowwiseQuantize */ true,
/* fused */ false, /* FP16 */ false,
/* accumFP16 */ false);
}
/// Compare backend against the interpreter in Float.
TEST_P(SLWSSweepTest, FRWQSLWS_Float) {
ENABLED_BACKENDS(CPU, NNPI);
testParamSweepSLWS(GetParam(), ElemKind::FloatTy, ElemKind::FloatTy,
0.000001f,
/* rowwiseQuantize */ true,
/* fused */ true, /* FP16 */ false,
/* accumFP16 */ false);
}
/// Compare backend against the interpreter in Float.
TEST_P(SLWSSweepTest, RWQSLWS_Float16) {
// Note: not currently enabled for any open-source backends, as only the
// Interpreter supports this.
ENABLED_BACKENDS(NNPI);
testParamSweepSLWS(GetParam(), ElemKind::FloatTy, ElemKind::FloatTy,
0.000001f,
/* rowwiseQuantize */ true,
/* fused */ false, /* FP16 */ true,
/* accumFP16 */ false);
}
/// Compare backend against the interpreter in Float.
TEST_P(SLWSSweepTest, FRWQSLWS_Float16) {
// Note: not currently enabled for any open-source backends, as only the
// Interpreter supports this.
ENABLED_BACKENDS(NNPI);
testParamSweepSLWS(GetParam(), ElemKind::FloatTy, ElemKind::FloatTy,
0.000001f,
/* rowwiseQuantize */ true,
/* fused */ true, /* FP16 */ true,
/* accumFP16 */ false);
}
/// Compare backend against the interpreter in Float.
TEST_P(SLWSSweepTest, RWQSLWS_Float16_AccumFloat16) {
// Note: not currently enabled for any open-source backends, as only the
// Interpreter supports this.
ENABLED_BACKENDS(NNPI);
testParamSweepSLWS(GetParam(), ElemKind::FloatTy, ElemKind::FloatTy,
0.000001f,
/* rowwiseQuantize */ true,
/* fused */ false, /* FP16 */ true,
/* accumFP16 */ true);
}
/// Compare backend against the interpreter in Float.
TEST_P(SLWSSweepTest, FRWQSLWS_Float16_AccumFloat16) {
// Note: not currently enabled for any open-source backends, as only the
// Interpreter supports this.
ENABLED_BACKENDS(NNPI);
testParamSweepSLWS(GetParam(), ElemKind::FloatTy, ElemKind::FloatTy,
0.000001f,
/* rowwiseQuantize */ true,
/* fused */ true, /* FP16 */ true,
/* accumFP16 */ true);
}
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
llvm::sys::PrintStackTraceOnErrorSignal(argv[0]);
llvm::cl::ParseCommandLineOptions(argc, argv);
return RUN_ALL_TESTS();
}
| 43.569231 | 80 | 0.636299 | [
"vector"
] |
90b7d344d4877840d318eba63c80de820e12e3be | 4,844 | cpp | C++ | miniapps/autodiff/seq_test.cpp | ajithvallabai/mfem | 5920fbf645f328c29a9d6489f2474d989f808451 | [
"BSD-3-Clause"
] | null | null | null | miniapps/autodiff/seq_test.cpp | ajithvallabai/mfem | 5920fbf645f328c29a9d6489f2474d989f808451 | [
"BSD-3-Clause"
] | null | null | null | miniapps/autodiff/seq_test.cpp | ajithvallabai/mfem | 5920fbf645f328c29a9d6489f2474d989f808451 | [
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2010-2021, Lawrence Livermore National Security, LLC. Produced
// at the Lawrence Livermore National Laboratory. All Rights reserved. See files
// LICENSE and NOTICE for details. LLNL-CODE-806117.
//
// This file is part of the MFEM library. For more information and source code
// availability visit https://mfem.org.
//
// MFEM is free software; you can redistribute it and/or modify it under the
// terms of the BSD-3 license. We welcome feedback and contributions, see file
// CONTRIBUTING.md for details.
#include "admfem.hpp"
#include "mfem.hpp"
template<typename TDataType, typename TParamVector, typename TStateVector
, int state_size, int param_size>
class DiffusionFunctional
{
public:
TDataType operator() (TParamVector& vparam, TStateVector& uu)
{
MFEM_ASSERT(state_size==4,"ExampleFunctor state_size should be equal to 4!");
MFEM_ASSERT(param_size==2,"ExampleFunctor param_size should be equal to 2!");
auto kappa = vparam[0]; // diffusion coefficient
auto load = vparam[1]; // volumetric influx
TDataType rez = kappa*(uu[0]*uu[0]+uu[1]*uu[1]+uu[2]*uu[2])/2.0 - load*uu[3];
return rez;
}
};
template<typename TDataType, typename TParamVector, typename TStateVector,
int residual_size, int state_size, int param_size>
class DiffusionResidual
{
public:
void operator ()(TParamVector& vparam, TStateVector& uu, TStateVector& rr)
{
MFEM_ASSERT(residual_size==4,
"DiffusionResidual residual_size should be equal to 4!");
MFEM_ASSERT(state_size==4,"ExampleFunctor state_size should be equal to 4!");
MFEM_ASSERT(param_size==2,"ExampleFunctor param_size should be equal to 2!");
auto kappa = vparam[0]; // diffusion coefficient
auto load = vparam[1]; // volumetric influx
rr[0] = kappa * uu[0];
rr[1] = kappa * uu[1];
rr[2] = kappa * uu[2];
rr[3] = -load;
}
};
int main(int argc, char *argv[])
{
#ifdef MFEM_USE_ADFORWARD
std::cout<<"MFEM_USE_ADFORWARD == true"<<std::endl;
#else
std::cout<<"MFEM_USE_ADFORWARD == false"<<std::endl;
#endif
#ifdef MFEM_USE_CALIPER
cali::ConfigManager mgr;
#endif
// Caliper instrumentation
MFEM_PERF_FUNCTION;
#ifdef MFEM_USE_CALIPER
const char* cali_config = "runtime-report";
mgr.add(cali_config);
mgr.start();
#endif
mfem::Vector param(2);
param[0]=3.0; // diffusion coefficient
param[1]=2.0; // volumetric influx
mfem::Vector state(4);
state[0]=1.0; // grad_x
state[1]=2.0; // grad_y
state[2]=3.0; // grad_z
state[3]=4.0; // state value
mfem::QFunctionAutoDiff<DiffusionFunctional,4,2> adf;
mfem::Vector rr0(4);
mfem::DenseMatrix hh0(4,4);
mfem::Vector rr1(4);
mfem::DenseMatrix hh1(4,4);
MFEM_PERF_BEGIN("Grad");
adf.Grad(param,state,rr0);
MFEM_PERF_END("Grad");
MFEM_PERF_BEGIN("Hessian");
adf.Hessian(param, state, hh0);
MFEM_PERF_END("Hessian");
// dump out the results
std::cout<<"FunctionAutoDiff"<<std::endl;
std::cout<< adf.Eval(param,state)<<std::endl;
rr0.Print(std::cout);
hh0.Print(std::cout);
mfem::QVectorFuncAutoDiff<DiffusionResidual,4,4,2> rdf;
MFEM_PERF_BEGIN("Jacobian");
rdf.Jacobian(param, state, hh1);
MFEM_PERF_END("Jacobian");
std::cout<<"ResidualAutoDiff"<<std::endl;
hh1.Print(std::cout);
// using lambda expression
auto func = [](mfem::Vector& vparam,
mfem::ad::ADVectorType& uu,
mfem::ad::ADVectorType& vres)
{
// auto func = [](auto& vparam, auto& uu, auto& vres) { //c++14
auto kappa = vparam[0]; // diffusion coefficient
auto load = vparam[1]; // volumetric influx
vres[0] = kappa * uu[0];
vres[1] = kappa * uu[1];
vres[2] = kappa * uu[2];
vres[3] = -load;
};
mfem::VectorFuncAutoDiff<4,4,2> fdr(func);
MFEM_PERF_BEGIN("JacobianV");
fdr.Jacobian(param,state,
hh1); // computes the gradient of func and stores the result in hh1
MFEM_PERF_END("JacobianV");
std::cout<<"LambdaAutoDiff"<<std::endl;
hh1.Print(std::cout);
double kappa = param[0];
double load = param[1];
// using lambda expression
auto func01 = [&kappa,&load](mfem::Vector& vparam,
mfem::ad::ADVectorType& uu,
mfem::ad::ADVectorType& vres)
{
// auto func = [](auto& vparam, auto& uu, auto& vres) { //c++14
vres[0] = kappa * uu[0];
vres[1] = kappa * uu[1];
vres[2] = kappa * uu[2];
vres[3] = -load;
};
mfem::VectorFuncAutoDiff<4,4,2> fdr01(func01);
MFEM_PERF_BEGIN("Jacobian1");
fdr01.Jacobian(param,state,hh1);
MFEM_PERF_END("Jacobian1");
std::cout<<"LambdaAutoDiff 01"<<std::endl;
hh1.Print(std::cout);
#ifdef MFEM_USE_CALIPER
mgr.flush();
#endif
}
| 30.465409 | 83 | 0.642651 | [
"vector"
] |
90b9cdc406d9bec3ccc0e23661a9cc4e431be2b0 | 789 | hpp | C++ | plugins/d3d9/include/sge/d3d9/vf/convert/extra_type_visitor.hpp | cpreh/spacegameengine | 313a1c34160b42a5135f8223ffaa3a31bc075a01 | [
"BSL-1.0"
] | 2 | 2016-01-27T13:18:14.000Z | 2018-05-11T01:11:32.000Z | plugins/d3d9/include/sge/d3d9/vf/convert/extra_type_visitor.hpp | cpreh/spacegameengine | 313a1c34160b42a5135f8223ffaa3a31bc075a01 | [
"BSL-1.0"
] | null | null | null | plugins/d3d9/include/sge/d3d9/vf/convert/extra_type_visitor.hpp | cpreh/spacegameengine | 313a1c34160b42a5135f8223ffaa3a31bc075a01 | [
"BSL-1.0"
] | 3 | 2018-05-11T01:11:34.000Z | 2021-04-24T19:47:45.000Z | // Copyright Carl Philipp Reh 2006 - 2019.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef SGE_D3D9_VF_CONVERT_EXTRA_TYPE_VISITOR_HPP_INCLUDED
#define SGE_D3D9_VF_CONVERT_EXTRA_TYPE_VISITOR_HPP_INCLUDED
#include <sge/d3d9/d3dinclude.hpp>
#include <sge/renderer/vf/dynamic/color_fwd.hpp>
#include <sge/renderer/vf/dynamic/vector_fwd.hpp>
namespace sge
{
namespace d3d9
{
namespace vf
{
namespace convert
{
class extra_type_visitor
{
public:
typedef D3DDECLTYPE result_type;
result_type operator()(sge::renderer::vf::dynamic::color const &) const;
result_type operator()(sge::renderer::vf::dynamic::vector const &) const;
};
}
}
}
}
#endif
| 20.763158 | 75 | 0.751584 | [
"vector"
] |
90c0b9f3dfd904e55a3997d4bb0eebabe970f96b | 11,744 | cpp | C++ | inverse_kinematics.cpp | amphineko/cs7gvX | a5c19ba1850d93e5728d1bbd6abf6c07eee7585a | [
"MIT"
] | null | null | null | inverse_kinematics.cpp | amphineko/cs7gvX | a5c19ba1850d93e5728d1bbd6abf6c07eee7585a | [
"MIT"
] | null | null | null | inverse_kinematics.cpp | amphineko/cs7gvX | a5c19ba1850d93e5728d1bbd6abf6c07eee7585a | [
"MIT"
] | null | null | null | #include "lib/cameras/camera_tp.h"
#include "lib/kinematics/bone.h"
#include "lib/kinematics/inverse.h"
#include "lib/program.h"
#include "ozz/animation/runtime/animation.h"
#include "ozz/animation/runtime/local_to_model_job.h"
#include "ozz/animation/runtime/sampling_job.h"
#include "ozz/animation/runtime/skeleton.h"
#include "ozz/base/containers/vector.h"
#include "ozz/base/io/archive.h"
#include "ozz/base/maths/simd_math.h"
#include "ozz/base/maths/soa_transform.h"
#include "ozz/base/maths/vec_float.h"
class InverseKinematicsProgram : public Program {
public:
InverseKinematicsProgram() {
delete (FirstPersonCamera *)camera_;
camera_ = new ThirdPersonCamera(50.0f, 100.f, 150.0f, -20.0f, 270.0f);
}
bool Initialize(const std::string &window_title) {
if (!Program::Initialize(window_title, false)) {
return false;
}
shader_ = new ShaderProgram("shaders/phong.vert", "shaders/cook-torrance.frag");
if (!shader_->IsReady()) {
printf("FATAL: Failed to initialize shaders.\n");
return false;
}
shaders_.push_back(shader_);
if (!Scene::CreateFromFile("resources/models/robotic_arm/scene.gltf", arm_, textures_) ||
!Scene::CreateFromFile("resources/models/table/scene.gltf", table_, textures_) ||
!Scene::CreateFromFile("resources/models/axis/scene.gltf", axis_, textures_) ||
!Scene::CreateFromFile("resources/models/crate/scene.gltf", crate_, textures_)) {
std::cerr << "FATAL: Failed to load scene" << std::endl;
return false;
}
arm_->Initialize();
arm_->Scale(1.0f);
if (!arm_->FindByName("Shoulder", base_node_) || !arm_->FindByName("UpperArm", upper_arm_) ||
!arm_->FindByName("ForeArm", fore_arm_) || !arm_->FindByName("Hand", hand_) ||
!arm_->FindByName("Finger", finger_)) {
std::cerr << "FATAL: Failed to find animation objects" << std::endl;
return false;
}
table_->Initialize();
table_->Scale(1.0f);
table_->Translate(-4.0f, 0.0f, 1.0f);
axis_->Initialize();
axis_->Scale(0.005f);
crate_->Initialize();
crate_->Scale(10.0f);
crate_->Translate(100.0f, 0.0f, 0.0f);
SetLightCount(4);
SetLight(0, glm::vec3(0.0f, 100.0f, 150.0f), glm::vec3(0.0f));
SetLight(1, glm::vec3(-50.0f, 50.0f, 50.0f), glm::vec3(0.0f));
SetLight(2, glm::vec3(50.0f, 50.0f, -50.0f), glm::vec3(0.0f));
SetLight(3, glm::vec3(-50.0f, 50.0f, -50.0f), glm::vec3(0.0f));
InitializeKinematics();
if (!InitializeAnimation()) {
return false;
}
return glCheckError() == GL_NO_ERROR;
};
private:
Scene *arm_, *table_, *axis_, *crate_;
Node *base_node_, *upper_arm_, *fore_arm_, *hand_, *finger_;
BoneChain *chain_;
std::vector<Bone *> joints_;
BoneChain *chain_locked_;
std::vector<Bone *> joints_locked_;
bool two_bones_ = false;
ozz::animation::Animation animation_;
ozz::animation::Skeleton skeleton_;
ozz::animation::SamplingJob sampling_job_;
ozz::animation::SamplingJob::Context sampling_context_;
ozz::vector<ozz::math::SoaTransform> animation_transforms_;
ozz::animation::LocalToModelJob local_to_model_job_;
ozz::vector<ozz::math::Float4x4> animation_models_;
bool enable_animation_ = false;
float animation_speed_ = 7.5f;
float target_x = 25.0f, target_y = 50.0f, target_z = 0.0f;
bool enable_solver_ = true;
float velocity_ = 0.005f;
bool track_crate_ = false;
bool track_sine_ = false;
bool draw_end_position_ = true;
bool draw_model_ = true;
bool draw_target_ = true;
ShaderProgram *shader_;
TextureManager textures_;
void Draw() override {
Program::Draw();
// sine function animation
if (track_sine_) {
auto pi = 3.1415926535897932384626433832795;
auto t = fmod(current_frame_clock_ * 1.0f, 2.0 * pi) - pi;
target_y = float(-abs(t) * cos(pi * sin(t) / t) * 25.0f) + 100.0f;
target_z = float(t * sin(pi * .872 * sin(t) / t) * 25.0f);
}
// scripted animation
sampling_job_.ratio =
enable_animation_
? float(fmod(current_frame_clock_ / animation_speed_, animation_.duration())) / animation_.duration()
: 0.0f;
if (sampling_job_.Run() && local_to_model_job_.Run() && enable_animation_) {
ozz::math::SimdFloat4 base_position{0.0f, 0.0f, 0.0f, 1.0f};
auto position = TransformPoint(animation_models_[animation_models_.size() - 1], base_position);
auto x = position.x * 10.0f + 50.0f;
auto y = position.y * 15.0f + 25.0f;
auto z = position.z * -15.0f + 75.0f;
crate_->SetPosition(x, y - 25.0f, z);
if (track_crate_) {
target_x = x;
target_y = y;
target_z = z;
}
}
// draw
shader_->Use();
if (draw_model_) {
arm_->Draw(shader_);
}
crate_->Draw(shader_);
table_->Draw(shader_);
if (draw_end_position_) {
for (auto &joint : joints_) {
auto end = joint->GetEndPosition();
axis_->SetPosition(end.x, end.y, end.z);
float x, y, z;
glm::extractEulerAngleXYZ(joint->GetWorldTransform(), x, y, z);
axis_->SetRotation(glm::vec3(x, y, z));
axis_->Draw(shader_);
}
}
if (draw_target_) {
axis_->SetPosition(target_x, target_y, target_z);
axis_->Draw(shader_);
}
if (enable_solver_) {
if (two_bones_) {
chain_locked_->Solve(glm::vec3(target_x, target_y, target_z), float(last_frame_time_) * velocity_);
} else {
chain_->Solve(glm::vec3(target_x, target_y, target_z), float(last_frame_time_) * velocity_);
}
}
glCheckError();
}
void DrawImGui() override {
Program::DrawImGui();
ImGui::Begin("Inverse Kinematics: Settings");
ImGui::TreeNode("Solver");
ImGui::SliderFloat("Velocity", &velocity_, 0.005f, 0.01f);
ImGui::Checkbox("Enable Solver", &enable_solver_);
ImGui::Checkbox("Simple 2-bone only", &two_bones_);
ImGui::Checkbox("Track Crate", &track_crate_);
ImGui::Checkbox("Track Sine Function", &track_sine_);
ImGui::TreeNode("Target");
ImGui::SliderFloat("Target X", &target_x, -150.0f, 150.0f);
ImGui::SliderFloat("Target Y", &target_y, 0.0f, 150.0f);
ImGui::SliderFloat("Target Z", &target_z, -150.0f, 150.0f);
ImGui::TreeNode("Animation");
ImGui::Checkbox("Enable Animation", &enable_animation_);
ImGui::SliderFloat("Animation Speed", &animation_speed_, 1.0f, 10.0f);
ImGui::TreeNode("Rendering");
ImGui::Checkbox("Draw End Position", &draw_end_position_);
ImGui::Checkbox("Draw Model", &draw_model_);
ImGui::Checkbox("Draw Target", &draw_target_);
ImGui::End();
}
bool InitializeAnimation() {
if (!LoadOzzArchive("resources/models/crate/CrateAction.001.ozz", animation_)) {
std::cerr << "FATAL: Failed to load animation" << std::endl;
return false;
}
if (!LoadOzzArchive("resources/models/crate/skeleton.ozz", skeleton_)) {
std::cerr << "FATAL: Failed to load skeleton" << std::endl;
return false;
}
sampling_context_.Resize(skeleton_.num_joints());
animation_transforms_.resize(skeleton_.num_soa_joints());
sampling_job_.animation = &animation_;
sampling_job_.context = &sampling_context_;
sampling_job_.output = ozz::make_span(animation_transforms_);
sampling_job_.ratio = 1.0f;
animation_models_.resize(skeleton_.num_joints());
local_to_model_job_.skeleton = &skeleton_;
local_to_model_job_.input = ozz::make_span(animation_transforms_);
local_to_model_job_.output = ozz::make_span(animation_models_);
return true;
}
void InitializeKinematics() {
auto disabled = glm::vec2(0.0f, 0.0f);
auto speed = glm::radians(0.5f);
auto base_origin = glm::vec3(0.0f, 0.0f, 0.0f);
auto base_length = glm::vec3(0.0f, 0.0f, 5.0f);
auto base_rot_z = glm::vec2(-114514.0f, 114514.0f);
auto base = new Bone(base_origin, base_length, disabled, disabled, base_rot_z, speed, base_node_);
auto base_locked = new Bone(base_origin, base_length, disabled, disabled, disabled, speed, base_node_);
auto upper = new Bone(glm::vec3(0.0f, 0.0f, 0.0f),
glm::vec3(0.0f, 0.0f, 48.5f),
disabled,
glm::vec2(glm::radians(-45.0f), glm::radians(90.0f)),
disabled,
speed,
upper_arm_);
auto fore_origin = glm::vec3(0.0f, 0.0f, 0.0f);
auto fore_length = glm::vec3(40.0f, 0.0f, 8.0f);
auto fore = new Bone(fore_origin,
fore_length,
disabled,
glm::vec2(glm::radians(-180.0f), glm::radians(0.0f)),
disabled,
speed,
fore_arm_);
auto hand_origin = glm::vec3(0.0f, 0.0f, 0.0f);
auto hand_length = glm::vec3(12.5f, 0.0f, 0.0f);
auto hand_rot_x = glm::vec2(-114514.0f, 114514.0f);
auto hand = new Bone(hand_origin, hand_length, hand_rot_x, disabled, disabled, speed, hand_);
auto hand_locked = new Bone(hand_origin, hand_length, disabled, disabled, disabled, speed, hand_);
auto finger_origin = glm::vec3(0.0f, -3.5f, 0.0f);
auto finger_length = glm::vec3(0.0f, 0.0f, -20.0f);
auto finger = new Bone(finger_origin,
finger_length,
disabled,
glm::vec2(glm::radians(-180.0f), glm::radians(0.0f)),
disabled,
speed,
finger_);
auto finger_locked = new Bone(finger_origin, finger_length, disabled, disabled, disabled, speed, finger_);
joints_.push_back(base);
joints_.push_back(upper);
joints_.push_back(fore);
joints_.push_back(hand);
joints_.push_back(finger);
chain_ = new BoneChain(joints_);
joints_locked_.push_back(base_locked);
joints_locked_.push_back(upper);
joints_locked_.push_back(fore);
joints_locked_.push_back(hand_locked);
joints_locked_.push_back(finger_locked);
chain_locked_ = new BoneChain(joints_locked_);
}
template <typename T> static bool LoadOzzArchive(const std::string &path, T &output) {
ozz::io::File file(path.c_str(), "rb");
if (!file.opened()) {
std::cerr << "FATAL: Failed to open archive file " << path << std::endl;
return false;
}
ozz::io::IArchive archive(&file);
if (!archive.TestTag<T>()) {
return false;
}
archive >> output;
return true;
}
};
int main() {
InverseKinematicsProgram program;
if (!program.Initialize("CS7GV5: Inverse Kinematics")) {
return -1;
}
program.Run();
} | 35.373494 | 117 | 0.57672 | [
"vector",
"model"
] |
90c187c3ef574f77058f08396cea23a3113a2cb8 | 3,235 | cpp | C++ | src/tcpserversession.cpp | karthagokul/microtunnel | 78ac1c0620504481fe456725ea22d5a1a46b53fa | [
"Apache-2.0"
] | null | null | null | src/tcpserversession.cpp | karthagokul/microtunnel | 78ac1c0620504481fe456725ea22d5a1a46b53fa | [
"Apache-2.0"
] | null | null | null | src/tcpserversession.cpp | karthagokul/microtunnel | 78ac1c0620504481fe456725ea22d5a1a46b53fa | [
"Apache-2.0"
] | null | null | null | #include "tcpserversession.h"
#include "tcpclientsession.h"
TcpServerSession::TcpServerSession(TcpServerSessionListener *aListner)
:Session(aListner),mListener(aListner)
{
LOG_FUNCTION_NAME;
}
bool TcpServerSession::start(const char *aIp,const int &aPort)
{
LOG_FUNCTION_NAME;
mSockFd = socket(AF_INET, SOCK_STREAM, 0);
if (mSockFd == -1) {
LOG(ERROR)<<"Invalid Socket";
return false;
}
memset(&mServerAddr, 0,sizeof(mServerAddr));
// To avoid binding problems
int val = 1;
setsockopt(mSockFd,SOL_SOCKET,SO_REUSEADDR,&val,sizeof(int));
mServerAddr.sin_family = AF_INET;
mServerAddr.sin_addr.s_addr = inet_addr(aIp);
mServerAddr.sin_port = htons(aPort);
if ((bind(mSockFd,(struct sockaddr*)&mServerAddr, sizeof(mServerAddr))) != 0)
{
LOG(ERROR)<<"Bind Failed";
return false;
}
mCleanupThread=new std::thread(&TcpServerSession::cleanupThread,this);
mEventThread=new std::thread(&TcpServerSession::eventLoop,this);
return true;
}
TcpServerSession::~TcpServerSession()
{
LOG_FUNCTION_NAME;
stop();
}
bool TcpServerSession::stop()
{
LOG_FUNCTION_NAME;
mMutex.lock();
if(mSockFd>=0)
{
//Look at the client shutdown calls
close(mSockFd);
mSockFd=-1;
}
setStatus(Disconnected);
if(mCleanupThread)
{
mCleanupThread->detach();
delete mCleanupThread;
mCleanupThread=0;
}
if(mEventThread)
{
mEventThread->detach();
delete mEventThread;
mEventThread=0;
}
mMutex.unlock();
return true;
}
void TcpServerSession::eventLoop()
{
LOG_FUNCTION_NAME;
while(1)
{
// Now server is ready to listen and verification
if ((listen(mSockFd, 5)) != 0) {
LOG(ERROR)<<"Listen Failed";
exit(0);
}
setStatus(Listening);
int len = sizeof(mClientAddr);
// Accept the data packet from client and verification
int connfd = accept(mSockFd, (struct sockaddr*)&mClientAddr, (socklen_t*)&len);
if (connfd < 0) {
LOG(ERROR)<<"Accept Failed";
exit(0);
}
TcpClientSession *s=new TcpClientSession(0);
s->setSocketDescriptor(connfd);
mActiveClients.push_back(s);
if(mListener)
mListener->newConnection(s);
}
}
void TcpServerSession::cleanupThread()
{
LOG_FUNCTION_NAME;
while(1)
{
LOG(DEBUG)<<"Number of Total Clients"<<mActiveClients.size();
std::this_thread::sleep_for(std::chrono::seconds( 5) );
//Let's iterate through the sessions and see if any of them has been disconnected, if so , free up.
for (std::vector<TcpClientSession *>::iterator i=mActiveClients.begin(); i!=mActiveClients.end(); i++)
{
TcpClientSession *t=*i;
if(t && t->status()==Disconnected)
{
LOG(DEBUG)<<"Cleaning up an inactive Session";
i=mActiveClients.erase(i);
delete t;
i--;
}
else
{
LOG(DEBUG)<<"T Status"<<t->status();
}
}
}
}
| 24.323308 | 110 | 0.590726 | [
"vector"
] |
90c3bb71c1aded40d7db4fde015dca95455489d4 | 6,161 | cc | C++ | chrome/browser/net/dns_probe_test_util.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 14,668 | 2015-01-01T01:57:10.000Z | 2022-03-31T23:33:32.000Z | chrome/browser/net/dns_probe_test_util.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 86 | 2015-10-21T13:02:42.000Z | 2022-03-14T07:50:50.000Z | chrome/browser/net/dns_probe_test_util.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 5,941 | 2015-01-02T11:32:21.000Z | 2022-03-31T16:35:46.000Z | // Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/net/dns_probe_test_util.h"
#include <stdint.h>
#include <utility>
#include "chrome/browser/net/dns_probe_runner.h"
#include "net/base/ip_address.h"
#include "net/base/network_isolation_key.h"
#include "net/dns/public/resolve_error_info.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace chrome_browser_net {
namespace {
static absl::optional<net::AddressList> AddressListForResponse(
FakeHostResolver::Response response) {
absl::optional<net::AddressList> resolved_addresses;
switch (response) {
case FakeHostResolver::kNoResponse:
break;
case FakeHostResolver::kEmptyResponse:
resolved_addresses = net::AddressList();
break;
case FakeHostResolver::kOneAddressResponse:
resolved_addresses =
net::AddressList(net::IPEndPoint(net::IPAddress(192, 168, 1, 1), 0));
break;
}
return resolved_addresses;
}
} // namespace
FakeHostResolver::SingleResult::SingleResult(
int32_t result,
net::ResolveErrorInfo resolve_error_info,
Response response)
: result(result),
resolve_error_info(resolve_error_info),
response(response) {
DCHECK(result == net::OK || result == net::ERR_NAME_NOT_RESOLVED);
}
FakeHostResolver::FakeHostResolver(
mojo::PendingReceiver<network::mojom::HostResolver> resolver_receiver,
std::vector<SingleResult> result_list)
: receiver_(this, std::move(resolver_receiver)),
result_list_(result_list) {}
FakeHostResolver::FakeHostResolver(
mojo::PendingReceiver<network::mojom::HostResolver> resolver_receiver,
int32_t result,
net::ResolveErrorInfo resolve_error_info,
Response response)
: FakeHostResolver(std::move(resolver_receiver),
{SingleResult(result, resolve_error_info, response)}) {}
FakeHostResolver::~FakeHostResolver() = default;
void FakeHostResolver::ResolveHost(
const net::HostPortPair& host,
const net::NetworkIsolationKey& network_isolation_key,
network::mojom::ResolveHostParametersPtr optional_parameters,
mojo::PendingRemote<network::mojom::ResolveHostClient>
pending_response_client) {
EXPECT_TRUE(network_isolation_key.IsTransient());
const SingleResult& cur_result = result_list_[next_result_];
if (next_result_ + 1 < result_list_.size())
next_result_++;
mojo::Remote<network::mojom::ResolveHostClient> response_client(
std::move(pending_response_client));
response_client->OnComplete(cur_result.result, cur_result.resolve_error_info,
AddressListForResponse(cur_result.response));
}
void FakeHostResolver::MdnsListen(
const net::HostPortPair& host,
net::DnsQueryType query_type,
mojo::PendingRemote<network::mojom::MdnsListenClient> response_client,
MdnsListenCallback callback) {
NOTREACHED();
}
HangingHostResolver::HangingHostResolver(
mojo::PendingReceiver<network::mojom::HostResolver> resolver_receiver)
: receiver_(this, std::move(resolver_receiver)) {}
HangingHostResolver::~HangingHostResolver() = default;
void HangingHostResolver::ResolveHost(
const net::HostPortPair& host,
const net::NetworkIsolationKey& network_isolation_key,
network::mojom::ResolveHostParametersPtr optional_parameters,
mojo::PendingRemote<network::mojom::ResolveHostClient> response_client) {
EXPECT_TRUE(network_isolation_key.IsTransient());
// Intentionally do not call response_client->OnComplete, but hang onto the
// |response_client| since destroying that also causes the mojo
// set_connection_error_handler handler to be called.
response_client_.Bind(std::move(response_client));
}
void HangingHostResolver::MdnsListen(
const net::HostPortPair& host,
net::DnsQueryType query_type,
mojo::PendingRemote<network::mojom::MdnsListenClient> response_client,
MdnsListenCallback callback) {
NOTREACHED();
}
FakeHostResolverNetworkContext::FakeHostResolverNetworkContext(
std::vector<FakeHostResolver::SingleResult> current_config_result_list,
std::vector<FakeHostResolver::SingleResult> google_config_result_list)
: current_config_result_list_(std::move(current_config_result_list)),
google_config_result_list_(std::move(google_config_result_list)) {}
FakeHostResolverNetworkContext::~FakeHostResolverNetworkContext() = default;
void FakeHostResolverNetworkContext::CreateHostResolver(
const absl::optional<net::DnsConfigOverrides>& config_overrides,
mojo::PendingReceiver<network::mojom::HostResolver> receiver) {
ASSERT_TRUE(config_overrides);
if (!config_overrides->nameservers) {
if (!current_config_resolver_) {
current_config_resolver_ = std::make_unique<FakeHostResolver>(
std::move(receiver), current_config_result_list_);
}
} else {
if (!google_config_resolver_) {
google_config_resolver_ = std::make_unique<FakeHostResolver>(
std::move(receiver), google_config_result_list_);
}
}
}
HangingHostResolverNetworkContext::HangingHostResolverNetworkContext() =
default;
HangingHostResolverNetworkContext::~HangingHostResolverNetworkContext() =
default;
void HangingHostResolverNetworkContext::CreateHostResolver(
const absl::optional<net::DnsConfigOverrides>& config_overrides,
mojo::PendingReceiver<network::mojom::HostResolver> receiver) {
resolver_ = std::make_unique<HangingHostResolver>(std::move(receiver));
}
FakeDnsConfigChangeManager::FakeDnsConfigChangeManager(
mojo::PendingReceiver<network::mojom::DnsConfigChangeManager> receiver)
: receiver_(this, std::move(receiver)) {}
FakeDnsConfigChangeManager::~FakeDnsConfigChangeManager() = default;
void FakeDnsConfigChangeManager::RequestNotifications(
mojo::PendingRemote<network::mojom::DnsConfigChangeManagerClient> client) {
ASSERT_FALSE(client_);
client_.Bind(std::move(client));
}
void FakeDnsConfigChangeManager::SimulateDnsConfigChange() {
ASSERT_TRUE(client_);
client_->OnDnsConfigChanged();
}
} // namespace chrome_browser_net
| 36.02924 | 79 | 0.764162 | [
"vector"
] |
90c410ed66a05b6b1e53eae2d27ebc727faa0a5e | 12,322 | cc | C++ | python/jittor/src/parallel_compiler.cc | Exusial/jittor | eca21d5bba5098bce4f492fa44908677b6e76588 | [
"Apache-2.0"
] | 2,571 | 2020-03-20T03:38:35.000Z | 2022-03-31T08:20:05.000Z | python/jittor/src/parallel_compiler.cc | Exusial/jittor | eca21d5bba5098bce4f492fa44908677b6e76588 | [
"Apache-2.0"
] | 197 | 2020-03-20T04:11:47.000Z | 2022-03-31T10:14:24.000Z | python/jittor/src/parallel_compiler.cc | Exusial/jittor | eca21d5bba5098bce4f492fa44908677b6e76588 | [
"Apache-2.0"
] | 284 | 2020-03-20T03:53:15.000Z | 2022-03-28T07:20:32.000Z | // ***************************************************************
// Copyright (c) 2021 Jittor. All Rights Reserved.
// Maintainers: Dun Liang <randonlang@gmail.com>.
// This file is subject to the terms and conditions defined in
// file 'LICENSE.txt', which is part of this source code package.
// ***************************************************************
#include <atomic>
#include <chrono>
#include <thread>
#include <tuple>
#include <mutex>
#include <condition_variable>
#include <iomanip>
#include "parallel_compiler.h"
#include "op_compiler.h"
#include "executor.h"
#include "lock.h"
#include "opt/jit_searcher.h"
#include "fused_op.h"
namespace jittor {
DEFINE_FLAG(int, use_parallel_op_compiler, 16, "Number of threads that parallel op comiler used, default 16, set this value to 0 will disable parallel op compiler.");
// from log.cc
EXTERN_LIB int segfault_happen;
// simple thread used for parallel compilation
struct SimpleThread {
int id;
typedef std::function<void(int)> Func;
Func func;
std::mutex mtx;
std::condition_variable cv;
std::thread thread;
void run() {
get_thread_name() = "C"+S(id);
try {
std::unique_lock<std::mutex> lck(mtx);
if (func)
func(id);
while (true) {
cv.wait(lck);
if (func) {
func(id);
} else
return;
}
} catch (const std::exception& e) {
LOGe << e.what();
}
}
void launch_one(Func func) {
std::unique_lock<std::mutex> lck(mtx);
this->func = func;
cv.notify_all();
}
SimpleThread(int id) : id(id), func(nullptr), thread(&SimpleThread::run, this) {}
~SimpleThread() {
join();
}
void join() {
if (thread.joinable()) {
launch_one(nullptr);
thread.join();
}
}
};
struct SimpleThreads;
EXTERN_LIB SimpleThreads threads;
EXTERN_LIB vector<void(*)()> cleanup_callback;
struct SimpleThreads {
list<SimpleThread> threads;
static void stop() {
jittor::threads.threads.clear();
}
void create_threads(int n) {
if (threads.size()) return;
for (int i=0; i<n; i++)
threads.emplace_back(i);
cleanup_callback.push_back(&stop);
}
void wait_all() {
for (auto& t : threads) {
auto start = clock();
int ok = 0;
while (clock()<start+5*CLOCKS_PER_SEC) {
if (t.mtx.try_lock()) {
t.mtx.unlock();
ok = 1;
break;
}
using namespace std::chrono_literals;
std::this_thread::sleep_for(1ms);
}
if (!ok) {
LOGw << "Compile thread timeout, ignored.";
}
}
}
void launch_all(int active_thread, SimpleThread::Func func) {
if (active_thread == 1) {
func(0);
return;
}
for (auto& t : threads) {
t.launch_one(func);
active_thread--;
if (!active_thread)
return;
}
}
} threads;
static int last_compiled_op_num = 0;
static int not_compile_window = 0;
void parallel_compile_all_ops(vector<int>& queue, vector<int>& range, FusedOp& fused_op, vector<int>& fuse_ops, vector<Op*>& ops, int64 tt) {
// jit_search_kernel require compile at runtime
if (jit_search_kernel || !use_parallel_op_compiler || not_compile_window > 100000)
return;
// try not use parallel compile if no op needs compile
if (last_compiled_op_num != jit_key_mapper.size()) {
not_compile_window = 0;
last_compiled_op_num = jit_key_mapper.size();
} else {
not_compile_window += queue.size();
}
vector<int> op_needs_compile;
string_view_map<int> map;
vector<unique_ptr<FusedOp>> fop_needs_compile;
auto& jkl = get_jk();
for (uint rid=0; rid<queue.size(); rid++) {
int root = queue[rid];
Op* op = ops[root];
bool is_fused_op = false;
try {
if (op->type() != OpType::other) {
op = &fused_op;
is_fused_op = true;
int ll = (rid<queue.size()-1)?range[queue.size()-rid-2]:0, rr = range[queue.size()-rid-1];
root = fuse_ops[rr-1];
load_fused_op(fused_op, fuse_ops, ops, ll, rr, tt);
}
LOGvvv << "Check op needs compile:" << op;
op->do_prepare(jkl);
if (jkl.empty()) continue;
const char* jit_key = jkl.to_cstring();
auto iter = jit_key_mapper.find(jit_key);
if (iter != jit_key_mapper.end()) continue;
auto iter2 = map.find(jit_key);
if (iter2 != map.end()) continue;
map[jit_key] = 1;
if (is_fused_op) {
op_needs_compile.push_back(-1-(int)fop_needs_compile.size());
fop_needs_compile.emplace_back(std::make_unique<FusedOp>(fused_op));
} else {
op_needs_compile.push_back(rid);
}
LOGvv << "Op needs compile:" << op;
} catch (const std::exception& e) {
// log jit_key and file location
op->do_prepare(jkl);
string jit_src_path = Op::get_filename_from_jit_key(jkl.to_cstring(), ".cc");
LOGe << "[Error] source file location:" << jit_src_path;
if (is_fused_op) {
LOGf << "Compile fused operator(" >> rid >> '/' >> queue.size() >> ")"
<< "failed:" << fused_op.ops << "\n\nReason: " >> e.what();
} else
LOGf << "Compile operator(" >> rid >> '/' >> queue.size() >> ")"
<< "failed:" << op << "\n\nReason: " >> e.what();
}
}
// if too less op needs compile, don't use parallel compiler
// if (op_needs_compile.size() < 3) return;
if (op_needs_compile.size() == 0) return;
static int thread_num = std::max(1, std::min(use_parallel_op_compiler,
int(mem_info.total_cpu_ram/(1024ll*1024*1024*3))));
#ifdef NODE_MEMCHECK
// only use one thread in debug mode
// because global id map has no lock
thread_num = 1;
#endif
static std::atomic<int> ai;
static volatile int has_error;
static vector<vector<std::tuple<int,int,void*,string>>> op_entrys(thread_num);
// <int,int,void*,string> represents: task id, is_fused_op, entry or context, new_jit_key
threads.create_threads(thread_num);
static std::mutex entry_lock;
ai = 0;
has_error = 0;
int n = op_needs_compile.size();
LOGvv << "Total number of op needs compile" << op_needs_compile.size()
<< "thread_num:" << thread_num;
// backup number
auto bk_var = Var::number_of_lived_vars, bk_op = Op::number_of_lived_ops;
jittor::lock_guard lg;
auto func = [&](int tid) {
auto& entrys = op_entrys.at(tid);
entrys.clear();
auto& jkl = get_jk();
while (!has_error && !segfault_happen) {
int i = ai++;
if (i >= n) break;
int rid = op_needs_compile[i];
Op* op;
bool is_fused_op = rid<0;
try {
if (!is_fused_op) {
int root = queue[rid];
op = ops[root];
LOGvv << "Compile Op:" << op;
op->do_prepare(jkl);
auto op_entry = OpCompiler::do_compile(op);
entrys.emplace_back(std::make_tuple(i, 0, (void*)op_entry, op->get_jit_key(jkl)));
} else {
FusedOp& fused_op = *fop_needs_compile[-rid-1];
op = &fused_op;
LOGvv << "Compile FusedOp:" << op;
LOGV(11) << "FusedOps:" << fused_op.ops;
fused_op.context = new FusedOpContext();
fused_op.context->setup(&fused_op);
fused_op.do_prepare(jkl);
auto op_entry = OpCompiler::do_compile(op);
fused_op.context->entry = op_entry;
entrys.emplace_back(std::make_tuple(i, 1, (void*)fused_op.context, op->get_jit_key(jkl)));
// compile relay operators
for (auto& vrg : fused_op.context->vrm.relay_groups) {
for (auto& orc : vrg.oprcs) {
orc.op->do_prepare(jkl);
bool needs_compile;
{
std::lock_guard<std::mutex> lock(entry_lock);
auto iter = jit_ops.find(jkl.to_cstring());
needs_compile = (iter == jit_ops.end());
if (needs_compile) {
jit_ops[jkl.to_cstring()] = nullptr;
}
}
if (!needs_compile) continue;
string s = jkl.to_string();
auto op_entry = OpCompiler::do_compile(orc.op);
{
std::lock_guard<std::mutex> lock(entry_lock);
jit_ops[s] = op_entry;
}
}
}
}
} catch (const std::exception& e) {
// log jit_key and file location
op->do_prepare(jkl);
string jit_src_path = Op::get_filename_from_jit_key(jkl.to_cstring(), ".cc");
LOGe << "[Error] source file location:" << jit_src_path;
if (is_fused_op) {
LOGe << "Compile fused operator(" >> i >> '/' >> n >> ")"
<< "failed:" << ((FusedOp*)op)->ops << "\n\nReason: " >> e.what();
} else
LOGe << "Compile operator(" >> i >> '/' >> n >> ")"
<< "failed:" << op << "\n\nReason: " >> e.what();
has_error = 1;
break;
}
}
}; // end of threads.launch_all
typedef std::chrono::high_resolution_clock Time;
auto start = Time::now();
int active_threads = std::min(thread_num, (int)op_needs_compile.size());
threads.launch_all(active_threads, func);
int prev_i = 0;
bool change_line = false;
int sleep_us = 10;
while (prev_i < n && !has_error && !segfault_happen) {
int i = std::max(std::min(ai-active_threads, n), 0);
if (i == prev_i) {
// std::this_thread::sleep_for(std::chrono::milliseconds(100));
std::this_thread::sleep_for(std::chrono::microseconds(sleep_us));
sleep_us = std::min(sleep_us*2, 1000000); // max 0.1s
continue;
}
prev_i = i;
auto diff = (Time::now() - start).count();
if (diff > 2e9) {
if (!change_line) {
std::cerr << "\n";
change_line = true;
}
// delay output progress in 2s
float eta = diff / 1e9 / i * (n-i);
std::cerr << "Compiling Operators(" << i << '/' << n << ")"
<< " used: " << std::setprecision(3) << std::setw(4) << diff/1e9 << "s eta: "
<< std::setprecision(3) << std::setw(4) << eta << "s \r";
}
}
if (change_line)
std::cerr << std::endl;
Var::number_of_lived_vars = bk_var; Op::number_of_lived_ops = bk_op;
if (segfault_happen) {
LOGe << "Segfault happen, main thread exit";
threads.wait_all();
exit(1);
}
if (has_error) {
threads.wait_all();
LOGf << "Error happend during compilation, see error above.";
}
// fill all op entry
for (int i=0; i<active_threads; i++) {
auto& v = op_entrys[i];
for (auto& t : v) {
auto& prev_jit_key = map.holder.at(std::get<0>(t));
int is_fused_op = std::get<1>(t);
auto& new_jit_key = std::get<3>(t);
if (is_fused_op)
jit_fused_ops[new_jit_key] = jit_fused_ops[prev_jit_key] = (FusedOpContext*)std::get<2>(t);
else
jit_ops[new_jit_key] = jit_ops[prev_jit_key] = (jit_op_entry_t)std::get<2>(t);
jit_key_mapper[prev_jit_key] = new_jit_key;
}
}
}
} // jittor
| 35.612717 | 166 | 0.514689 | [
"vector"
] |
90ca6a774680a8ae2e9a8ccc56a8495f9288e800 | 4,571 | cpp | C++ | test/fuzz/comparator_deep_blocks_first_test.cpp | stefanomil/SPIRV-Tools | 57abfd88c57ef1b6e77349aa16b2d5a1616c2100 | [
"Apache-2.0"
] | null | null | null | test/fuzz/comparator_deep_blocks_first_test.cpp | stefanomil/SPIRV-Tools | 57abfd88c57ef1b6e77349aa16b2d5a1616c2100 | [
"Apache-2.0"
] | null | null | null | test/fuzz/comparator_deep_blocks_first_test.cpp | stefanomil/SPIRV-Tools | 57abfd88c57ef1b6e77349aa16b2d5a1616c2100 | [
"Apache-2.0"
] | null | null | null | // Copyright (c) 2020 Google LLC
//
// 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 "source/fuzz/comparator_deep_blocks_first.h"
#include "source/fuzz/fact_manager/fact_manager.h"
#include "source/fuzz/pseudo_random_generator.h"
#include "source/fuzz/transformation_context.h"
#include "test/fuzz/fuzz_test_util.h"
namespace spvtools {
namespace fuzz {
namespace {
std::string shader = R"(
OpCapability Shader
%1 = OpExtInstImport "GLSL.std.450"
OpMemoryModel Logical GLSL450
OpEntryPoint Fragment %2 "main"
OpExecutionMode %2 OriginUpperLeft
OpSource ESSL 310
%3 = OpTypeVoid
%4 = OpTypeFunction %3
%5 = OpTypeBool
%6 = OpConstantTrue %5
%7 = OpTypeInt 32 1
%8 = OpTypePointer Function %7
%9 = OpConstant %7 1
%10 = OpConstant %7 10
%11 = OpConstant %7 2
%2 = OpFunction %3 None %4
%12 = OpLabel
OpSelectionMerge %13 None
OpBranchConditional %6 %14 %15
%14 = OpLabel
OpBranch %13
%15 = OpLabel
OpBranch %16
%16 = OpLabel
OpLoopMerge %17 %18 None
OpBranch %19
%19 = OpLabel
OpBranchConditional %6 %20 %17
%20 = OpLabel
OpSelectionMerge %21 None
OpBranchConditional %6 %22 %23
%22 = OpLabel
OpBranch %21
%23 = OpLabel
OpBranch %21
%21 = OpLabel
OpBranch %18
%18 = OpLabel
OpBranch %16
%17 = OpLabel
OpBranch %13
%13 = OpLabel
OpReturn
OpFunctionEnd
)";
TEST(ComparatorDeepBlocksFirstTest, Compare) {
const auto env = SPV_ENV_UNIVERSAL_1_5;
const auto consumer = nullptr;
const auto context = BuildModule(env, consumer, shader, kFuzzAssembleOption);
ASSERT_TRUE(IsValid(env, context.get()));
spvtools::ValidatorOptions validator_options;
TransformationContext transformation_context(
MakeUnique<FactManager>(context.get()), validator_options);
auto is_deeper = ComparatorDeepBlocksFirst(context.get());
// The block ids and the corresponding depths are:
// 12, 13 -> depth 0
// 14, 15, 16, 17 -> depth 1
// 18, 19, 20, 21 -> depth 2
// 22, 23 -> depth 3
// Perform some comparisons and check that they return true iff the first
// block is deeper than the second.
ASSERT_FALSE(is_deeper(12, 12));
ASSERT_FALSE(is_deeper(12, 13));
ASSERT_FALSE(is_deeper(12, 14));
ASSERT_FALSE(is_deeper(12, 18));
ASSERT_FALSE(is_deeper(12, 22));
ASSERT_TRUE(is_deeper(14, 12));
ASSERT_FALSE(is_deeper(14, 15));
ASSERT_FALSE(is_deeper(15, 14));
ASSERT_FALSE(is_deeper(14, 18));
ASSERT_TRUE(is_deeper(18, 12));
ASSERT_TRUE(is_deeper(18, 16));
}
TEST(ComparatorDeepBlocksFirstTest, Sort) {
const auto env = SPV_ENV_UNIVERSAL_1_5;
const auto consumer = nullptr;
const auto context = BuildModule(env, consumer, shader, kFuzzAssembleOption);
ASSERT_TRUE(IsValid(env, context.get()));
spvtools::ValidatorOptions validator_options;
TransformationContext transformation_context(
MakeUnique<FactManager>(context.get()), validator_options);
// Check that, sorting using the comparator, the blocks are ordered from more
// deeply nested to less deeply nested.
// 17 has depth 1, 20 has depth 2, 13 has depth 0.
std::vector<opt::BasicBlock*> blocks = {context->get_instr_block(17),
context->get_instr_block(20),
context->get_instr_block(13)};
std::sort(blocks.begin(), blocks.end(),
ComparatorDeepBlocksFirst(context.get()));
// Check that the blocks are in the correct order.
ASSERT_EQ(blocks[0]->id(), 20);
ASSERT_EQ(blocks[1]->id(), 17);
ASSERT_EQ(blocks[2]->id(), 13);
}
} // namespace
} // namespace fuzz
} // namespace spvtools
| 34.89313 | 79 | 0.631372 | [
"vector"
] |
90d3bdd78c04795511137e662ade49c74e095025 | 4,392 | cpp | C++ | src/backend/gporca/libnaucrates/src/parser/CParseHandlerCostParams.cpp | bradfordb-vmware/gpdb | 5cc23bd1df4133aaa7a80174f5b0950933a83cc2 | [
"PostgreSQL",
"Apache-2.0"
] | 5,535 | 2015-10-28T01:05:40.000Z | 2022-03-30T13:46:53.000Z | src/backend/gporca/libnaucrates/src/parser/CParseHandlerCostParams.cpp | bradfordb-vmware/gpdb | 5cc23bd1df4133aaa7a80174f5b0950933a83cc2 | [
"PostgreSQL",
"Apache-2.0"
] | 9,369 | 2015-10-28T07:48:01.000Z | 2022-03-31T23:56:42.000Z | src/backend/gporca/libnaucrates/src/parser/CParseHandlerCostParams.cpp | bradfordb-vmware/gpdb | 5cc23bd1df4133aaa7a80174f5b0950933a83cc2 | [
"PostgreSQL",
"Apache-2.0"
] | 1,800 | 2015-10-28T01:08:25.000Z | 2022-03-29T13:29:36.000Z | //---------------------------------------------------------------------------
// Greenplum Database
// Copyright (C) 2013 EMC Corp.
//
// @filename:
// CParseHandlerCostParams.cpp
//
// @doc:
// Implementation of the SAX parse handler class for parsing cost parameters.
//
//---------------------------------------------------------------------------
#include "naucrates/dxl/parser/CParseHandlerCostParams.h"
#include "gpdbcost/CCostModelParamsGPDB.h"
#include "naucrates/dxl/parser/CParseHandlerCostParam.h"
#include "naucrates/dxl/parser/CParseHandlerFactory.h"
#include "naucrates/dxl/parser/CParseHandlerManager.h"
using namespace gpdxl;
using namespace gpopt;
//---------------------------------------------------------------------------
// @function:
// CParseHandlerCostParams::CParseHandlerCostParams
//
// @doc:
// Ctor
//
//---------------------------------------------------------------------------
CParseHandlerCostParams::CParseHandlerCostParams(
CMemoryPool *mp, CParseHandlerManager *parse_handler_mgr,
CParseHandlerBase *parse_handler_root)
: CParseHandlerBase(mp, parse_handler_mgr, parse_handler_root),
m_cost_model_params(nullptr)
{
}
//---------------------------------------------------------------------------
// @function:
// CParseHandlerCostParams::~CParseHandlerCostParams
//
// @doc:
// Dtor
//
//---------------------------------------------------------------------------
CParseHandlerCostParams::~CParseHandlerCostParams()
{
CRefCount::SafeRelease(m_cost_model_params);
}
//---------------------------------------------------------------------------
// @function:
// CParseHandlerCostParams::StartElement
//
// @doc:
// Invoked by Xerces to process an opening tag
//
//---------------------------------------------------------------------------
void
CParseHandlerCostParams::StartElement(const XMLCh *const element_uri,
const XMLCh *const element_local_name,
const XMLCh *const element_qname,
const Attributes &attrs)
{
if (0 ==
XMLString::compareString(CDXLTokens::XmlstrToken(EdxltokenCostParams),
element_local_name))
{
// as of now, we only parse params of GPDB cost model
m_cost_model_params = GPOS_NEW(m_mp) CCostModelParamsGPDB(m_mp);
}
else if (0 == XMLString::compareString(
CDXLTokens::XmlstrToken(EdxltokenCostParam),
element_local_name))
{
GPOS_ASSERT(nullptr != m_cost_model_params);
// start new search stage
CParseHandlerBase *parse_handler_cost_params =
CParseHandlerFactory::GetParseHandler(
m_mp, CDXLTokens::XmlstrToken(EdxltokenCostParam),
m_parse_handler_mgr, this);
m_parse_handler_mgr->ActivateParseHandler(parse_handler_cost_params);
// store parse handler
this->Append(parse_handler_cost_params);
parse_handler_cost_params->startElement(element_uri, element_local_name,
element_qname, attrs);
}
else
{
CWStringDynamic *str = CDXLUtils::CreateDynamicStringFromXMLChArray(
m_parse_handler_mgr->GetDXLMemoryManager(), element_local_name);
GPOS_RAISE(gpdxl::ExmaDXL, gpdxl::ExmiDXLUnexpectedTag,
str->GetBuffer());
}
}
//---------------------------------------------------------------------------
// @function:
// CParseHandlerCostParams::EndElement
//
// @doc:
// Invoked by Xerces to process a closing tag
//
//---------------------------------------------------------------------------
void
CParseHandlerCostParams::EndElement(const XMLCh *const, // element_uri,
const XMLCh *const element_local_name,
const XMLCh *const // element_qname
)
{
if (0 !=
XMLString::compareString(CDXLTokens::XmlstrToken(EdxltokenCostParams),
element_local_name))
{
CWStringDynamic *str = CDXLUtils::CreateDynamicStringFromXMLChArray(
m_parse_handler_mgr->GetDXLMemoryManager(), element_local_name);
GPOS_RAISE(gpdxl::ExmaDXL, gpdxl::ExmiDXLUnexpectedTag,
str->GetBuffer());
}
const ULONG length = this->Length();
for (ULONG ul = 0; ul < length; ul++)
{
CParseHandlerCostParam *parse_handler_cost_params =
dynamic_cast<CParseHandlerCostParam *>((*this)[ul]);
m_cost_model_params->SetParam(
parse_handler_cost_params->GetName(),
parse_handler_cost_params->Get(),
parse_handler_cost_params->GetLowerBoundVal(),
parse_handler_cost_params->GetUpperBoundVal());
}
// deactivate handler
m_parse_handler_mgr->DeactivateHandler();
}
// EOF
| 30.082192 | 78 | 0.616576 | [
"model"
] |
90dc05bd7de193281b0aac838903e164da767761 | 24,493 | hpp | C++ | include/modes.hpp | GoldFeniks/Acoustic | 44122f7a1d815aeeb4f06b60342c8db932a806f3 | [
"MIT"
] | 4 | 2019-12-06T21:11:59.000Z | 2020-08-05T11:11:12.000Z | include/modes.hpp | GoldFeniks/Acoustic | 44122f7a1d815aeeb4f06b60342c8db932a806f3 | [
"MIT"
] | 3 | 2021-01-31T14:09:41.000Z | 2021-02-07T05:48:05.000Z | include/modes.hpp | GoldFeniks/Ample | 44122f7a1d815aeeb4f06b60342c8db932a806f3 | [
"MIT"
] | null | null | null | #pragma once
#include <tuple>
#include <mutex>
#include <thread>
#include <cstddef>
#include <istream>
#include <algorithm>
#include <type_traits>
#include "normal_modes.h"
#include "utils/types.hpp"
#include "utils/utils.hpp"
#include "utils/assert.hpp"
#include "utils/callback.hpp"
#include "utils/interpolation.hpp"
namespace ample {
template<typename T>
class config;
namespace _impl {
template<typename T, typename V>
struct modes_copier {
static void copy(const NormalModes& n_m, types::vector3d_t<V>& k_j, types::vector4d_t<T>& phi_j,
const size_t& i, const size_t& j) {
for (size_t k = 0; k < std::min(n_m.khs.size(), k_j.size()); ++k) {
k_j[k][i][j] = V(n_m.khs[k], n_m.mattenuation[k]);
phi_j[k][i][j] = std::move(n_m.mfunctions_zr[k]);
}
}
static void copy(const NormalModes& n_m, types::vector2d_t<V>& k_j, types::vector3d_t<T>& phi_j,
const size_t& i) {
for (size_t k = 0; k < std::min(n_m.khs.size(), k_j.size()); ++k) {
k_j[k][i] = V(n_m.khs[k], n_m.mattenuation[k]);
phi_j[k][i] = std::move(n_m.mfunctions_zr[k]);
}
}
};
template<typename T>
struct modes_copier<T, T> {
static void copy(const NormalModes& n_m, types::vector3d_t<T>& k_j, types::vector4d_t<T>& phi_j,
const size_t& i, const size_t& j) {
for (size_t k = 0; k < std::min(n_m.khs.size(), k_j.size()); ++k) {
k_j[k][i][j] = n_m.khs[k];
phi_j[k][i][j] = std::move(n_m.mfunctions_zr[k]);
}
}
static void copy(const NormalModes& n_m, types::vector2d_t<T>& k_j, types::vector3d_t<T>& phi_j,
const size_t& i) {
for (size_t k = 0; k < std::min(n_m.khs.size(), k_j.size()); ++k) {
k_j[k][i] = n_m.khs[k];
phi_j[k][i] = std::move(n_m.mfunctions_zr[k]);
}
}
};
}// namespace _impl
template<typename T = types::real_t, typename V = T>
class modes {
private:
static constexpr auto Complex = !std::is_same_v<T, V>;
public:
explicit modes(const config<T>& config) : _config(config) {
_n_m.iModesSubset = _config.mode_subset();
_n_m.ppm = static_cast<unsigned int>(_config.ppm());
_n_m.ordRich = static_cast<unsigned int>(_config.ord_rich());
_n_m.f = _config.f();
_n_m.M_betas = _config.betas();
_n_m.eigen_type = "alglib";
_n_m.M_depths.resize(_config.n_layers() + _config.bottom_layers().size());
if (!config.additive_depth())
std::copy(_config.bottom_layers().begin(), _config.bottom_layers().end(), _n_m.M_depths.begin() + _config.n_layers());
_n_m.M_c1s.resize(_config.n_layers());
_n_m.M_c1s.insert(_n_m.M_c1s.end(), _config.bottom_c1s().begin(), _config.bottom_c1s().end());
_n_m.M_c2s.resize(_config.n_layers());
_n_m.M_c2s.insert(_n_m.M_c2s.end(), _config.bottom_c2s().begin(), _config.bottom_c2s().end());
_n_m.M_rhos.resize(config.n_layers(), T(1));
_n_m.M_rhos.insert(_n_m.M_rhos.end(), _config.bottom_rhos().begin(), _config.bottom_rhos().end());
_n_m.M_Ns_points.resize(_n_m.M_depths.size());
}
modes(const config<T>& config, const types::vector1d_t<T>& z) : modes(config) {
_check_z(z);
_n_m.zr.assign(z.begin(), z.end());
}
auto point(const T& x, const T& y, const size_t& c = -1) {
_point(x, y, c);
if constexpr (Complex) {
types::vector1d_t<V> k_j(_n_m.khs.size());
for (size_t j = 0; j < k_j.size(); ++j)
k_j[j] = V(_n_m.khs[j], _n_m.mattenuation[j]);
return std::make_tuple(std::move(k_j), std::move(_n_m.mfunctions_zr));
} else
return std::make_tuple(std::move(_n_m.khs), std::move(_n_m.mfunctions_zr));
}
template<typename C, typename = std::enable_if_t<std::is_invocable_v<C, const NormalModes&, const size_t&>>>
void line(const T& x, const T& y0, const T& y1, const size_t& ny, C&& callback, const size_t& num_workers = 1, const size_t& c = -1) {
const auto hy = (y1 - y0) / (ny - 1);
const auto depth = _config.bathymetry().line(x, y0, y1, ny);
_compute(ny, num_workers, [&](const size_t i0, const size_t i1, NormalModes n_m) {
auto y = y0 + hy * i0;
for (size_t i = i0; i < i1; ++i, y += hy) {
_point(n_m, x, y, depth[i], c);
callback(std::as_const(n_m), std::as_const(i));
}
}
);
}
template<typename C, typename = std::enable_if_t<std::is_invocable_v<C, const NormalModes&, const size_t&>>>
void line(const T& x, const size_t& ny, C&& callback, const size_t& num_workers = 1, const size_t& c = -1) {
const auto [y0, y1] = _config.y_bounds();
return line(x, y0, y1, ny, callback, num_workers, c);
}
template<typename C, typename = std::enable_if_t<std::is_invocable_v<C, const NormalModes&, const size_t&>>>
void line(const T& x, C&& callback, const size_t& num_workers = 1, const size_t& c = -1) {
return line(x, _config.mny(), callback, num_workers, c);
}
auto vector_line(const T& x, const T& y0, const T& y1, const size_t& ny, const size_t& num_workers = 1, const size_t& c = -1) {
return vector_line(x, y0, y1, ny, utils::nothing_callback(), num_workers, c);
}
auto vector_line(const T& x, const size_t& ny, const size_t& num_workers = 1, const size_t& c = -1) {
const auto [y0, y1] = _config.y_bounds();
return vector_line(x, y0, y1, ny, num_workers, c);
}
auto vector_line(const T& x, const size_t& c = -1) {
return vector_line(x, _config.mny(), c);
}
template<typename C, typename = std::enable_if_t<std::is_invocable_v<C, const NormalModes&, const size_t&>>>
auto vector_line(const T& x, const T& y0, const T& y1, const size_t& ny, C&& callback, const size_t& num_workers = 1, const size_t& c = -1) {
size_t m = 0;
types::vector2d_t<V> k_j;
types::vector3d_t<T> phi_j;
std::mutex mutex;
line(x, y0, y1, ny,
utils::callbacks(
callback,
[&, mm=_config.max_mode()](const NormalModes& n_m, const size_t& i) mutable {
std::lock_guard<std::mutex> lock(mutex);
_fill_data(n_m, k_j, phi_j, ny, i, mm, m);
}
), num_workers, c
);
_fill_gaps(k_j);
return std::make_tuple(std::move(k_j), std::move(phi_j));
}
template<typename C, typename = std::enable_if_t<std::is_invocable_v<C, const NormalModes&, const size_t&>>>
auto vector_line(const T& x, const size_t& ny, C&& callback, const size_t& num_workers = 1, const size_t& c = -1) {
const auto [y0, y1] = _config.y_bounds();
return vector_line(x, y0, y1, ny, callback, num_workers, c);
}
template<typename C, typename = std::enable_if_t<std::is_invocable_v<C, const NormalModes&, const size_t&>>>
auto vector_line(const T& x, C&& callback, const size_t& num_workers = 1, const size_t& c = -1) {
return vector_line(x, callback, num_workers, c);
}
auto interpolated_line(const T& x, const T& y0, const T& y1, const size_t& ny, const size_t& num_workers = 1, const size_t& c = -1) {
return interpolated_line(x, y0, y1, ny, utils::nothing_callback(), num_workers, c);
}
auto interpolated_line(const T& x, const size_t& ny, const size_t& num_workers = 1, const size_t& c = -1) {
const auto [y0, y1] = _config.y_bounds();
return interpolated_line(x, y0, y1, ny, num_workers, c);
}
auto interpolated_line(const T& x, const size_t& num_workers = 1, const size_t& c = -1) {
return interpolated_line(x, _config.mny(), num_workers, c);
}
template<typename C, typename = std::enable_if_t<std::is_invocable_v<C, const NormalModes&, const size_t&>>>
auto interpolated_line(const T& x, const T& y0, const T& y1, const size_t& ny, C&& callback, const size_t& num_workers = 1, const size_t& c = -1) {
const auto y = utils::mesh_1d(y0, y1, ny);
auto [k_j, phi_j] = vector_line(x, y0, y1, ny, callback, num_workers, c);
return std::make_tuple(
utils::linear_interpolated_data_1d<T, V>(y, std::move(k_j)),
utils::linear_interpolated_data_2d<T, T>(y, _n_m.zr, std::move(phi_j))
);
}
template<typename C, typename = std::enable_if_t<std::is_invocable_v<C, const NormalModes&, const size_t&>>>
auto interpolated_line(const T& x, const size_t& ny, C&& callback, const size_t& num_workers = 1, const size_t& c = -1) {
const auto [y0, y1] = _config.y_bounds();
return interpolated_line(x, y0, y1, ny, callback, num_workers, c);
}
template<typename C, typename = std::enable_if_t<std::is_invocable_v<C, const NormalModes&, const size_t&>>>
auto interpolated_line(const T& x, C&& callback, const size_t& num_workers = 1, const size_t& c = -1) {
return interpolated_line(x, _config.mny(), callback, num_workers, c);
}
template<typename C, typename = std::enable_if_t<std::is_invocable_v<C, const NormalModes&, const size_t&, const size_t&>>>
void field(
const T& x0, const T& x1, const size_t& nx,
const T& y0, const T& y1, const size_t& ny,
C&& callback, const size_t& num_workers = 1, const size_t& c = -1) {
const auto hx = (x1 - x0) / (nx - 1);
const auto hy = (y1 - y0) / (ny - 1);
const auto depth = _config.bathymetry().field(x0, x1, nx, y0, y1, ny);
_compute(ny, num_workers, [&](const size_t j0, const size_t j1, NormalModes n_m) {
auto x = x0;
for (size_t i = 0; i < nx; ++i, x += hx) {
auto y = y0 + j0 * hy;
for (size_t j = j0; j < j1; ++j, y += hy) {
_point(n_m, x, y, depth[i][j], c);
callback(std::as_const(n_m), std::as_const(i), std::as_const(j));
}
}
}
);
}
template<typename C, typename = std::enable_if_t<std::is_invocable_v<C, const NormalModes&, const size_t&, const size_t&>>>
void field(const size_t& nx, const size_t& ny, C&& callback, const size_t& num_workers = 1, const size_t& c = -1) {
const auto [x0, x1] = _config.x_bounds();
const auto [y0, y1] = _config.y_bounds();
return field(x0, x1, nx, y0, y1, ny, callback, num_workers, c);
}
template<typename C, typename = std::enable_if_t<std::is_invocable_v<C, const NormalModes&, const size_t&, const size_t&>>>
void field(C&& callback, const size_t& num_workers = 1, const size_t& c = -1) {
return field(_config.mnx(), _config.mny(), callback, num_workers, c);
}
auto vector_field(
const T& x0, const T& x1, const size_t& nx,
const T& y0, const T& y1, const size_t& ny,
const size_t& num_workers = 1, const size_t& c = -1) {
return vector_field(x0, x1, nx, y0, y1, ny, utils::nothing_callback(), num_workers, c);
}
auto vector_field(const size_t& nx, const size_t& ny, const size_t& num_workers = 1, const size_t& c = -1) {
const auto [x0, x1] = _config.x_bounds();
const auto [y0, y1] = _config.y_bounds();
return vector_field(x0, x1, nx, y0, y1, ny, utils::nothing_callback(), num_workers, c);
}
auto vector_field(const size_t& num_workers = 1, const size_t& c = -1) {
return vector_field(_config.mnx(), _config.mny(), utils::nothing_callback(), num_workers, c);
}
template<typename C, typename = std::enable_if_t<std::is_invocable_v<C, const NormalModes&, const size_t&, const size_t&>>>
auto vector_field(
const T& x0, const T& x1, const size_t& nx,
const T& y0, const T& y1, const size_t& ny,
C&& callback, const size_t& num_workers = 1, const size_t& c = -1, const bool& smooth = false) {
types::vector3d_t<V> k_j;
types::vector4d_t<T> phi_j;
std::mutex mutex;
field(x0, x1, nx, y0, y1, ny,
utils::callbacks(
callback,
[&, m=size_t(0), mm=_config.max_mode()](const NormalModes& n_m, const size_t& i, const size_t& j) mutable {
std::lock_guard<std::mutex> lock(mutex);
m = j ? m : 0;
_fill_data(n_m, k_j, phi_j, nx, ny, i, j, mm, m);
}
), num_workers, c
);
for (auto& it : k_j)
_fill_gaps(it);
if (smooth)
_smooth((y1 - y0) / (ny - 1), _config.border_width(), k_j, phi_j);
return std::make_tuple(std::move(k_j), std::move(phi_j));
}
template<typename C, typename = std::enable_if_t<std::is_invocable_v<C, const NormalModes&, const size_t&, const size_t&>>>
auto vector_field(const size_t& nx, const size_t& ny, C&& callback, const size_t& num_workers = 1, const size_t& c = -1) {
const auto [x0, x1] = _config.x_bounds();
const auto [y0, y1] = _config.y_bounds();
return vector_field(x0, x1, nx, y0, y1, ny, callback, num_workers, c);
}
template<typename C, typename = std::enable_if_t<std::is_invocable_v<C, const NormalModes&, const size_t&, const size_t&>>>
auto vector_field(C&& callback, const size_t& num_workers = 1, const size_t& c = -1) {
return vector_field(_config.mnx(), _config.mny(), callback, num_workers, c);
}
auto interpolated_field(
const T& x0, const T& x1, const size_t& nx,
const T& y0, const T& y1, const size_t& ny,
const size_t& num_workers = 1, const size_t& c = -1) {
return interpolated_field(x0, x1, nx, y0, y1, ny, utils::nothing_callback(), num_workers, c);
}
auto interpolated_field(const size_t& nx, const size_t& ny, const size_t& num_workers = 1, const size_t& c = -1) {
const auto [x0, x1] = _config.x_bounds();
const auto [y0, y1] = _config.y_bounds();
return interpolated_field(x0, x1, nx, y0, y1, ny, num_workers, c);
}
auto interpolated_field(const size_t& num_workers = 1, const size_t& c = -1) {
return interpolated_field(_config.mnx(), _config.mny(), num_workers, c);
}
template<typename C, typename = std::enable_if_t<std::is_invocable_v<C, const NormalModes&, const size_t&, const size_t&>>>
auto interpolated_field(
const T& x0, const T& x1, const size_t& nx,
const T& y0, const T& y1, const size_t& ny,
C&& callback, const size_t& num_workers = 1, const size_t& c = -1) {
const auto x = utils::mesh_1d(x0, x1, nx);
const auto y = utils::mesh_1d(y0, y1, ny);
auto [k_j, phi_j] = vector_field(x0, x1, nx, y0, y1, ny, callback, num_workers, c);
return std::make_tuple(
utils::linear_interpolated_data_2d<T, V>(x, y, std::move(k_j)),
utils::linear_interpolated_data_3d<T, T>(x, y, _n_m.zr, std::move(phi_j))
);
}
template<typename C, typename = std::enable_if_t<std::is_invocable_v<C, const NormalModes&, const size_t&, const size_t&>>>
auto interpolated_field(const size_t& nx, const size_t& ny, C&& callback, const size_t& num_workers = 1, const size_t& c = -1) {
const auto [x0, x1] = _config.x_bounds();
const auto [y0, y1] = _config.y_bounds();
return interpolated_field(x0, x1, nx, y0, y1, ny, callback, num_workers, c);
}
template<typename C, typename = std::enable_if_t<std::is_invocable_v<C, const NormalModes&, const size_t&, const size_t&>>>
auto interpolated_field(C&& callback, const size_t& num_workers = 1, const size_t& c = -1) {
return interpolated_field(_config.mnx(), _config.mny(), callback, num_workers, c);
}
void set_z(const types::vector1d_t<T>& z) {
_check_z(z);
_n_m.zr.assign(z.begin(), z.end());
}
private:
NormalModes _n_m;
const config<T>& _config;
static constexpr T eps = 1;
template<typename C>
void _compute(const size_t& n, size_t num_workers, C&& callback) {
num_workers = std::min(num_workers, n);
if (num_workers <= 1) {
callback(0, n, _n_m);
return;
}
types::vector1d_t<std::thread> workers;
workers.reserve(num_workers);
const auto m = n / num_workers;
for (size_t i = 0; i < num_workers; ++i)
workers.emplace_back(
[&callback](const size_t& i, const size_t& j, NormalModes n_m) { callback(i, j, std::move(n_m)); },
m * i, i == num_workers - 1 ? n : m * (i + 1), _n_m);
for (auto& it : workers)
it.join();
}
static void _check_z(const types::vector1d_t<T>& z) {
utils::dynamic_assert(std::all_of(z.begin(), z.end(), [](const auto& v) { return v >= -eps; }),
"All z coordinates must be non-negative");
}
static void _smooth(const T& h, const size_t& count, types::vector3d_t<V>& k_j, types::vector4d_t<T>& phi_j) {
types::vector1d_t<T> coefficients(count);
const auto d = (count - 1) * h;
for (size_t i = 0; i < count; ++i)
coefficients[i] = i * h / d;
for (size_t j = 0; j < k_j.size(); ++j) {
const auto& k0 = k_j[j][0];
const auto& phi0 = phi_j[j][0];
for (size_t i = 1; i < k_j[j].size(); ++i)
for (size_t l = 0, r = k0.size() - count; l < count; ++l, ++r) {
k_j[j][i][l] = k0[l] * (T(1) - coefficients[l]) + coefficients[l] * k_j[j][i][l];
k_j[j][i][r] = k_j[j][i][r] * (T(1) - coefficients[l]) + coefficients[l] * k0[r];
for (size_t k = 0; k < phi0[l].size(); ++k) {
phi_j[j][i][l][k] = phi0[l][k] * (T(1) - coefficients[l]) + coefficients[l] * phi_j[j][i][l][k];
phi_j[j][i][r][k] = phi_j[j][i][r][k] * (T(1) - coefficients[l]) + coefficients[l] * phi0[r][k];
}
}
}
}
void _point(NormalModes& n_m, const T& x, const T& y, const T& depth, const size_t& c = -1) {
utils::dynamic_assert(!n_m.zr.empty(), "There must be at least one depth value");
if (depth <= eps) {
n_m.khs.clear();
n_m.mfunctions_zr.clear();
return;
}
n_m.nmod = static_cast<int>(c == -1 ? _config.n_modes() : c);
n_m.alpha = M_PI / 180 * (n_m.nmod > 0);
auto buff = utils::mesh_1d(T(0), depth, _config.n_layers() + 1);
std::copy(buff.begin() + 1, buff.end(), n_m.M_depths.begin());
if (_config.additive_depth())
std::transform(_config.bottom_layers().begin(), _config.bottom_layers().end(),
n_m.M_depths.begin() + _config.n_layers(), [&depth](const auto& z) { return z + depth; });
_config.hydrology().line(x, T(0), depth, buff);
std::copy(buff.begin(), buff.end() - 1, n_m.M_c1s.begin());
std::copy(buff.begin() + 1, buff.end(), n_m.M_c2s.begin());
n_m.M_Ns_points[0] = static_cast<unsigned>(std::round(n_m.ppm * n_m.M_depths[0]));
for (size_t i = 1; i < n_m.M_depths.size(); ++i)
n_m.M_Ns_points[i] = static_cast<unsigned>(std::round(n_m.ppm * (n_m.M_depths[i] - n_m.M_depths[i - 1])));
n_m.compute_khs();
n_m.compute_mfunctions_zr();
if constexpr (Complex)
n_m.compute_mattenuation();
}
void _point(const T& x, const T& y, const T& depth, const size_t& c = -1) {
_point(_n_m, x, y, depth, c);
}
void _point(const T& x, const T& y, const size_t& c = -1) {
_point(x, y, _config.bathymetry().point(x, y), c);
}
static auto _fill_data(const NormalModes& n_m, types::vector3d_t<V>& k_j, types::vector4d_t<T>& phi_j,
const size_t& nx, const size_t& ny, const size_t& i, const size_t& j, const size_t& mm, size_t& m) {
const auto n = std::min(n_m.khs.size(), mm);
if (n > k_j.size()) {
k_j.resize(n, types::vector2d_t<V>(nx, types::vector1d_t<V>(ny, V(-1))));
phi_j.resize(n, types::vector3d_t<T>(nx, types::vector2d_t<T>(ny, types::vector1d_t<T>(n_m.zr.size(), T(0)))));
}
_impl::modes_copier<T, V>::copy(n_m, k_j, phi_j, i, j);
m = std::max(n, m);
}
static auto _fill_data(const NormalModes& n_m, types::vector2d_t<V>& k_j, types::vector3d_t<T>& phi_j,
const size_t& ny, const size_t& i, const size_t& mm, size_t& m) {
const auto n = std::min(n_m.khs.size(), mm);
if (n > k_j.size()) {
k_j.resize(n, types::vector1d_t<V>(ny, V(-1)));
phi_j.resize(n, types::vector2d_t<T>(ny, types::vector1d_t<T>(n_m.zr.size(), T(0))));
}
_impl::modes_copier<T, V>::copy(n_m, k_j, phi_j, i);
m = std::max(n, m);
}
static void _fill_gaps(types::vector1d_t<V>& line) {
V left_value, right_value;
size_t left = 0, right = 0;
while (true) {
while (left < line.size() && real(line[left]) >= T(0))
++left;
if (left >= line.size())
break;
right = left + 1;
while (right < line.size() && real(line[right]) < T(0))
++right;
if (left == 0 && right >= line.size()) {
line.assign(line.size(), T(0));
break;
}
if (right < line.size()) {
right_value = line[right];
if (left == 0)
left_value = right_value;
}
if (left != 0) {
left_value = line[left - 1];
if (right >= line.size())
right_value = left_value;
}
const auto d = (right_value - left_value) / static_cast<T>(right - left + 1);
auto value = left_value + d;
for (size_t i = left; i < right; ++i, value += d)
line[i] = value;
left = right + 1;
}
}
static void _fill_gaps(types::vector2d_t<V>& k_j) {
for (auto& line : k_j)
_fill_gaps(line);
}
static void _fill_gaps(types::vector3d_t<V>& k_j) {
for (auto& area : k_j)
for (auto& line : area)
_fill_gaps(line);
}
static void _real(V& value) {
if constexpr (Complex)
return value.real();
else
return value;
}
};
}// namespace ample
| 44.613843 | 155 | 0.527906 | [
"transform"
] |
90df07ef124b12c637340718fabe6b728ac9dbdc | 3,707 | cpp | C++ | src/amplitudes/pomeron_exchange.cpp | cfanelli/jpacPhoto | d1a020eb69b699cecf813347380169f3551c0a07 | [
"MIT"
] | null | null | null | src/amplitudes/pomeron_exchange.cpp | cfanelli/jpacPhoto | d1a020eb69b699cecf813347380169f3551c0a07 | [
"MIT"
] | null | null | null | src/amplitudes/pomeron_exchange.cpp | cfanelli/jpacPhoto | d1a020eb69b699cecf813347380169f3551c0a07 | [
"MIT"
] | null | null | null | // Vector meson photoproduction dynamics proceeding through a pomeron exchange
//
// Author: Daniel Winney (2019)
// Affiliation: Joint Physics Analysis Center (JPAC)
// Email: dwinney@iu.edu
// ---------------------------------------------------------------------------
#include "amplitudes/pomeron_exchange.hpp"
// ---------------------------------------------------------------------------
// Given a set of helicities for each particle, assemble the helicity amplitude by contracting Lorentz indicies
std::complex<double> jpacPhoto::pomeron_exchange::helicity_amplitude(std::vector<int> helicities, double xs, double xt)
{
int lam_gam = helicities[0];
int lam_targ = helicities[1];
int lam_vec = helicities[2];
int lam_rec = helicities[3];
// Save energies
s = xs; t = xt; theta = kinematics->theta_s(xs, xt);
std::complex<double> result = 0.;
// IF using helicity conserving delta fuction model
if (DELTA == true)
{
(lam_gam == lam_vec && lam_rec == lam_targ) ? (result = regge_factor()) : (result = 0.);
return result;
}
// else use Lesniak-Szczepaniak Model
for (int mu = 0; mu < 4; mu++)
{
std::complex<double> temp = regge_factor();
temp *= top_vertex(mu, lam_gam, lam_vec);
temp *= metric[mu];
temp *= bottom_vertex(mu, lam_targ, lam_rec);
result += temp;
}
return result;
};
// ---------------------------------------------------------------------------
// Bottom vertex coupling the target and recoil proton spinors to the vector pomeron
std::complex<double> jpacPhoto::pomeron_exchange::bottom_vertex(int mu, int lam_targ, int lam_rec)
{
std::complex<double> result = 0.;
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
{
std::complex<double> temp;
// Recoil oriented an angle theta + pi
temp = kinematics->recoil->adjoint_component(i, lam_rec, s, theta + M_PI);
// vector coupling
temp *= gamma_matrices[mu][i][j];
// target oriented in negative z direction
temp *= kinematics->target->component(j, lam_targ, s, M_PI);
result += temp;
}
}
// Divide by s to remove the energy dependence left over by the spinors
result /= s;
return result;
};
// ---------------------------------------------------------------------------
// Top vertex coupling the photon, pomeron, and vector meson.
std::complex<double> jpacPhoto::pomeron_exchange::top_vertex(int mu, int lam_gam, int lam_vec)
{
std::complex<double> sum1 = 0., sum2 = 0.;
for (int nu = 0; nu < 4; nu++)
{
std::complex<double> temp1, temp2;
temp1 = kinematics->initial->q(nu, s, 0.);
temp1 *= metric[nu];
temp1 *= kinematics->eps_vec->conjugate_component(nu, lam_vec, s, theta);
sum1 += kinematics->eps_gamma->component(mu, lam_gam, s, 0.) * temp1;
temp2 = kinematics->eps_gamma->component(nu, lam_gam, s, 0.);
temp2 *= metric[nu];
temp2 *= kinematics->eps_vec->conjugate_component(nu, lam_vec, s, theta);
sum2 += kinematics->initial->q(mu, s, 0.) * temp2;
}
return -sum1 + sum2;
};
// ---------------------------------------------------------------------------
// Usual Regge power law behavior, s^alpha(t) with an exponential fall from the forward direction
std::complex<double> jpacPhoto::pomeron_exchange::regge_factor()
{
if (s < kinematics->sth())
{
std::cout << " \n pomeron_exchange: Trying to evaluate below threshold (sqrt(s) = " << sqrt(s) << ")! Quitting... \n";
exit(0);
}
double t_min = kinematics->t_man(s, 0.); // t_min = t(theta = 0)
std::complex<double> result = exp(b0 * (t - t_min));
result *= pow(s - kinematics->sth(), pomeron_traj->eval(t));
result *= xi * norm * e;
return result;
};
| 32.234783 | 122 | 0.58403 | [
"vector",
"model"
] |
90e34765dd13322efbd1e72aedfe035c884ce257 | 58,135 | cpp | C++ | game/client/cstrike15/Scaleform/options_scaleform.cpp | DannyParker0001/Kisak-Strike | 99ed85927336fe3aff2efd9b9382b2b32eb1d05d | [
"Unlicense"
] | 252 | 2020-12-16T15:34:43.000Z | 2022-03-31T23:21:37.000Z | cstrike15_src/game/client/cstrike15/Scaleform/options_scaleform.cpp | bahadiraraz/Counter-Strike-Global-Offensive | 9a0534100cb98ffa1cf0c32e138f0e7971e910d3 | [
"MIT"
] | 23 | 2020-12-20T18:02:54.000Z | 2022-03-28T16:58:32.000Z | cstrike15_src/game/client/cstrike15/Scaleform/options_scaleform.cpp | bahadiraraz/Counter-Strike-Global-Offensive | 9a0534100cb98ffa1cf0c32e138f0e7971e910d3 | [
"MIT"
] | 42 | 2020-12-19T04:32:33.000Z | 2022-03-30T06:00:28.000Z | //========= Copyright � 1996-2005, Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#include "cbase.h"
#if defined( INCLUDE_SCALEFORM )
#include "basepanel.h"
#include "options_scaleform.h"
#include "options_audio_scaleform.h"
#include "options_video_scaleform.h"
#include "filesystem.h"
#include "vgui/ILocalize.h"
#include "inputsystem/iinputsystem.h"
#include "IGameUIFuncs.h"
#include "c_playerresource.h"
#include <vstdlib/vstrtools.h>
#include "matchmaking/imatchframework.h"
#include "../gameui/cstrike15/cstrike15basepanel.h"
#include "iachievementmgr.h"
#include "gameui_interface.h"
#include "gameui_util.h"
#include "vgui_int.h"
#include "materialsystem/materialsystem_config.h"
#include "vgui/ISurface.h"
#include "platforminputdevice.h"
#ifndef _GAMECONSOLE
#include "steam/steam_api.h"
#endif
#define CSGO_TOTAL_OPTION_SLOTS_PER_SCREEN 20
// memdbgon must be the last include file in a .cpp file!!!
#include <tier0/memdbgon.h>
const char *UTIL_Parse( const char *data, char *token, int sizeofToken );
int SortByPriority( COptionsScaleform::Option_t * const *pLeft, COptionsScaleform::Option_t * const *pRight )
{
return ( ( *pLeft )->m_nPriority - ( *pRight )->m_nPriority );
}
COptionsScaleform* COptionsScaleform::m_pInstanceOptions = NULL;
COptionsScaleform::DialogType_e COptionsScaleform::m_DialogType( DIALOG_TYPE_NONE );
CUtlString COptionsScaleform::m_strMessage = "";
CUtlQueue<COptionsScaleform::DialogQueue_t> COptionsScaleform::m_DialogQueue;
// Must match DialogType_e
static const char * s_rgszDialogScripts[] =
{
"scripts/mouse_keyboard_options" PLATFORM_EXT ".txt", // DIALOG_TYPE_KEYBOARD and DIALOG_TYPE_MOUSE
"scripts/controller_options.txt", // DIALOG_TYPE_CONTROLLER
#if defined( _X360 ) || defined( _PS3 )
"scripts/game_options.consoles.txt", // DIALOG_TYPE_SETTINGS
#else
"scripts/game_options.txt", // DIALOG_TYPE_SETTINGS
#endif // _X360
"scripts/motion_controller_options.txt", // DIALOG_TYPE_MOTION_CONTROLLER
"scripts/motion_controller_move_options.txt", // DIALOG_TYPE_MOTION_CONTROLLER_MOVE
"scripts/motion_controller_sharpshooter_options.txt", // DIALOG_TYPE_MOTION_CONTROLLER_SHARPSHOOTER
"scripts/video_options.txt", // DIALOG_TYPE_VIDEO
"scripts/video_advanced_options.txt", // DIALOG_TYPE_VIDEO_ADVANCED
"scripts/audio_options.txt", // DIALOG_TYPE_AUDIO
};
COMPILE_TIME_ASSERT( ARRAYSIZE( s_rgszDialogScripts ) == ( COptionsScaleform::DIALOG_TYPE_COUNT - 1 ) ); // These must be updated in parallel.
SFUI_BEGIN_GAME_API_DEF
SFUI_DECL_METHOD( OnCancel ),
SFUI_DECL_METHOD( OnUpdateValue ),
SFUI_DECL_METHOD( OnHighlightWidget ),
SFUI_DECL_METHOD( OnLayoutComplete ),
SFUI_DECL_METHOD( OnPopulateGlyphRequest ),
SFUI_DECL_METHOD( OnClearBind ),
SFUI_DECL_METHOD( OnResetToDefaults ),
SFUI_DECL_METHOD( OnRequestScroll ),
SFUI_DECL_METHOD( OnResizeVertical ),
SFUI_DECL_METHOD( OnResizeHorizontal ),
SFUI_DECL_METHOD( OnSetSizeVertical ),
SFUI_DECL_METHOD( OnSetSizeHorizontal ),
SFUI_DECL_METHOD( OnSetNextMenu ),
SFUI_DECL_METHOD( OnApplyChanges ),
SFUI_DECL_METHOD( OnSetupMic ),
SFUI_DECL_METHOD( OnMCCalibrate ),
SFUI_DECL_METHOD( OnSaveProfile ),
SFUI_DECL_METHOD( OnRefreshValues ),
SFUI_DECL_METHOD( GetTotalOptionsSlots ),
SFUI_DECL_METHOD( GetCurrentScrollOffset ),
SFUI_DECL_METHOD( GetSafeZoneXMin ),
SFUI_END_GAME_API_DEF( COptionsScaleform, OptionsMenu );
COptionsScaleform::COptionsScaleform() :
m_bVisible ( false ),
m_bLoading ( false ),
m_nScrollPos( 0 ),
m_pConfirmDialog( NULL ),
m_bNavButtonsEnabled( false ),
m_bResetRequired( false ),
m_bOptionsChanged( false ),
m_NoticeType( NOTICE_TYPE_NONE ),
m_pDeadZonePanel( NULL )
{
memset( m_rgOptionsBySlot, 0, sizeof( m_rgOptionsBySlot ) );
memset( m_rgTextBySlot, 0, sizeof( m_rgTextBySlot ) );
m_iSplitScreenSlot = GET_ACTIVE_SPLITSCREEN_SLOT();
}
COptionsScaleform::~COptionsScaleform()
{
StopListeningForAllEvents();
m_vecOptions.PurgeAndDeleteElements();
m_pInstanceOptions = NULL;
m_DialogType = DIALOG_TYPE_NONE;
if ( m_DialogQueue.Count() > 0 )
{
BasePanel()->PostMessage( BasePanel(), new KeyValues( "RunMenuCommand", "command", "OpenOptionsQueued" ) );
return;
}
if ( GameUI().IsInLevel() )
{
if ( ( ( CCStrike15BasePanel* )BasePanel() )->IsScaleformPauseMenuEnabled() )
{
( ( CCStrike15BasePanel* )BasePanel() )->ShowMainMenu( false );
( ( CCStrike15BasePanel* )BasePanel() )->RestorePauseMenu();
}
}
else
{
if (( ( CCStrike15BasePanel* )BasePanel() )-> IsScaleformMainMenuEnabled() )
{
( ( CCStrike15BasePanel* )BasePanel() )->ShowMainMenu( false );
( ( CCStrike15BasePanel* )BasePanel() )->RestoreMainMenuScreen();
}
}
}
void COptionsScaleform::LoadDialog( DialogType_e type )
{
if ( !m_pInstanceOptions )
{
if ( type == DIALOG_TYPE_NONE )
{
if ( m_DialogQueue.Count() > 0 )
{
DialogQueue_t dialogQueue = m_DialogQueue.RemoveAtHead();
type = dialogQueue.m_Type;
m_strMessage = dialogQueue.m_strMessage;
}
else
{
AssertMsg( false, "Trying to invoke a queued dialog with none in queue");
}
}
m_DialogType = type;
#if defined( _PS3 )
// Load the bindings for the specific device.
engine->ExecuteClientCmd( VarArgs( "cl_read_ps3_bindings %d %d", GET_ACTIVE_SPLITSCREEN_SLOT(), GetDeviceFromDialogType( m_DialogType ) ) );
#endif
// this is a convenient place to make sure scaleform has the correct keybindings
g_pScaleformUI->RefreshKeyBindings();
g_pScaleformUI->ShowActionNameWhenActionIsNotBound( false );
/*
if ( m_DialogType == DIALOG_TYPE_VIDEO )
{
engine->ExecuteClientCmd( "mat_updateconvars" );
}
*/
if ( m_DialogType == DIALOG_TYPE_VIDEO || m_DialogType == DIALOG_TYPE_VIDEO_ADVANCED )
{
engine->ExecuteClientCmd( "mat_updateconvars" );
m_pInstanceOptions = new COptionsVideoScaleform( );
}
else if ( m_DialogType == DIALOG_TYPE_AUDIO )
{
m_pInstanceOptions = new COptionsAudioScaleform( );
}
else
{
m_pInstanceOptions = new COptionsScaleform( );
}
SFUI_REQUEST_ELEMENT( SF_FULL_SCREEN_SLOT, g_pScaleformUI, COptionsScaleform, m_pInstanceOptions, OptionsMenu );
}
else
{
AssertMsg( false, "Trying to load an option dialog when an instance already exists!" );
}
}
void COptionsScaleform::UnloadDialog( void )
{
// m_pInstanceControls is deleted in PostUnloadFlash. RemoveFlashElement is called at the end of the hide animation.
if ( m_pInstanceOptions )
{
// Flash elements are removed after hide animation completes
m_pInstanceOptions->Hide();
}
#if defined( _PS3 )
// We need to restore our settings based on our active device since we may have loaded other settings by entering this screen.
InputDevice_t currentDevice = g_pInputSystem->GetCurrentInputDevice();
// open the message box, but make sure we don't have a selected device and aren't already sampling for a device
if( currentDevice != INPUT_DEVICE_NONE )
{
// Load the bindings for the specific device.
engine->ExecuteClientCmd( VarArgs( "cl_read_ps3_bindings %d %d", GET_ACTIVE_SPLITSCREEN_SLOT(), (int)currentDevice ) );
}
#endif // _PS3
}
void COptionsScaleform::ShowMenu( bool bShow, DialogType_e type )
{
if ( type == DIALOG_TYPE_CONTROLLER )
{
if( steamapicontext && steamapicontext->SteamController() )
{
ControllerHandle_t handles[ MAX_STEAM_CONTROLLERS ];
int nControllers = steamapicontext->SteamController()->GetConnectedControllers( handles );
if ( nControllers > 0 )
{
steamapicontext->SteamController()->ShowBindingPanel( handles[ 0 ] );
return;
}
}
}
//TODO tear down existing instance if it already exists
if ( bShow && !m_pInstanceOptions)
{
LoadDialog( type );
}
else
{
if ( bShow != m_pInstanceOptions->m_bVisible )
{
if ( bShow )
{
m_pInstanceOptions->Show();
}
else
{
m_pInstanceOptions->Hide();
}
}
}
}
void COptionsScaleform::FlashLoaded( void )
{
if ( m_FlashAPI && m_pScaleformUI )
{
ReadOptionsFromFile( s_rgszDialogScripts[m_DialogType] );
WITH_SFVALUEARRAY( args, 2 )
{
m_pScaleformUI->ValueArray_SetElement( args, 0, m_vecOptions.Count() );
m_pScaleformUI->ValueArray_SetElement( args, 1, m_DialogType );
WITH_SLOT_LOCKED
{
g_pScaleformUI->Value_InvokeWithoutReturn( m_FlashAPI, "Init", args, 2 );
}
}
g_pMatchFramework->GetEventsSubscription()->Subscribe( this );
}
}
void COptionsScaleform::FlashReady( void )
{
if ( m_FlashAPI && m_pScaleformUI )
{
SF_FORCE_SPLITSCREEN_PLAYER_GUARD( m_iSplitScreenSlot );
m_bLoading = false;
LockInputToSlot( m_iSplitScreenSlot );
SFVALUE topPanel = m_pScaleformUI->Value_GetMember( m_FlashAPI, "TopPanel" );
if ( topPanel )
{
SFVALUE panel = m_pScaleformUI->Value_GetMember( topPanel, "Panel" );
if ( panel )
{
SFVALUE titlePanel = m_pScaleformUI->Value_GetMember( panel, "TitleText" );
ISFTextObject * pTitleText = NULL;
if ( titlePanel )
{
pTitleText = m_pScaleformUI->TextObject_MakeTextObjectFromMember( titlePanel, "Title" );
m_pScaleformUI->ReleaseValue( titlePanel );
}
if ( pTitleText )
{
const char * szName = NULL;
IPlayerLocal *pProfile = g_pMatchFramework->GetMatchSystem()->GetPlayerManager()->GetLocalPlayer( XBX_GetActiveUserId() );
if ( pProfile )
{
szName = pProfile->GetName();
}
if ( !szName )
{
szName = "Player1";
}
wchar_t wcName[MAX_PLAYER_NAME_LENGTH];
g_pVGuiLocalize->ConvertANSIToUnicode( szName, wcName, sizeof( wcName ) );
wchar_t wcTitle[128];
wcTitle[0] = NULL;
g_pVGuiLocalize->ConstructString( wcTitle, sizeof( wcTitle ), g_pVGuiLocalize->Find( "#SFUI_Controls_Title" ), 1, wcName );
pTitleText->SetText( wcTitle );
SafeReleaseSFTextObject( pTitleText );
}
SFVALUE controldummy = m_pScaleformUI->Value_GetMember( panel, "Control_Dummy" );
if ( controldummy )
{
int nMaxSize = m_vecOptions.Count();
for ( int i = 0; i < nMaxSize; i++ )
{
char szLabelName[64];
V_snprintf( szLabelName, sizeof( szLabelName ), "Control_%i", i );
SFVALUE controlpanel = m_pScaleformUI->Value_GetMember( controldummy, szLabelName );
if ( controlpanel )
m_rgTextBySlot[i] = m_pScaleformUI->TextObject_MakeTextObjectFromMember( controlpanel, "Control_Text" );
m_pScaleformUI->ReleaseValue( controlpanel );
}
m_pScaleformUI->ReleaseValue( controldummy );
}
m_pScaleformUI->ReleaseValue( panel );
}
m_pScaleformUI->ReleaseValue( topPanel );
}
m_pDeadZonePanel = m_pScaleformUI->Value_GetMember( m_FlashAPI, "DeadZone" );
if ( m_pDeadZonePanel )
{
m_pScaleformUI->Value_SetVisible( m_pDeadZonePanel, false );
}
// Perform initial layout
LayoutDialog( 0, true );
}
}
void COptionsScaleform::Show( void )
{
if ( FlashAPIIsValid() && !m_bVisible )
{
WITH_SLOT_LOCKED
{
g_pScaleformUI->Value_InvokeWithoutReturn( m_FlashAPI, "ShowPanel", 0, NULL );
}
m_bVisible = true;
}
}
void COptionsScaleform::Hide( void )
{
if ( FlashAPIIsValid() && m_bVisible )
{
WITH_SLOT_LOCKED
{
g_pScaleformUI->Value_InvokeWithoutReturn( m_FlashAPI, "HidePanel", 0, NULL );
}
m_bVisible = false;
}
}
bool COptionsScaleform::PreUnloadFlash( void )
{
g_pMatchFramework->GetEventsSubscription()->Unsubscribe( this );
UnlockInput();
g_pScaleformUI->ShowActionNameWhenActionIsNotBound( true );
int nMaxSize = m_vecOptions.Count( );
for ( int i = 0; i < nMaxSize; i++ )
{
SafeReleaseSFTextObject( m_rgTextBySlot[i] );
}
SafeReleaseSFVALUE( m_pDeadZonePanel );
return CControlsFlashBaseClass::PreUnloadFlash();
}
void COptionsScaleform::PostUnloadFlash( void )
{
if ( m_pInstanceOptions )
{
delete m_pInstanceOptions;
}
else
{
Assert( false );
}
}
void COptionsScaleform::OnApplyChanges( SCALEFORM_CALLBACK_ARGS_DECL )
{
SaveChanges();
}
void COptionsScaleform::OnCancel( SCALEFORM_CALLBACK_ARGS_DECL )
{
if ( m_bResetRequired &&
( ( m_DialogType == DIALOG_TYPE_VIDEO ) || ( m_DialogType == DIALOG_TYPE_VIDEO_ADVANCED ) ) )
{
m_NoticeType = NOTICE_TYPE_DISCARD_CHANGES;
( ( CCStrike15BasePanel* )BasePanel() )->OnOpenMessageBox( "#SFUI_Settings_Video",
/*m_DialogType == DIALOG_TYPE_VIDEO ? "#SFUI_Settings_Changed_Resolution_Discard" : */"#SFUI_Settings_Changed_Discard",
"#SFUI_Settings_Discard_Nav",
( MESSAGEBOX_FLAG_OK | MESSAGEBOX_FLAG_CANCEL ),
this,
&m_pConfirmDialog );
}
else
{
if ( m_bOptionsChanged )
{
SaveChanges();
}
Hide();
}
}
void COptionsScaleform::OnUpdateValue( SCALEFORM_CALLBACK_ARGS_DECL )
{
SF_FORCE_SPLITSCREEN_PLAYER_GUARD( m_iSplitScreenSlot );
int nWidgetIndex = m_pScaleformUI->Params_GetArgAsNumber( obj, 0 );
int nValue = m_pScaleformUI->Params_GetArgAsNumber( obj, 1 );
m_pScaleformUI->Params_SetResult( obj, UpdateValue( nWidgetIndex, nValue ) );
}
void COptionsScaleform::OnHighlightWidget( SCALEFORM_CALLBACK_ARGS_DECL )
{
#ifdef OSX
//test on OSX to see if this will make a common crash go away.
//maybe this is being somehow called with this as a dangling pointer?
if ( m_pInstanceOptions != this )
{
return;
}
#endif
SF_FORCE_SPLITSCREEN_PLAYER_GUARD( m_iSplitScreenSlot );
int nWidgetIndex = m_pScaleformUI->Params_GetArgAsNumber( obj, 0 );
int nMaxSize = m_vecOptions.Count( );
if ( nWidgetIndex >= 0 && nWidgetIndex < nMaxSize )
{
Option_t * pOption = m_rgOptionsBySlot[nWidgetIndex];
if ( IsMotionControllerDialog() )
{
bool bDeadZone = false;
if ( pOption->m_szConVar && !V_strcmp( pOption->m_szConVar, "mc_dead_zone_radius" ) )
{
bDeadZone = true;
}
if ( m_pDeadZonePanel )
{
m_pScaleformUI->Value_SetVisible( m_pDeadZonePanel, bDeadZone );
}
}
}
}
bool COptionsScaleform::UpdateValue( int nWidgetIndex, int nValue )
{
SF_FORCE_SPLITSCREEN_PLAYER_GUARD( m_iSplitScreenSlot );
m_bOptionsChanged = true;
// the widget index is a bad hardcoded thing, if more options get added, this needs to be updated
if ( m_DialogType == DIALOG_TYPE_VIDEO_ADVANCED || m_DialogType == DIALOG_TYPE_VIDEO && nWidgetIndex > 10 )
{
// changes to any of the advanced video options requires that the render device be reset
m_bResetRequired = true;
}
int nMaxSize = m_vecOptions.Count( );
if ( nWidgetIndex >= 0 && nWidgetIndex < nMaxSize )
{
Option_t * pOption = m_rgOptionsBySlot[nWidgetIndex];
if ( pOption )
{
int iConVarSlot = pOption->m_bSystemValue ? 0 : m_iSplitScreenSlot;
switch( pOption->m_Type )
{
case OPTION_TYPE_SLIDER:
{
OptionSlider_t * pOptionSlider = static_cast<OptionSlider_t *>( pOption );
if ( nValue < 0 || nValue > 100 )
{
Assert( false );
Warning ( "Widget updated with out of range value: %s - %i\n", pOptionSlider->m_szConVar, nValue);
}
nValue = clamp( nValue, 0, 100 );
if ( !pOptionSlider->m_bLeftMin )
{
// Calculate the final value as if the left side of the slider = pOptionSlider->m_fMinValue
nValue = 100 - nValue;
}
float fPercent = ( 0.01f * nValue );
if ( pOptionSlider->m_fMaxValue <= 0.0f )
{
fPercent = 1.0f - fPercent;
}
float fRange = pOptionSlider->m_fMaxValue - pOptionSlider->m_fMinValue;
pOptionSlider->m_fSlideValue = ( ( fPercent * fRange ) + pOptionSlider->m_fMinValue );
SplitScreenConVarRef varOption( pOptionSlider->m_szConVar );
varOption.SetValue( iConVarSlot, pOptionSlider->m_fSlideValue );
WITH_SFVALUEARRAY( data, 1 )
{
m_pScaleformUI->ValueArray_SetElement( data, 0, nWidgetIndex );
WITH_SLOT_LOCKED
{
g_pScaleformUI->Value_InvokeWithoutReturn( m_FlashAPI, "RefreshInputField", data, 1 );
}
}
}
break;
case OPTION_TYPE_CHOICE:
{
OptionChoice_t * pOptionChoice = static_cast< OptionChoice_t * >( pOption );
int nCurrentChoice = pOptionChoice->m_nChoiceIndex;
int nNumChoices = pOptionChoice->m_Choices.Count();
nCurrentChoice += nValue;
if ( nCurrentChoice < 0 )
{
nCurrentChoice = nNumChoices - 1;
}
else if ( nCurrentChoice >= nNumChoices )
{
nCurrentChoice = 0;
}
if ( HandleUpdateChoice( pOptionChoice, nCurrentChoice ) )
{
UpdateWidget( nWidgetIndex, static_cast< Option_t * >( pOptionChoice ) );
DisableConditionalWidgets();
}
}
break;
case OPTION_TYPE_DROPDOWN:
{
OptionChoice_t * pOptionChoice = static_cast<OptionChoice_t *>( pOption );
int nCurrentChoice = pOptionChoice->m_nChoiceIndex;
int nNumChoices = pOptionChoice->m_Choices.Count();
nCurrentChoice = nValue;
if ( nCurrentChoice < 0 )
{
nCurrentChoice = nNumChoices - 1;
}
else if ( nCurrentChoice >= nNumChoices )
{
nCurrentChoice = 0;
}
if ( HandleUpdateChoice( pOptionChoice, nCurrentChoice ) )
{
UpdateWidget( nWidgetIndex, static_cast<Option_t *>( pOptionChoice ) );
DisableConditionalWidgets();
}
}
break;
case OPTION_TYPE_BIND:
{
OptionBind_t * pOptionBind = static_cast<OptionBind_t *>( pOption );
if ( nValue == BIND_CMD_BIND )
{
ButtonCode_t code = g_pScaleformUI->GetCurrentKey();
// Don't allow actions to be bound to ~
if ( code == KEY_BACKQUOTE )
{
return false;
}
// do not allow primary navigation keys to be bound to filtered actions
static const char *szNoFilterList[] =
{
"screenshot",
};
static const int kNumNoFilterEntries = sizeof( szNoFilterList ) / sizeof( szNoFilterList[0] );
if ( pOptionBind->m_szCommand && pOptionBind->m_szCommand[0] )
{
for ( int idx=0; idx < kNumNoFilterEntries; ++idx )
{
if ( StringHasPrefix( pOptionBind->m_szCommand, szNoFilterList[idx] ) )
{
if ( code == JOYSTICK_FIRST ||
code == MOUSE_LEFT ||
code == MOUSE_RIGHT ||
code == KEY_SPACE )
{
return false;
}
}
}
}
UnbindOption( pOptionBind );
char szCommand[ 256 ];
V_snprintf( szCommand, sizeof( szCommand ), "bind \"%s\" \"%s\"", g_pInputSystem->ButtonCodeToString( code ), pOptionBind->m_szCommand );
engine->ExecuteClientCmd( szCommand );
// Refresh the key glyphs associated with each action
m_pScaleformUI->RefreshKeyBindings();
RefreshValues( false );
}
}
break;
case OPTION_TYPE_CATEGORY:
{
UpdateWidget( nWidgetIndex, pOption );
}
break;
default:
{
Warning ( "Attempted to update widget of bad type: %s - %i\n", pOption->m_szConVar, pOption->m_Type );
Assert( false );
}
break;
}
}
else
{
Assert( false );
}
}
else
{
Assert( false );
Warning( "Attempted to update widget that is outside of expected index range. Current number of expected widgets: %i\n", SF_FULL_SCREEN_SLOT );
}
return true;
}
bool COptionsScaleform::HandleUpdateChoice( OptionChoice_t * pOptionChoice, int nCurrentChoice )
{
if ( pOptionChoice &&
nCurrentChoice >= 0 &&
nCurrentChoice < pOptionChoice->m_Choices.Count() )
{
pOptionChoice->m_nChoiceIndex = nCurrentChoice;
int iConVarSlot = pOptionChoice->m_bSystemValue ? 0 : m_iSplitScreenSlot;
SplitScreenConVarRef varOption( pOptionChoice->m_szConVar );
varOption.SetValue( iConVarSlot, pOptionChoice->m_Choices[nCurrentChoice].m_szValue );
return true;
}
return false;
}
void COptionsScaleform::OnLayoutComplete( SCALEFORM_CALLBACK_ARGS_DECL )
{
WITH_SLOT_LOCKED
{
g_pScaleformUI->Value_InvokeWithoutReturn( m_FlashAPI, "RefreshWidgetLayout", 0, NULL );
}
Show();
PerformPostLayout();
DisableConditionalWidgets();
}
void COptionsScaleform::DisableConditionalWidgets()
{
#ifndef POSIX
SF_FORCE_SPLITSCREEN_PLAYER_GUARD( m_iSplitScreenSlot );
for ( int iOption = m_nScrollPos; iOption < m_vecOptions.Count(); ++iOption )
{
Option_t * pOption = m_vecOptions[iOption];
int nWidgetID = -1;
bool bDisable = false;
HandleDisableConditionalWidgets( pOption, nWidgetID, bDisable );
if ( nWidgetID != -1 )
{
WITH_SFVALUEARRAY( args, 2 )
{
m_pScaleformUI->ValueArray_SetElement( args, 0, nWidgetID );
m_pScaleformUI->ValueArray_SetElement( args, 1, bDisable );
WITH_SLOT_LOCKED
{
g_pScaleformUI->Value_InvokeWithoutReturn( m_FlashAPI, "DisableWidget", args, 2 );
}
}
}
}
#endif
}
void COptionsScaleform::HandleDisableConditionalWidgets( Option_t * pOption, int & nWidgetIDOut, bool & bDisableOut )
{
if ( pOption->m_szConVar )
{
nWidgetIDOut = pOption->m_nWidgetSlotID;
bDisableOut = false;
if ( !V_strcmp( pOption->m_szConVar, "m_customaccel_exponent" ) )
{
SplitScreenConVarRef m_customaccel( "m_customaccel" );
bDisableOut = !m_customaccel.GetBool( m_iSplitScreenSlot );
}
}
}
void COptionsScaleform::GetTotalOptionsSlots( SCALEFORM_CALLBACK_ARGS_DECL )
{
m_pScaleformUI->Params_SetResult( obj, m_vecOptions.Count() );
}
void COptionsScaleform::GetCurrentScrollOffset( SCALEFORM_CALLBACK_ARGS_DECL )
{
m_pScaleformUI->Params_SetResult( obj, m_nScrollPos );
}
void COptionsScaleform::OnRequestScroll( SCALEFORM_CALLBACK_ARGS_DECL )
{
bool bSuccess = false;
SF_FORCE_SPLITSCREEN_PLAYER_GUARD( m_iSplitScreenSlot );
int nScrollDirection = m_pScaleformUI->Params_GetArgAsNumber( obj, 0 );
int nSize = m_vecOptions.Count() - CSGO_TOTAL_OPTION_SLOTS_PER_SCREEN;
if ( ( nScrollDirection > 0 && ( nSize >= m_nScrollPos + nScrollDirection ) ) ||
( nScrollDirection < 0 && ( ( m_nScrollPos + nScrollDirection ) >= 0 ) ) )
{
LayoutDialog( m_nScrollPos + nScrollDirection );
vgui::surface()->PlaySound( "UI/buttonrollover.wav" );
bSuccess = true;
}
m_pScaleformUI->Params_SetResult( obj, bSuccess );
}
void COptionsScaleform::OnPopulateGlyphRequest( SCALEFORM_CALLBACK_ARGS_DECL )
{
SF_FORCE_SPLITSCREEN_PLAYER_GUARD( m_iSplitScreenSlot );
ISFTextObject * pText = m_pScaleformUI->TextObject_MakeTextObjectFromMember( m_pScaleformUI->Params_GetArg( obj, 0 ), "Text" );
if ( pText )
{
pText->SetTextHTML( m_pScaleformUI->Params_GetArgAsString( obj, 1 ) );
SafeReleaseSFTextObject( pText );
}
}
void COptionsScaleform::OnClearBind( SCALEFORM_CALLBACK_ARGS_DECL )
{
SF_FORCE_SPLITSCREEN_PLAYER_GUARD( m_iSplitScreenSlot );
int nWidgetIndex = m_pScaleformUI->Params_GetArgAsNumber( obj, 0 );
int nMaxSize = m_vecOptions.Count( );
Assert( nWidgetIndex < nMaxSize );
if ( nWidgetIndex >= 0 && nWidgetIndex < nMaxSize )
{
Option_t * pOption = m_rgOptionsBySlot[nWidgetIndex];
if ( pOption->m_Type == OPTION_TYPE_BIND )
{
OptionBind_t * pOptionBind = static_cast<OptionBind_t *>( pOption );
UnbindOption( pOptionBind );
}
}
}
bool COptionsScaleform::OnMessageBoxEvent( MessageBoxFlags_t buttonPressed )
{
if ( buttonPressed & MESSAGEBOX_FLAG_OK )
{
switch( m_NoticeType )
{
case NOTICE_TYPE_RESET_TO_DEFAULT:
ResetToDefaults();
break;
case NOTICE_TYPE_INFO:
break;
default:
AssertMsg( false, "Invalid message box notice type" );
}
m_NoticeType = NOTICE_TYPE_NONE;
}
if ( FlashAPIIsValid() )
{
WITH_SLOT_LOCKED
{
g_pScaleformUI->Value_InvokeWithoutReturn( m_FlashAPI, "changeUIDevice", 0, NULL );
}
}
return true;
}
void COptionsScaleform::OnResetToDefaults( SCALEFORM_CALLBACK_ARGS_DECL )
{
m_NoticeType = NOTICE_TYPE_RESET_TO_DEFAULT;
SF_FORCE_SPLITSCREEN_PLAYER_GUARD( m_iSplitScreenSlot );
const char * szTitle = NULL;
const char * szBody = NULL;
const char * szNav = NULL;
switch( m_DialogType )
{
case DIALOG_TYPE_KEYBOARD:
case DIALOG_TYPE_CONTROLLER:
case DIALOG_TYPE_MOTION_CONTROLLER:
case DIALOG_TYPE_MOTION_CONTROLLER_MOVE:
case DIALOG_TYPE_MOTION_CONTROLLER_SHARPSHOOTER:
szTitle = "#SFUI_Controls_Confirm_Default_Title";
szBody = "#SFUI_Controls_Confirm_Default_Msg";
szNav = "#SFUI_Controls_Confirm_Default_Nav";
break;
default:
szTitle = "#SFUI_Settings_Confirm_Default_Title";
szBody = "#SFUI_Settings_Confirm_Default_Msg";
szNav = "#SFUI_Settings_Confirm_Default_Nav";
break;
}
( ( CCStrike15BasePanel* )BasePanel() )->OnOpenMessageBox( szTitle, szBody, szNav, ( MESSAGEBOX_FLAG_OK | MESSAGEBOX_FLAG_CANCEL | MESSAGEBOX_FLAG_AUTO_CLOSE_ON_DISCONNECT ), this, &m_pConfirmDialog );
}
void COptionsScaleform::BuildClanTagsLabels( CUtlVector<OptionChoiceData_t> &choices )
{
// Build out the clan dropdown
OptionChoiceData_t choiceElement;
ConVarRef cl_clanid( "cl_clanid" );
//const char *pClanID = cl_clanid.GetString();
#ifndef NO_STEAM
ISteamFriends *pFriends = steamapicontext->SteamFriends();
if ( pFriends )
{
V_strncpy( choiceElement.m_szValue, "0", sizeof( choiceElement.m_szValue ) );
V_wcsncpy( choiceElement.m_wszLabel, g_pVGuiLocalize->Find( "#SFUI_Settings_ClanTag_None" ), sizeof( choiceElement.m_wszLabel ) );
choices.AddToTail( choiceElement );
/* Removed for partner depot */
}
#endif
}
void COptionsScaleform::ReadOptionsFromFile( const char * szFileName )
{
SF_FORCE_SPLITSCREEN_PLAYER_GUARD( m_iSplitScreenSlot );
KeyValues *pOptionKeys = new KeyValues( "options" );
bool bResult = pOptionKeys->LoadFromFile( g_pFullFileSystem, szFileName, NULL );
bool bDevMode = !IsCert() && !IsRetail();
if ( bResult )
{
KeyValues *pKey = NULL;
for ( pKey = pOptionKeys->GetFirstTrueSubKey(); pKey; pKey = pKey->GetNextTrueSubKey() )
{
// Skip disabled options
if ( pKey->GetInt( "disable", 0 ) != 0 )
{
continue;
}
// Skip options that are only available in non-cert, non-retail builds
if ( !bDevMode && ( pKey->GetInt( "devonly", 0 ) != 0 ) )
{
continue;
}
bool bSkip = false;
KeyValues *pRestrictionsKey = pKey->FindKey( "restrictions" );
if ( pRestrictionsKey )
{
KeyValues *pSubKey = NULL;
for ( pSubKey = pRestrictionsKey->GetFirstSubKey(); pSubKey; pSubKey = pRestrictionsKey->GetNextKey() )
{
char const *szRestrictionName = pSubKey->GetName();
if ( szRestrictionName[0] == '-' )
{
bool bParameterPresent = ( CommandLine()->FindParm( szRestrictionName ) != 0 );
bool bParameterSkip = pSubKey->GetBool( ( const char * ) NULL, true );
if ( bParameterPresent == bParameterSkip )
{
bSkip = true;
break;
}
}
else if ( const ConVar *pVar = g_pCVar->FindVar( szRestrictionName ) )
{
if ( !V_strcmp( pVar->GetString(), pSubKey->GetString() ) )
{
bSkip = true;
break;
}
}
}
}
if ( bSkip )
{
continue;
}
// Get the type and instantiate an appropriate option
OptionType_e type = OPTION_TYPE_TOTAL;
const char * szType = pKey->GetString( "type", "" );
if ( !V_strcmp( szType, "slider" ) )
{
type = OPTION_TYPE_SLIDER;
}
else if ( !V_strcmp( szType, "choice" ) )
{
type = OPTION_TYPE_CHOICE;
}
else if ( !V_strcmp( szType, "dropdown" ) )
{
type = OPTION_TYPE_DROPDOWN;
}
else if ( !V_strcmp( szType, "bind" ) )
{
type = OPTION_TYPE_BIND;
}
else if ( !V_strcmp( szType, "category" ) )
{
type = OPTION_TYPE_CATEGORY;
}
Option_t * pOption = NULL;
switch ( type )
{
case OPTION_TYPE_SLIDER:
pOption = new OptionSlider_t();
break;
case OPTION_TYPE_CHOICE:
case OPTION_TYPE_DROPDOWN:
pOption = new OptionChoice_t();
break;
case OPTION_TYPE_BIND:
pOption = new OptionBind_t();
break;
case OPTION_TYPE_CATEGORY:
pOption = new Option_t();
break;
default:
Warning ( "Bad widget type read from file: %s\n", pKey->GetString( "name", "" ) );
Assert( false );
break;
}
// Update the option with values from the data file
if ( pOption )
{
// Shared values
pOption->m_Type = type;
g_pVGuiLocalize->ConvertANSIToUnicode( pKey->GetString( "name", "" ), pOption->m_wcLabel, sizeof( pOption->m_wcLabel ) );
V_strncpy( pOption->m_szConVar, pKey->GetString( "convar", "" ), sizeof( pOption->m_szConVar ) );
g_pVGuiLocalize->ConvertANSIToUnicode( pKey->GetString( "tooltip", "" ), pOption->m_wcTooltip, sizeof( pOption->m_wcTooltip ) );
pOption->m_bSystemValue = pKey->GetBool( "systemvalue" );
pOption->m_bRefreshInventoryIconsWhenIncreased = pKey->GetBool( "refresh_inventory_icons_when_increased" );
pOption->m_nPriority = pKey->GetInt( "priority", 0 );
// Type specific values
if ( pOption->m_Type == OPTION_TYPE_SLIDER )
{
OptionSlider_t * pOptionSlider = static_cast<OptionSlider_t *>( pOption );
pOptionSlider->m_bLeftMin = pKey->GetBool( "leftmin", true );
SplitScreenConVarRef varOption( pOptionSlider->m_szConVar );
if ( varOption.IsValid() )
{
pOptionSlider->m_fMinValue = pKey->GetBool( "customrange", false ) ? pKey->GetFloat( "minvalue" ) : varOption.GetMin();
pOptionSlider->m_fMaxValue = pKey->GetBool( "customrange", false ) ? pKey->GetFloat( "maxvalue" ) : varOption.GetMax();
}
else
{
Assert( false );
Warning( "Data File Error. Convar associated with control not found: %s", pOptionSlider->m_szConVar );
}
SetSliderWithConVar( pOptionSlider );
if ( pOptionSlider->m_fMaxValue <= pOptionSlider->m_fMinValue )
{
Warning( "Datafile error. maxvalue and minvalue cannot be the same. nimvalue cannot be < maxvalue. Control: %s\n", pOptionSlider->m_szConVar );
}
else if ( ( pOptionSlider->m_fSlideValue > pOptionSlider->m_fMaxValue ) ||
( pOptionSlider->m_fSlideValue < pOptionSlider->m_fMinValue ) )
{
Warning( "Datafile error. maxvalue and minvalue not within range of ConvVar value. ConVar: %s (%.1f) not in range %.1f to %.1f\n", pOptionSlider->m_szConVar,
pOptionSlider->m_fSlideValue,
pOptionSlider->m_fMinValue,
pOptionSlider->m_fMaxValue);
}
}
else if ( pOption->m_Type == OPTION_TYPE_CHOICE || pOption->m_Type == OPTION_TYPE_DROPDOWN )
{
OptionChoice_t * pOptionChoice = static_cast<OptionChoice_t *>( pOption );
KeyValues *pChoicesKey = pKey->FindKey( "choices" );
if ( pOption->m_Type == OPTION_TYPE_DROPDOWN )
pChoicesKey = pKey->FindKey( "dropdown" );
if ( pChoicesKey )
{
// special case the splitscreen mode because
// it can only have the value "0" when running
// on an SD display
if ( !InitUniqueWidget( pKey->GetName(), pOptionChoice ) )
{
KeyValues *pSubKey = NULL;
for ( pSubKey = pChoicesKey->GetFirstSubKey(); pSubKey; pSubKey = pSubKey->GetNextKey() )
{
int nChoice = pOptionChoice->m_Choices.AddToTail();
OptionChoiceData_t * pNewOptionChoice = &( pOptionChoice->m_Choices[ nChoice ]);
wchar_t wszTemp[ SF_OPTIONS_MAX ];
wchar_t *pwchLabel = g_pVGuiLocalize->Find( pSubKey->GetName() );
if ( !pwchLabel || pwchLabel[ 0 ] == L'\0' )
{
g_pVGuiLocalize->ConvertANSIToUnicode( pSubKey->GetName(), wszTemp, sizeof( wszTemp ) );
pwchLabel = wszTemp;
}
V_wcsncpy( pNewOptionChoice->m_wszLabel, pwchLabel, sizeof( pNewOptionChoice->m_wszLabel ) );
V_strncpy( pNewOptionChoice->m_szValue, pSubKey->GetString(), sizeof( pNewOptionChoice->m_szValue ) );
//
// Autodetect options support
//
if ( !V_stricmp( "#SFUI_Settings_Choice_Autodetect", pSubKey->GetName() )
&& V_strstr( pOption->m_szConVar, "_optionsui" ) )
{
static KeyValues *s_kvOptionsUiDefaults = NULL;
if ( !s_kvOptionsUiDefaults )
{
s_kvOptionsUiDefaults = new KeyValues( "defaults" );
if ( !s_kvOptionsUiDefaults->LoadFromFile( filesystem, "cfg/videodefaults.txt", "USRLOCAL" ) )
s_kvOptionsUiDefaults->Clear();
}
// This option is Auto - also concatenate it with the actual value that was auto-detected
CFmtStr fmtDefaultSetting( "setting.%.*s", V_strlen( pOption->m_szConVar ) - V_strlen( "_optionsui" ), pOption->m_szConVar );
if ( char const *szOptionsUiDefault = s_kvOptionsUiDefaults->GetString( fmtDefaultSetting, NULL ) )
{
int nResult = FindChoiceFromString( pOptionChoice, szOptionsUiDefault );
if ( nResult >= 0 && nResult < nChoice )
{
V_wcsncat( pNewOptionChoice->m_wszLabel, L" : <font color='#707070'>", sizeof( pNewOptionChoice->m_wszLabel ) );
V_wcsncat( pNewOptionChoice->m_wszLabel, pOptionChoice->m_Choices[nResult].m_wszLabel, sizeof( pNewOptionChoice->m_wszLabel ) );
V_wcsncat( pNewOptionChoice->m_wszLabel, L"</font>", sizeof( pNewOptionChoice->m_wszLabel ) );
}
}
}
}
if ( pOptionChoice->m_Choices.Count() < 2 )
{
Assert( false );
Warning( "Type is choice but there is only one option: %s\n", pOptionChoice->m_szConVar );
}
}
SetChoiceWithConVar( pOptionChoice );
}
else
{
Assert( false );
Warning( "\"choices\" key not found for widget: %s\n", pOptionChoice->m_szConVar );
}
}
else if ( pOption->m_Type == OPTION_TYPE_BIND )
{
OptionBind_t * pOptionBind = static_cast<OptionBind_t *>( pOption );
V_strncpy( pOptionBind->m_szCommand, pKey->GetString( "command", "" ), sizeof( pOptionBind->m_szCommand ) );
}
m_vecOptions.AddToTail( pOption );
}
}
m_vecOptions.Sort( SortByPriority );
}
else
{
Warning( "Failed to read file: %s\n", szFileName );
}
pOptionKeys->deleteThis();
Assert( bResult && m_vecOptions.Count() > 0 );
}
bool COptionsScaleform::InitUniqueWidget( const char * szWidgetID, OptionChoice_t * pOptionChoice )
{
bool bFound = false;
if ( !V_strcmp( szWidgetID, "ClanTag" ) )
{
//m_pResolutionWidget = pOptionChoice;
BuildClanTagsLabels( pOptionChoice->m_Choices );
bFound = true;
}
return bFound;
}
int COptionsScaleform::FindChoiceFromString( OptionChoice_t * pOption, const char * szMatch )
{
int nResult = -1;
for ( int nChoice = 0; nChoice < pOption->m_Choices.Count(); ++nChoice )
{
if ( V_stricmp( pOption->m_Choices[ nChoice ].m_szValue, szMatch ) == 0 )
{
nResult = nChoice;
break;
}
// We need to compare values in case we have "0" & "0.00000".
if ( ( szMatch[0] >= '0' && szMatch[0] <= '9' ) || szMatch[0] == '-' )
{
float flVal = V_atof( szMatch );
float flChoiceVal = V_atof( pOption->m_Choices[ nChoice ].m_szValue );
if ( flVal == flChoiceVal )
{
nResult = nChoice;
break;
}
}
}
return nResult;
}
void COptionsScaleform::SetChoiceWithConVar( OptionChoice_t * pOption, bool bForceDefaultValue )
{
SF_FORCE_SPLITSCREEN_PLAYER_GUARD( m_iSplitScreenSlot );
SplitScreenConVarRef varOption( pOption->m_szConVar );
int iConVarSlot = pOption->m_bSystemValue ? 0 : m_iSplitScreenSlot;
if ( bForceDefaultValue )
{
varOption.SetValue( iConVarSlot, varOption.GetDefault() );
}
int nResult = -1;
nResult = FindChoiceFromString( pOption, varOption.GetString( iConVarSlot ) );
if ( !V_strcmp( pOption->m_szConVar, "rate" ) )
{
int nCurrentValue = varOption.GetInt( iConVarSlot );
// Find the value with a bigger value than user's setting
for ( int nChoice = 0; nChoice < pOption->m_Choices.Count(); ++nChoice )
{
int nChoiceRateValue = V_atoi( pOption->m_Choices[ nChoice ].m_szValue );
if ( ( nCurrentValue <= nChoiceRateValue ) // found a setting with a bigger value
|| ( nChoice == pOption->m_Choices.Count() - 1 ) ) // ... or last setting is "Unrestricted"
{
nResult = nChoice;
break;
}
}
}
else if ( !V_strcmp( pOption->m_szConVar, "cl_clanid" ) )
{
//ResolutionModes_t current = FindCurrentResolution();
ConVarRef cl_clanid( "cl_clanid" );
const char *pClanID = cl_clanid.GetString();
//char szResolutionName[ 256 ];
//GetResolutionName( current.m_nWidth, current.m_nHeight, szResolutionName, sizeof( szResolutionName ) );
for ( int nChoice = 0; nChoice < pOption->m_Choices.Count(); ++nChoice )
{
if ( V_stricmp( pOption->m_Choices[ nChoice ].m_szValue, pClanID ) == 0 )
{
nResult = nChoice;
break;
}
}
if ( nResult == -1 )
{
nResult = pOption->m_Choices.Count() - 1;
}
pOption->m_nChoiceIndex = nResult;
}
if ( nResult == -1 )
{
// Unexpected ConVar value, try matching with the default
Warning( "ConVar did not match any of the options found in data file: %s\n", pOption->m_szConVar );
nResult = FindChoiceFromString( pOption, varOption.GetDefault() );
if ( nResult == -1 )
{
// Completely unexpected ConVar value. Display whatever choice is at the zero index so that
// the client does not draw undefined characters
Assert( false );
Warning( "ConVar default not match any of the options found in data file: %s\n", pOption->m_szConVar );
nResult = 0;
}
}
pOption->m_nChoiceIndex = nResult;
}
void COptionsScaleform::SetSliderWithConVar( OptionSlider_t * pOption )
{
SF_FORCE_SPLITSCREEN_PLAYER_GUARD( m_iSplitScreenSlot );
int iConVarSlot = pOption->m_bSystemValue ? 0 : m_iSplitScreenSlot;
const char * szConVar = pOption->m_szConVar;
if ( szConVar && szConVar[0] )
{
SplitScreenConVarRef varOption( szConVar );
pOption->m_fSlideValue = varOption.GetFloat( iConVarSlot );
}
}
void COptionsScaleform::LayoutDialog( const int nVecOptionsOffset, const bool bInit )
{
SF_FORCE_SPLITSCREEN_PLAYER_GUARD( m_iSplitScreenSlot );
int nSize = m_vecOptions.Count();
Assert( nSize > 0 && "ReadOptionsFromFile successful?");
//int nLowerBound = nVecOptionsOffset;
// It is possible for the number of options to be < than the number of total available slots. Account for this.
//int nUpperBound = MIN( nSize, nVecOptionsOffset + ( nSize < SF_OPTIONS_SLOTS_COUNT ? nSize : SF_OPTIONS_SLOTS_COUNT ) );
if ( bInit )
{
int nWidgetIndex = 0;
for ( int nOptionID = 0; nOptionID < ( nSize ? nSize : SF_OPTIONS_SLOTS_COUNT_MAX ); nOptionID++ )
{
UpdateWidget( nWidgetIndex, m_vecOptions[nOptionID] );
m_rgOptionsBySlot[nWidgetIndex] = m_vecOptions[nOptionID];
m_vecOptions[nOptionID]->m_nWidgetSlotID = nWidgetIndex;
nWidgetIndex++;
}
}
m_nScrollPos = nVecOptionsOffset;
WITH_SFVALUEARRAY( args, 1 )
{
m_pScaleformUI->ValueArray_SetElement( args, 0, nVecOptionsOffset );
g_pScaleformUI->Value_InvokeWithoutReturn( m_FlashAPI, "LayoutUpdateHighlight", args, 1 );
}
}
void COptionsScaleform::UpdateWidget( const int nWidgetIndex, Option_t const * const pOption )
{
int nMaxSize = m_vecOptions.Count( );
Assert( nWidgetIndex < nMaxSize );
SF_FORCE_SPLITSCREEN_PLAYER_GUARD( m_iSplitScreenSlot );
if ( nWidgetIndex >= 0 && nWidgetIndex < nMaxSize )
{
WITH_SFVALUEARRAY( data, 6 )
{
m_pScaleformUI->ValueArray_SetElement( data, 0, nWidgetIndex );
m_pScaleformUI->ValueArray_SetElement( data, 1, pOption->m_Type );
if ( m_rgTextBySlot[nWidgetIndex] )
{
WITH_SLOT_LOCKED
{
m_rgTextBySlot[nWidgetIndex]->SetText( pOption->m_wcLabel );
}
}
switch( pOption->m_Type )
{
case OPTION_TYPE_SLIDER:
{
OptionSlider_t const * const pOptionSlider = static_cast<OptionSlider_t const * const>( pOption );
if ( pOptionSlider->m_fMaxValue != pOptionSlider->m_fMinValue )
{
float fPercent = ( pOptionSlider->m_fSlideValue - pOptionSlider->m_fMinValue ) / ( pOptionSlider->m_fMaxValue - pOptionSlider->m_fMinValue );
if ( pOptionSlider->m_fMaxValue <= 0.0f )
{
fPercent = 1.0f - fPercent;
}
int nPercent = static_cast<int>( fPercent * 100.f );
if ( !pOptionSlider->m_bLeftMin )
{
// Calculate the final value as if the left side of the slider = pOptionSlider->m_fMinValue
nPercent = 100 - nPercent;
}
m_pScaleformUI->ValueArray_SetElement( data, 2, nPercent );
m_pScaleformUI->ValueArray_SetElement( data, 3, pOptionSlider->m_szConVar );
}
else
{
Assert( false );
Warning( "Datafile error. maxvalue and minvalue cannot be the same. Control: %s\n", pOptionSlider->m_szConVar );
}
}
break;
case OPTION_TYPE_CATEGORY:
{
m_pScaleformUI->ValueArray_SetElement( data, 2, "" );
m_pScaleformUI->ValueArray_SetElement( data, 3, "" );
}
break;
case OPTION_TYPE_CHOICE:
{
OptionChoice_t const * const pOptionChoice = static_cast< OptionChoice_t const * const >( pOption );
Assert( pOptionChoice->m_nChoiceIndex != -1 );
if ( pOptionChoice->m_nChoiceIndex != -1 )
{
if ( pOptionChoice->m_nChoiceIndex < pOptionChoice->m_Choices.Count() )
{
OptionChoiceData_t const & value = pOptionChoice->m_Choices[pOptionChoice->m_nChoiceIndex];
m_pScaleformUI->ValueArray_SetElement( data, 2, value.m_wszLabel );
m_pScaleformUI->ValueArray_SetElement( data, 3, pOptionChoice->m_szConVar );
}
}
}
break;
case OPTION_TYPE_DROPDOWN:
{
OptionChoice_t const * const pOptionChoice = static_cast<OptionChoice_t const * const>( pOption );
Assert( pOptionChoice->m_nChoiceIndex != -1 );
if ( pOptionChoice->m_nChoiceIndex != -1 )
{
if ( pOptionChoice->m_nChoiceIndex < pOptionChoice->m_Choices.Count() )
{
//OptionChoiceData_t const & value = pOptionChoice->m_Choices[pOptionChoice->m_nChoiceIndex];
m_pScaleformUI->ValueArray_SetElement( data, 2, pOptionChoice->m_nChoiceIndex );
m_pScaleformUI->ValueArray_SetElement( data, 3, pOptionChoice->m_szConVar );
SFVALUE dropdownData = CreateFlashArray( pOptionChoice->m_Choices.Count( ) );
for ( int i = 0; i < pOptionChoice->m_Choices.Count(); i++ )
{
OptionChoiceData_t const & dropValue = pOptionChoice->m_Choices[i];
m_pScaleformUI->Value_SetArrayElement( dropdownData, i, dropValue.m_wszLabel );
}
m_pScaleformUI->ValueArray_SetElement( data, 4, dropdownData );
}
}
}
break;
case OPTION_TYPE_BIND:
{
OptionBind_t const * const pOptionBind = static_cast<OptionBind_t const * const>( pOption );
char szCommand[ 32];
szCommand[0] = 0;
V_snprintf( szCommand, sizeof( szCommand ), "${%s}", pOptionBind->m_szCommand );
bool bBindValueSet = false;
for ( int nCode = BUTTON_CODE_NONE; nCode < BUTTON_CODE_LAST; ++nCode )
{
ButtonCode_t code = static_cast<ButtonCode_t>( nCode );
// Only clear the binding for the current input device being configured. This allows a profile to maintain a configuration for multiple controller types.
if ( m_DialogType == DIALOG_TYPE_KEYBOARD || m_DialogType == DIALOG_TYPE_MOUSE ||
m_DialogType == DIALOG_TYPE_AUDIO )
{
if ( !IsKeyCode( code ) && !IsMouseCode( code ) )
{
continue;
}
}
else if ( m_DialogType == DIALOG_TYPE_CONTROLLER || IsMotionControllerDialog() )
{
if ( !IsJoystickCode( code ) )
{
continue;
}
}
const char * szBinding = gameuifuncs->GetBindingForButtonCode( code );
// Check if there's a binding for this key
if ( !szBinding || !szBinding[0] )
continue;
// If we use this binding, display the key in our list
if ( ActionsAreTheSame( szBinding, pOptionBind->m_szCommand ) )
{
if ( m_DialogType == DIALOG_TYPE_KEYBOARD || m_DialogType == DIALOG_TYPE_MOUSE ||
m_DialogType == DIALOG_TYPE_AUDIO )
{
const char * szKeyString = g_pInputSystem->ButtonCodeToString( code );
wchar_t wcKey[MAX_PLAYER_NAME_LENGTH];
g_pVGuiLocalize->ConvertANSIToUnicode( szKeyString, wcKey, sizeof( wcKey ) );
bBindValueSet = true;
m_pScaleformUI->ValueArray_SetElement( data, 2, wcKey );
}
else if ( m_DialogType == DIALOG_TYPE_CONTROLLER ||
IsMotionControllerDialog() )
{
const wchar_t * szGlyphResult = m_pScaleformUI->ReplaceGlyphKeywordsWithHTML( szCommand, 0, true );
bBindValueSet = true;
m_pScaleformUI->ValueArray_SetElement( data, 2, szGlyphResult );
}
}
}
if ( !bBindValueSet )
{
m_pScaleformUI->ValueArray_SetElement( data, 2, "" );
}
}
break;
default:
Assert( false );
break;
}
m_pScaleformUI->ValueArray_SetElement( data, 5, pOption->m_wcTooltip );
WITH_SLOT_LOCKED
{
g_pScaleformUI->Value_InvokeWithoutReturn( m_FlashAPI, "onUpdateWidget", data, 6 );
}
}
}
}
bool COptionsScaleform::ActionsAreTheSame( const char *szAction1, const char *szAction2 )
{
if ( V_stricmp( szAction1, szAction2 ) == 0 )
return true;
if ( ( V_stricmp( szAction1, "+duck" ) == 0 || V_stricmp( szAction1, "toggle_duck" ) == 0 ) &&
( V_stricmp( szAction2, "+duck" ) == 0 || V_stricmp( szAction2, "toggle_duck" ) == 0 ) )
{
// +duck and toggle_duck are interchangable
return true;
}
if ( ( V_stricmp( szAction1, "+zoom" ) == 0 || V_stricmp( szAction1, "toggle_zoom" ) == 0 ) &&
( V_stricmp( szAction2, "+zoom" ) == 0 || V_stricmp( szAction2, "toggle_zoom" ) == 0 ) )
{
// +zoom and toggle_zoom are interchangable
return true;
}
return false;
}
void COptionsScaleform::ResetToDefaults( void )
{
SF_FORCE_SPLITSCREEN_PLAYER_GUARD( m_iSplitScreenSlot );
m_bOptionsChanged = false;
m_bResetRequired = false;
// reset all convars to default values defined by code in case we don't reset them via cfg
RefreshValues( true );
// if this is a control screen, reset binds as well
if ( m_DialogType == DIALOG_TYPE_KEYBOARD ||
m_DialogType == DIALOG_TYPE_MOUSE ||
m_DialogType == DIALOG_TYPE_CONTROLLER ||
IsMotionControllerDialog() )
{
#if defined( _PS3 )
// Reset the convars etc. related to controllers. Does NOT reset bindings.
engine->ExecuteClientCmd( "exec controller.ps3.cfg" );
// Now reset the bindings for the active device.
engine->ExecuteClientCmd( VarArgs( "cl_reset_ps3_bindings %d %d", m_iSplitScreenSlot, GetDeviceFromDialogType( m_DialogType ) ) );
#else
// Reset all bind options with defaults
const char * szConfigFile = "cfg/controller" PLATFORM_EXT ".cfg";
if ( m_DialogType == DIALOG_TYPE_KEYBOARD || m_DialogType == DIALOG_TYPE_MOUSE )
{
szConfigFile = "cfg/config_default.cfg";
}
CUtlBuffer buf( 0, 0, CUtlBuffer::TEXT_BUFFER );
if ( !g_pFullFileSystem->ReadFile( szConfigFile, NULL, buf ) )
{
Assert( false );
Warning( "Unable to locate config file used for default settings: %s\n", szConfigFile );
return;
}
const char *data = ( const char * )buf.Base();
while ( data != NULL )
{
char cmd[64];
data = UTIL_Parse( data, cmd, sizeof( cmd ) );
if ( V_strlen( cmd ) <= 0 )
break;
if ( !V_stricmp(cmd, "bind") ||
!V_stricmp(cmd, "cmd2 bind") )
{
// FIXME: If we ever support > 2 player splitscreen this will need to be reworked.
int nJoyStick = 0;
if ( !V_stricmp(cmd, "cmd2 bind") )
{
nJoyStick = 1;
}
// Key name
char szKeyName[256];
data = UTIL_Parse( data, szKeyName, sizeof(szKeyName) );
if ( szKeyName[ 0 ] == '\0' )
break; // Error
char szBinding[256];
data = UTIL_Parse( data, szBinding, sizeof(szBinding) );
if ( szKeyName[ 0 ] == '\0' )
break; // Error
// Skip it if it's a bind for the other slit
if ( nJoyStick != m_iSplitScreenSlot )
continue;
// Bind it
char szCommand[ 256 ];
V_snprintf( szCommand, sizeof( szCommand ), "bind \"%s\" \"%s\"", szKeyName, szBinding );
engine->ExecuteClientCmd( szCommand );
}
else if ( m_DialogType == DIALOG_TYPE_CONTROLLER ||
IsMotionControllerDialog() )
{
// L4D: Use Defaults also resets cvars listed in config_default.cfg
CGameUIConVarRef var( cmd );
if ( var.IsValid() )
{
char szValue[256] = "";
data = UTIL_Parse( data, szValue, sizeof(szValue) );
var.SetValue( szValue );
}
}
}
#endif // _PS3
}
// Refresh the dialog
RefreshValues( false );
WriteUserSettings( m_iSplitScreenSlot );
}
void COptionsScaleform::UnbindOption( OptionBind_t const * const pOptionBind )
{
SF_FORCE_SPLITSCREEN_PLAYER_GUARD( m_iSplitScreenSlot );
for ( int nCode = BUTTON_CODE_NONE; nCode < BUTTON_CODE_LAST; ++nCode )
{
ButtonCode_t code = static_cast<ButtonCode_t>( nCode );
// Only clear the binding for the current input device being configured. This allows a profile to maintain a configuration for multiple controller types.
if ( m_DialogType == DIALOG_TYPE_KEYBOARD || m_DialogType == DIALOG_TYPE_MOUSE ||
m_DialogType == DIALOG_TYPE_AUDIO )
{
if ( !IsKeyCode( code ) && !IsMouseCode( code ) )
{
continue;
}
}
else if ( m_DialogType == DIALOG_TYPE_CONTROLLER ||
IsMotionControllerDialog() )
{
if ( !IsJoystickCode( code ) )
{
continue;
}
}
const char * szBinding = gameuifuncs->GetBindingForButtonCode( code );
// Check if there's a binding for this key
if ( !szBinding || !szBinding[0] )
continue;
// If we use this binding, display the key in our list
if ( ActionsAreTheSame( szBinding, pOptionBind->m_szCommand ) )
{
char szCommand[ 256 ];
V_snprintf( szCommand, sizeof( szCommand ), "unbind %s", g_pInputSystem->ButtonCodeToString( code ) );
engine->ExecuteClientCmd( szCommand );
}
}
}
void COptionsScaleform::OnNotifyStartEvent( void )
{
if ( FlashAPIIsValid() )
{
WITH_SLOT_LOCKED
{
g_pScaleformUI->Value_InvokeWithoutReturn( m_FlashAPI, "StartKeyPressed", 0, NULL );
}
}
}
void COptionsScaleform::NotifyStartEvent( void )
{
if ( m_pInstanceOptions )
{
m_pInstanceOptions->OnNotifyStartEvent();
}
}
void COptionsScaleform::OnResizeVertical( SCALEFORM_CALLBACK_ARGS_DECL )
{
int nResizeDirection = m_pScaleformUI->Params_GetArgAsNumber( obj, 0 );
ConVarRef varOption( "safezoney" );
float fNewSafe = ( varOption.GetFloat() + ( nResizeDirection * 0.005f ) );
fNewSafe = clamp( fNewSafe, varOption.GetMin(), varOption.GetMax() );
varOption.SetValue( fNewSafe );
}
void COptionsScaleform::OnResizeHorizontal( SCALEFORM_CALLBACK_ARGS_DECL )
{
int nResizeDirection = m_pScaleformUI->Params_GetArgAsNumber( obj, 0 );
ConVarRef varOption( "safezonex" );
float fNewSafe = ( varOption.GetFloat() + ( nResizeDirection * 0.005f ) );
fNewSafe = clamp( fNewSafe, engine->GetSafeZoneXMin(), varOption.GetMax() );
varOption.SetValue( fNewSafe );
}
void COptionsScaleform::OnSetSizeVertical( SCALEFORM_CALLBACK_ARGS_DECL )
{
ConVarRef varOption( "safezoney" );
float fNewSafe = m_pScaleformUI->Params_GetArgAsNumber( obj, 0 );
fNewSafe = clamp( fNewSafe, varOption.GetMin(), varOption.GetMax() );
varOption.SetValue( fNewSafe );
}
void COptionsScaleform::OnSetSizeHorizontal( SCALEFORM_CALLBACK_ARGS_DECL )
{
ConVarRef varOption( "safezonex" );
float fNewSafe = m_pScaleformUI->Params_GetArgAsNumber( obj, 0 );
fNewSafe = clamp( fNewSafe, engine->GetSafeZoneXMin(), varOption.GetMax() );
varOption.SetValue( fNewSafe );
}
void COptionsScaleform::OnSetNextMenu( SCALEFORM_CALLBACK_ARGS_DECL )
{
int nDialogID = m_pScaleformUI->Params_GetArgAsNumber( obj, 0 );
const char * szMessage = m_pScaleformUI->Params_GetArgAsString( obj, 1 );
DialogQueue_t dialog;
dialog.m_Type = static_cast<DialogType_e>( nDialogID );
dialog.m_strMessage = szMessage;
m_DialogQueue.Insert( dialog );
}
void COptionsScaleform::ApplyChangesToSystemConVar( const char *pConVarName, int value )
{
SplitScreenConVarRef convar( pConVarName );
convar.SetValue( 0, value );
}
CEG_NOINLINE void COptionsScaleform::SaveChanges( void )
{
// Saves out the current profile
if ( m_bOptionsChanged )
{
PreSaveChanges();
CEG_ENCRYPT_FUNCTION( COptionsScaleform_ApplyChanges );
SF_FORCE_SPLITSCREEN_PLAYER_GUARD( m_iSplitScreenSlot );
WriteUserSettings( XBX_GetActiveUserId() );
m_bOptionsChanged = false;
}
}
bool COptionsScaleform::SplitRestartConvar( const char * szConVarRestartIn, char * szConVarOut, int nOutLength )
{
int nSuffixLength = 8;
const char * szTest = V_strstr( szConVarRestartIn, "_restart" );
if ( !szTest )
{
szTest = V_strstr( szConVarRestartIn, "_optionsui" );
nSuffixLength = 10;
}
if ( szTest )
{
int nStringLength = V_strlen( szConVarRestartIn );
nStringLength -= nSuffixLength;
V_StrLeft( szConVarRestartIn, nStringLength, szConVarOut, nOutLength );
return true;
}
return false;
}
void COptionsScaleform::OnSaveProfile( SCALEFORM_CALLBACK_ARGS_DECL )
{
// Save the values to the user's profile.
ACTIVE_SPLITSCREEN_PLAYER_GUARD( GET_ACTIVE_SPLITSCREEN_SLOT() );
WriteUserSettings( XBX_GetActiveUserId() );
}
void COptionsScaleform::GetSafeZoneXMin( SCALEFORM_CALLBACK_ARGS_DECL )
{
m_pScaleformUI->Params_SetResult( obj, engine->GetSafeZoneXMin() );
}
void COptionsScaleform::OnSetupMic( SCALEFORM_CALLBACK_ARGS_DECL )
{
#if !defined( _GAMECONSOLE ) && !defined( NO_STEAM )
if ( steamapicontext && steamapicontext->SteamFriends() &&
steamapicontext->SteamUtils() && steamapicontext->SteamUtils()->IsOverlayEnabled() )
{
steamapicontext->SteamFriends()->ActivateGameOverlay( "VoiceSettings" );
}
#endif
}
void COptionsScaleform::RefreshValues( bool bForceDefault )
{
for ( int iOption = 0; iOption < m_vecOptions.Count(); ++iOption )
{
Option_t * pOption = m_vecOptions[ iOption ];
int iConVarSlot = pOption->m_bSystemValue ? 0 : m_iSplitScreenSlot;
if ( pOption->m_Type == OPTION_TYPE_CHOICE || pOption->m_Type == OPTION_TYPE_DROPDOWN )
{
OptionChoice_t * pOptionChoice = static_cast<OptionChoice_t *>( pOption );
if ( pOptionChoice->m_szConVar )
{
SplitScreenConVarRef varOption( pOptionChoice->m_szConVar );
if ( bForceDefault )
{
pOptionChoice->m_nChoiceIndex = -1;
}
SetChoiceWithConVar( pOptionChoice, bForceDefault );
}
}
else if ( pOption->m_Type == OPTION_TYPE_SLIDER )
{
OptionSlider_t * pOptionSlider = static_cast<OptionSlider_t *>( pOption );
if ( pOptionSlider->m_szConVar)
{
SplitScreenConVarRef varOption( pOptionSlider->m_szConVar );
if ( bForceDefault )
{
varOption.SetValue( iConVarSlot, varOption.GetDefault() );
}
SetSliderWithConVar( pOptionSlider );
}
}
else if ( pOption->m_Type == OPTION_TYPE_BIND )
{
if ( bForceDefault )
{
// Default for bind widgets is unbound
UnbindOption( static_cast<OptionBind_t const * const>( pOption ) );
}
}
}
LayoutDialog( m_nScrollPos );
DisableConditionalWidgets();
}
void COptionsScaleform::PerformPostLayout( void )
{
// REI: Disabled this, it puts the scrollbar in an unusable state right now.
// (Also, right now we never use this, it used to be triggered by some
// transitions from Audio -> Keybindings screens
/*
if ( !V_strcmp( m_strMessage.String(), "ShowPTT" ) )
{
m_strMessage.Clear();
FOR_EACH_VEC( m_vecOptions, i )
{
Option_t * pOption = m_vecOptions[i];
if ( pOption && pOption->m_Type == OPTION_TYPE_BIND )
{
OptionBind_t * pOptionBind = static_cast<OptionBind_t *>( pOption );
if ( !V_strcmp( pOptionBind->m_szCommand, "+voicerecord" ) )
{
m_nScrollPos = i;
LayoutDialog( m_nScrollPos );
break;
}
}
}
}
*/
}
bool COptionsScaleform::IsBindMenuRaised()
{
if ( m_DialogType == DIALOG_TYPE_KEYBOARD ||
m_DialogType == DIALOG_TYPE_MOUSE ||
m_DialogType == DIALOG_TYPE_CONTROLLER ||
m_DialogType == DIALOG_TYPE_AUDIO ||
IsMotionControllerDialog() )
{
return true;
}
return false;
}
void COptionsScaleform::OnMCCalibrate( SCALEFORM_CALLBACK_ARGS_DECL )
{
BasePanel()->PostMessage( BasePanel(), new KeyValues( "RunMenuCommand", "command", "OpenMotionCalibrationDialog" ) );
}
void COptionsScaleform::OnRefreshValues( SCALEFORM_CALLBACK_ARGS_DECL )
{
RefreshValues( false );
}
void COptionsScaleform::OnEvent( KeyValues *kvEvent )
{
/* Removed for partner depot */
}
void COptionsScaleform::WriteUserSettings( int iSplitScreenSlot )
{
#if defined( _PS3 )
// Save out the current bindings for the active device.
engine->ClientCmd_Unrestricted( VarArgs( "cl_write_ps3_bindings %d %d", iSplitScreenSlot, GetDeviceFromDialogType( m_DialogType ) ) );
#endif
// Save the values to the user's profile.
engine->ClientCmd_Unrestricted( VarArgs( "host_writeconfig_ss %d", iSplitScreenSlot ) );
}
int COptionsScaleform::GetDeviceFromDialogType( DialogType_e eDialogType )
{
switch ( eDialogType )
{
case DIALOG_TYPE_NONE:
return (int) INPUT_DEVICE_NONE;
case DIALOG_TYPE_KEYBOARD:
case DIALOG_TYPE_CONTROLLER:
return (int) INPUT_DEVICE_GAMEPAD;
case DIALOG_TYPE_SETTINGS:
return (int) INPUT_DEVICE_NONE;
case DIALOG_TYPE_MOTION_CONTROLLER:
case DIALOG_TYPE_MOTION_CONTROLLER_MOVE:
return (int) INPUT_DEVICE_PLAYSTATION_MOVE;
case DIALOG_TYPE_MOTION_CONTROLLER_SHARPSHOOTER:
return (int) INPUT_DEVICE_SHARPSHOOTER;
case DIALOG_TYPE_VIDEO:
case DIALOG_TYPE_VIDEO_ADVANCED:
case DIALOG_TYPE_AUDIO:
case DIALOG_TYPE_SCREENSIZE:
return (int) INPUT_DEVICE_NONE;
default:
Warning( "Dialog type %d not handled in switch statement.", (int)eDialogType );
break;
//MDS_TODO Add INPUT_DEVICE_SHARPSHOOTER for a new SharpShooterBindings screen.
}
return (int) INPUT_DEVICE_NONE;
}
bool COptionsScaleform::IsMotionControllerDialog( void )
{
return ( m_DialogType == DIALOG_TYPE_MOTION_CONTROLLER ||
m_DialogType == DIALOG_TYPE_MOTION_CONTROLLER_MOVE ||
m_DialogType == DIALOG_TYPE_MOTION_CONTROLLER_SHARPSHOOTER );
}
#endif // INCLUDE_SCALEFORM
| 28.030376 | 204 | 0.687073 | [
"render"
] |
90f018e62adebd4dff72013eaf97f00be7412d1d | 12,527 | cxx | C++ | inetcore/mshtml/src/site/base/rootelem.cxx | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | inetcore/mshtml/src/site/base/rootelem.cxx | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | inetcore/mshtml/src/site/base/rootelem.cxx | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | //+---------------------------------------------------------------------------
//
// Microsoft Forms
// Copyright (C) Microsoft Corporation, 1994-1998
//
// File: rootelem.cxx
//
// Contents: Implementation of CRootElement
//
// Classes: CRootElement
//
//----------------------------------------------------------------------------
#include <headers.hxx>
#pragma MARK_DATA(__FILE__)
#pragma MARK_CODE(__FILE__)
#pragma MARK_CONST(__FILE__)
#ifndef X_SWITCHES_HXX_
#define X_SWITCHES_HXX_
#include "switches.hxx"
#endif
#ifndef X_ROOTELEM_HXX
#define X_ROOTELEM_HXX
#include "rootelem.hxx"
#endif
#ifndef X_ELEMENTP_HXX_
#define X_ELEMENTP_HXX_
#include "elementp.hxx"
#endif
#ifndef X_INPUTTXT_HXX_
#define X_INPUTTXT_HXX_
#include "inputtxt.hxx"
#endif
MtDefine(CRootElement, Elements, "CRootElement")
//////////////
// Globals //
//////////////
const CElement::CLASSDESC CRootElement::s_classdesc =
{
{
NULL, // _pclsid
0, // _idrBase
#ifndef NO_PROPERTY_PAGE
0, // _apClsidPages
#endif // NO_PROPERTY_PAGE
NULL, // _pcpi
ELEMENTDESC_NOLAYOUT, // _dwFlags
NULL, // _piidDispinterface
NULL
},
NULL,
NULL // _paccelsRun
};
void
CRootElement::Notify(CNotification *pNF)
{
NOTIFYTYPE ntype = pNF->Type();
CMarkup * pMarkup = GetMarkup();
super::Notify(pNF);
switch (ntype)
{
case NTYPE_SET_CODEPAGE:
//
// Directly switch the codepage (do not call SwitchCodePage)
//
{
ULONG ulData;
UINT WindowsCodePageFromCodePage( CODEPAGE cp );
pNF->Data(&ulData);
IGNORE_HR(pMarkup->SetCodePage(CODEPAGE(ulData)));
IGNORE_HR(pMarkup->SetFamilyCodePage(WindowsCodePageFromCodePage(CODEPAGE(ulData))));
}
break;
case NTYPE_END_PARSE:
pMarkup->SetLoaded(TRUE);
break;
case NTYPE_ELEMENT_ENTERVIEW_1:
// Inherit media property from our master
if (HasMasterPtr())
{
CElement *pMasterElem = GetMasterPtr();
CMarkup *pMasterMarkup = pMasterElem->GetMarkup();
CMarkup *pMarkup = GetMarkup();
mediaType mtMasterMarkup;
Assert( pMasterMarkup && pMarkup );
mtMasterMarkup = pMasterMarkup->GetMedia();
// Only inherit if the master has a media set.
if ( mtMasterMarkup != mediaTypeNotSet )
pMarkup->SetMedia( mtMasterMarkup );
}
break;
}
return;
}
HRESULT
CRootElement::ComputeFormatsVirtual(CFormatInfo * pCFI, CTreeNode * pNodeTarget FCCOMMA FORMAT_CONTEXT FCPARAM )
{
BOOL fParentFrameHidden = FALSE;
BOOL fParentFrameDisplayNone = FALSE;
BOOL fInheritEditableFalse = FALSE;
BOOL fParentEditable = IsDesignMode();
if (HasMasterPtr())
{
CElement * pElemMaster = GetMasterPtr();
ELEMENT_TAG etag = pElemMaster->TagType();
fInheritEditableFalse = (etag==ETAG_GENERIC) || (etag==ETAG_FRAME) || (etag==ETAG_IFRAME);
fParentEditable = pElemMaster->IsEditable(/*fCheckContainerOnly*/TRUE);
if (etag == ETAG_IFRAME || etag == ETAG_FRAME)
{
fParentFrameHidden = pElemMaster->IsVisibilityHidden();
fParentFrameDisplayNone = pElemMaster->IsDisplayNone();
}
if (pElemMaster->IsInMarkup())
{
CDefaults *pDefaults = pElemMaster->GetDefaults();
if ( (!pDefaults && pElemMaster->TagType() == ETAG_GENERIC)
|| (pDefaults && pDefaults->GetAAviewInheritStyle())
|| pElemMaster->Tag() == ETAG_INPUT)
{
return super::ComputeFormatsVirtual(pCFI, pNodeTarget FCCOMMA FCPARAM);
}
}
}
SwitchesBegTimer(SWITCHES_TIMER_COMPUTEFORMATS);
CDoc * pDoc = Doc();
THREADSTATE *pts = GetThreadState();
CColorValue cv;
COLORREF cr;
HRESULT hr = S_OK;
CMarkup * pMarkup = GetMarkup();
BOOL fEditable;
Assert(pCFI);
Assert(SameScope( this, pNodeTarget));
#ifdef MULTI_FORMAT
Assert( pCFI->_eExtraValues != ComputeFormatsType_Normal
|| ( !pNodeTarget->HasFormatAry()
&& IS_FC(FCPARAM)
)
|| ( ( pNodeTarget->GetICF(FCPARAM) == -1
&& pNodeTarget->GetIPF(FCPARAM) == -1
)
|| pNodeTarget->GetIFF(FCPARAM) == -1
)
);
#else
Assert( pCFI->_eExtraValues != ComputeFormatsType_Normal
|| ( ( pNodeTarget->GetICF(FCPARAM) == -1
&& pNodeTarget->GetIPF(FCPARAM) == -1
)
|| pNodeTarget->GetIFF(FCPARAM) == -1
)
);
#endif //MULTI_FORMAT
AssertSz(!TLS(fInInitAttrBag), "Trying to compute formats during InitAttrBag! This is bogus and must be corrected!");
pCFI->Reset();
pCFI->_pNodeContext = pNodeTarget;
//
// Setup Char Format
//
if (!pMarkup->_fDefaultCharFormatCached)
{
hr = THR(pMarkup->CacheDefaultCharFormat());
if (hr)
goto Cleanup;
}
if (pMarkup->_fHasDefaultCharFormat)
{
pCFI->_icfSrc = pMarkup->GetDefaultCharFormatIndex();
pCFI->_pcfSrc = pCFI->_pcf = &(*pts->_pCharFormatCache)[pCFI->_icfSrc];
}
else
{
pCFI->_icfSrc = pDoc->_icfDefault;
pCFI->_pcfSrc = pCFI->_pcf = pDoc->_pcfDefault;
}
if (pMarkup->_fInheritDesignMode)
{
if (fInheritEditableFalse)
{
fEditable = FALSE;
}
else
{
fEditable = fParentEditable;
}
}
else
{
fEditable = IsDesignMode();
}
if (pCFI->_pcf->_fEditable != fEditable)
{
pCFI->PrepareCharFormat();
pCFI->_cf()._fEditable = fEditable;
pCFI->UnprepareForDebug();
}
//
// Setup Para Format
//
pCFI->_ipfSrc = pts->_ipfDefault;
pCFI->_ppfSrc = pCFI->_ppf = pts->_ppfDefault;
//
// Setup Fancy Format
//
pCFI->_iffSrc = pts->_iffDefault;
pCFI->_pffSrc = pCFI->_pff = pts->_pffDefault;
if (fParentFrameHidden)
{
pCFI->PrepareCharFormat();
pCFI->_cf()._fVisibilityHidden = TRUE;
pCFI->UnprepareForDebug();
}
if (fParentFrameDisplayNone)
{
pCFI->PrepareCharFormat();
pCFI->_cf()._fDisplayNone = TRUE;
pCFI->UnprepareForDebug();
}
// TODO (JHarding): Per stress bug 90174, we think we have a window
// here, but we really don't, so adding extra protection.
// NB: (jbeda) I checked this out and it looks kosher.
if (IsInMarkup() && GetMarkup()->HasWindow() && GetMarkup()->HasWindow() )
{
cv = GetMarkup()->Document()->GetAAbgColor();
}
if (cv.IsDefined())
cr = cv.GetColorRef();
else
cr = pDoc->_pOptionSettings->crBack();
if ( !pCFI->_pff->_ccvBackColor.IsDefined()
|| pCFI->_pff->_ccvBackColor.GetColorRef() != cr)
{
pCFI->PrepareFancyFormat();
pCFI->_ff()._ccvBackColor = cr;
pCFI->UnprepareForDebug();
}
Assert(pCFI->_pff->_ccvBackColor.IsDefined());
if(pCFI->_eExtraValues == ComputeFormatsType_Normal)
{
hr = THR(pNodeTarget->CacheNewFormats(pCFI FCCOMMA FCPARAM ));
if (hr)
goto Cleanup;
// If the markup codepage is Hebrew visual order, set the flag.
GetMarkup()->_fVisualOrder = (GetMarkup()->GetCodePage() == CP_ISO_8859_8);
}
Cleanup:
SwitchesEndTimer(SWITCHES_TIMER_COMPUTEFORMATS);
RRETURN(hr);
}
//+---------------------------------------------------------------------------
//
// Member: CRootElement::YieldCurrency
//
// Synopsis:
//
//----------------------------------------------------------------------------
HRESULT
CRootElement::YieldCurrency(CElement *pElemNew)
{
return super::YieldCurrency( pElemNew );
}
//+---------------------------------------------------------------------------
//
// Member: CRootElement::YieldUI
//
// Synopsis:
//
//----------------------------------------------------------------------------
void
CRootElement::YieldUI(CElement *pElemNew)
{
// Note: We call Doc()->RemoveUI() if an embedded control
// calls IOIPF::SetBorderSpace or IOIPF::SetMenu with non-null
// values.
Doc()->ShowUIActiveBorder(FALSE);
}
//+---------------------------------------------------------------------------
//
// Member: CRootElement::BecomeUIActive
//
// Synopsis:
//
//----------------------------------------------------------------------------
HRESULT
CRootElement::BecomeUIActive()
{
HRESULT hr = S_OK;
CDoc *pDoc = Doc();
// Nothing to do?
// if the doc is not currently UIActive but a UIActive site exists, allow the
// doc to go into UIACTIVE state.
if (!pDoc->InPlace())
{
return E_FAIL;
}
if ( pDoc->_pElemUIActive == this
&& GetFocus() == pDoc->InPlace()->_hwnd
&& pDoc->State() >= OS_UIACTIVE)
{
return S_OK;
}
// Tell the document that we are now the UI active site.
// This will deactivate the current UI active site.
hr = THR(pDoc->SetUIActiveElement(this));
if (hr || pDoc->State() < OS_UIACTIVE)
goto Cleanup;
if (!pDoc->_pInPlace->_fDeactivating)
{
// We're now the UI active object, so tell the frame that.
IGNORE_HR(pDoc->SetActiveObject());
#ifndef NO_OLEUI
// Get our menus and toolbars up.
IGNORE_HR(pDoc->InstallUI(FALSE));
// If appropriate, show our grab handles.
if ( !pDoc->_fMsoDocMode
&& !pDoc->_fInWindowsXP_HSS
&& ( pDoc->GetAmbientBool(DISPID_AMBIENT_SHOWHATCHING, TRUE)
|| pDoc->GetAmbientBool(DISPID_AMBIENT_SHOWGRABHANDLES, TRUE)))
{
pDoc->ShowUIActiveBorder(TRUE);
}
#endif // NO_OLEUI
}
Cleanup:
RRETURN(hr);
}
//+-------------------------------------------------------------------
//
// Method: CRootElement::QueryStatusUndoRedo
//
// Synopsis: Helper function for QueryStatus(). Check if in our current
// state we suport these commands.
//
//--------------------------------------------------------------------
#ifndef NO_EDIT
HRESULT
CRootElement::QueryStatusUndoRedo(
BOOL fUndo,
MSOCMD * pcmd,
MSOCMDTEXT * pcmdtext)
{
BSTR bstr = NULL;
HRESULT hr;
// Get the Undo/Redo state.
if (fUndo)
hr = THR_NOTRACE(Doc()->_pUndoMgr->GetLastUndoDescription(&bstr));
else
hr = THR_NOTRACE(Doc()->_pUndoMgr->GetLastRedoDescription(&bstr));
// Return the command state.
pcmd->cmdf = hr ? MSOCMDSTATE_DISABLED : MSOCMDSTATE_UP;
// Return the command text if requested.
if (pcmdtext && pcmdtext->cmdtextf == MSOCMDTEXTF_NAME)
{
#if !defined(_MAC)
if (hr)
{
pcmdtext->cwActual = LoadString(
GetResourceHInst(),
fUndo ? IDS_CANTUNDO : IDS_CANTREDO,
pcmdtext->rgwz,
pcmdtext->cwBuf);
}
else
{
hr = Format(
0,
pcmdtext->rgwz,
pcmdtext->cwBuf,
MAKEINTRESOURCE(fUndo ? IDS_UNDO : IDS_REDO),
bstr);
if (!hr)
pcmdtext->cwActual = _tcslen(pcmdtext->rgwz);
}
#endif
}
if (bstr)
FormsFreeString(bstr);
return S_OK;
}
#endif // NO_EDIT
| 27.056156 | 122 | 0.508422 | [
"object"
] |
90f320c0f88445a498ea969c50880af272716360 | 580 | cpp | C++ | graphs and trees/#4 - DFS.cpp | WilliamPhilippe/Questions | 6b3fd095c08550a29f2b055be57fa8b86e042b27 | [
"MIT"
] | null | null | null | graphs and trees/#4 - DFS.cpp | WilliamPhilippe/Questions | 6b3fd095c08550a29f2b055be57fa8b86e042b27 | [
"MIT"
] | null | null | null | graphs and trees/#4 - DFS.cpp | WilliamPhilippe/Questions | 6b3fd095c08550a29f2b055be57fa8b86e042b27 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
vector<int> viz[5000];
int process[5000] = {0};
int visitado[5000] = {0};
void dfs(int ori){
if( visitado[ori] ) return;
visitado[ori] = 1;
int ha = 1;
for(int i = viz[ori].size() - 1; i >= 0; i--){
int atual = viz[ori][i];
if( !visitado[atual] ){
ha = 0;
dfs(atual);
visitado[atual] = 0;
}
}
if(process[ori] == 0){
process[ori] = 1;
cout << ori << endl;
}
}
int main(){
int n, ori;
cin >> n >> ori;
int a, b;
while(cin >> a >> b){
viz[a].push_back(b);
}
dfs(ori);
return 0;
} | 11.372549 | 47 | 0.524138 | [
"vector"
] |
90fd8a06eaf2ba7d66ac3c2c91bf6bf69745adf6 | 5,162 | cpp | C++ | NeoMathEngine/test/src/learn/BlobMaxOverTimePoolingBackwardTest.cpp | reisei/neoml | 2b397a410d220272e97c8d9393d92035f32d63d8 | [
"ECL-2.0",
"Apache-2.0"
] | 1 | 2020-12-25T08:04:55.000Z | 2020-12-25T08:04:55.000Z | NeoMathEngine/test/src/learn/BlobMaxOverTimePoolingBackwardTest.cpp | reisei/neoml | 2b397a410d220272e97c8d9393d92035f32d63d8 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | NeoMathEngine/test/src/learn/BlobMaxOverTimePoolingBackwardTest.cpp | reisei/neoml | 2b397a410d220272e97c8d9393d92035f32d63d8 | [
"ECL-2.0",
"Apache-2.0"
] | 1 | 2020-11-05T06:46:19.000Z | 2020-11-05T06:46:19.000Z | /* Copyright © 2017-2020 ABBYY Production LLC
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 <TestFixture.h>
using namespace NeoML;
using namespace NeoMLTest;
static void maxOverTimeBackwardNaive( int inputBatchLength, int batchWidth, int objectSize, int strideLength, int filterLength,
const float *outputDiff, const int *maxIndices, float *inputDiff )
{
const int resultBatchLength = ( inputBatchLength - filterLength ) / strideLength + 1;
for( int l = 0; l < resultBatchLength; ++l ) {
for( int w = 0; w < batchWidth; ++w ) {
for( int i = 0; i < objectSize; ++i ) {
const int ind = l * batchWidth * objectSize + w * objectSize + i;
const int maxIndex = maxIndices[ind];
const float diff = outputDiff[ind];
inputDiff[maxIndex * batchWidth * objectSize + w * objectSize + i] += diff;
}
}
}
}
static void maxOverTimePoolingBackwardImpl( const CTestParams& params, int seed )
{
CRandom random( seed );
const CInterval batchLengthInterval = params.GetInterval( "BatchLength" );
const CInterval batchWidthInterval = params.GetInterval( "BatchWidth" );
const CInterval objectSizeInterval = params.GetInterval( "ObjectSize" );
const CInterval strideLengthInterval = params.GetInterval( "StrideLength" );
const CInterval filterLengthInterval = params.GetInterval( "FilterLength" );
const CInterval valuesInterval = params.GetInterval( "Values" );
const int inputBatchLength = random.UniformInt( batchLengthInterval.Begin, batchLengthInterval.End );
const int batchWidth = random.UniformInt( batchWidthInterval.Begin, batchWidthInterval.End );
const int objectSize = random.UniformInt( objectSizeInterval.Begin, objectSizeInterval.End );
const int strideLength = random.UniformInt( strideLengthInterval.Begin, strideLengthInterval.End );
const int filterLength = random.UniformInt( filterLengthInterval.Begin, filterLengthInterval.End );
const int inputSize = objectSize * batchWidth * inputBatchLength;
CREATE_FILL_FLOAT_ARRAY( inputData, valuesInterval.Begin, valuesInterval.End, inputSize, random )
CFloatBlob inputBlob( MathEngine(), inputBatchLength, batchWidth, 1, 1, 1, 1, objectSize );
inputBlob.CopyFrom( inputData.data() );
const int resultBatchLength = ( inputBatchLength - filterLength ) / strideLength + 1;
const int outputSize = objectSize * batchWidth * resultBatchLength;
CFloatBlob outputBlob( MathEngine(), resultBatchLength, batchWidth, 1, 1, 1, 1, objectSize );
CIntBlob indexBlob( MathEngine(), resultBatchLength, batchWidth, 1, 1, 1, 1, objectSize );
CIntHandle indexBlobPtr = indexBlob.GetData();
CREATE_FILL_FLOAT_ARRAY( outputDiffData, valuesInterval.Begin, valuesInterval.End, outputSize, random )
CFloatBlob outputDiffBlob( MathEngine(), resultBatchLength, batchWidth, 1, 1, 1, 1, objectSize );
outputDiffBlob.CopyFrom( outputDiffData.data() );
CFloatBlob inputDiffBlob( MathEngine(), inputBatchLength, batchWidth, 1, 1, 1, 1, objectSize );
CMaxOverTimePoolingDesc *desc = MathEngine().InitMaxOverTimePooling( inputBlob.GetDesc(), filterLength, strideLength, outputBlob.GetDesc() );
MathEngine().BlobMaxOverTimePooling( *desc, inputBlob.GetData(), &indexBlobPtr, outputBlob.GetData() );
MathEngine().BlobMaxOverTimePoolingBackward( *desc, outputDiffBlob.GetData(), indexBlobPtr, inputDiffBlob.GetData() );
delete desc;
std::vector<int> maxIndices;
maxIndices.resize( outputSize );
indexBlob.CopyTo( maxIndices.data() );
std::vector<float> actualDiff, expectedDiff;
actualDiff.resize( inputSize );
inputDiffBlob.CopyTo( actualDiff.data() );
expectedDiff.insert( expectedDiff.begin(), inputSize, 0 );
maxOverTimeBackwardNaive( inputBatchLength, batchWidth, objectSize, strideLength, filterLength,
outputDiffData.data(), maxIndices.data(), expectedDiff.data() );
for( int i = 0; i < inputSize; i++ ) {
ASSERT_TRUE( FloatEq( expectedDiff[i], actualDiff[i] ) );
}
}
//---------------------------------------------------------------------------------------------------------------------
class CMathEngineBlobMaxOverTimePoolingBackwardTest : public CTestFixtureWithParams {
};
INSTANTIATE_TEST_CASE_P( CMathEngineBlobMaxOverTimePoolingBackwardTestInstantiation, CMathEngineBlobMaxOverTimePoolingBackwardTest,
::testing::Values(
CTestParams(
"BatchLength = (10..100);"
"BatchWidth = (1..5);"
"ObjectSize = (1..100);"
"StrideLength = (1..10);"
"FilterLength = (1..10);"
"Values = (-50..50);"
"TestCount = 100;"
)
)
);
TEST_P( CMathEngineBlobMaxOverTimePoolingBackwardTest, Random )
{
RUN_TEST_IMPL( maxOverTimePoolingBackwardImpl )
}
| 44.5 | 142 | 0.727625 | [
"vector"
] |
90fe78be63b874e12150075a3b1f0aedaa7d1461 | 2,133 | cpp | C++ | source/editor/windows/WindowsRegistry.cpp | RaygenEngine/Raygen | 2e61afd35f594d06186c16397b536412ebf4298d | [
"MIT"
] | 2 | 2021-01-27T15:49:04.000Z | 2021-01-28T07:40:30.000Z | source/editor/windows/WindowsRegistry.cpp | RaygenEngine/Raygen | 2e61afd35f594d06186c16397b536412ebf4298d | [
"MIT"
] | null | null | null | source/editor/windows/WindowsRegistry.cpp | RaygenEngine/Raygen | 2e61afd35f594d06186c16397b536412ebf4298d | [
"MIT"
] | 1 | 2021-03-07T23:17:31.000Z | 2021-03-07T23:17:31.000Z | #include "WindowsRegistry.h"
#include "assets/PodEditor.h"
#include "assets/pods/Image.h"
#include "editor/windows/EdMeshGenerator.h"
#include "editor/windows/editors/EdMaterialArchetypeEditor.h"
#include "editor/windows/general/EdAssetListWindow.h"
#include "editor/windows/general/EdAssetsWindow.h"
#include "editor/windows/general/EdAttachmentDebuggerWindow.h"
#include "editor/windows/general/EdConsoleWindow.h"
#include "editor/windows/general/EdMiscWindow.h"
#include "editor/windows/general/EdOutlinerWindow.h"
#include "editor/windows/general/EdProfilerWindow.h"
#include "editor/windows/general/EdPropertyEditorWindow.h"
namespace ed {
class ImageEditorTest : public AssetEditorWindowTemplate<Image> {
public:
ImageEditorTest(PodEntry* inEntry)
: AssetEditorWindowTemplate(inEntry)
{
}
void ImguiDraw() override
{
ImGui::Text(entry->path.c_str());
if (ImEd::Button("FLIP")) {
PodEditor<Image> ed(podHandle);
std::reverse(ed->data.begin(), ed->data.end());
}
}
};
void RegisterWindows(ed::ComponentWindows& windowsComponent)
{
windowsComponent.AddWindowEntry<OutlinerWindow>("Outliner");
windowsComponent.AddWindowEntry<PropertyEditorWindow>("Property Editor");
windowsComponent.AddWindowEntry<AssetsWindow>("Asset Browser");
windowsComponent.AddWindowEntry<AssetListWindow>("Asset List");
windowsComponent.AddWindowEntry<ConsoleWindow>("Console");
windowsComponent.AddWindowEntry<AttachmentDebuggerWindow>("Attachment Debugger");
windowsComponent.AddWindowEntry<ProfilerWindow>("Profiler");
windowsComponent.AddWindowEntry<ImGuiDemoWindow>("ImGui Demo");
windowsComponent.AddWindowEntry<PodEntryEditorWindow>("Entry Editor");
windowsComponent.AddWindowEntry<MeshGenerator>("Mesh Generator");
windowsComponent.RegisterAssetWindowEditor<ImageEditorTest>();
windowsComponent.RegisterAssetWindowEditor<ShaderStageEditorWindow>();
windowsComponent.RegisterAssetWindowEditor<ShaderHeaderEditorWindow>();
windowsComponent.RegisterAssetWindowEditor<MaterialArchetypeEditorWindow>();
windowsComponent.RegisterAssetWindowEditor<MaterialInstanceEditorWindow>();
}
} // namespace ed
| 31.835821 | 82 | 0.809658 | [
"mesh"
] |
2904e0ac7c348dc9c0524d121e42f5e2a8e4054c | 532 | hpp | C++ | source/backend/cpu/CPUScatterNd.hpp | xhuan28/MNN | 81df3a48d79cbc0b75251d12934345948866f7be | [
"Apache-2.0"
] | 6,958 | 2019-05-06T02:38:02.000Z | 2022-03-31T18:08:48.000Z | source/backend/cpu/CPUScatterNd.hpp | xhuan28/MNN | 81df3a48d79cbc0b75251d12934345948866f7be | [
"Apache-2.0"
] | 1,775 | 2019-05-06T04:40:19.000Z | 2022-03-30T15:39:24.000Z | source/backend/cpu/CPUScatterNd.hpp | xhuan28/MNN | 81df3a48d79cbc0b75251d12934345948866f7be | [
"Apache-2.0"
] | 1,511 | 2019-05-06T02:38:05.000Z | 2022-03-31T16:59:39.000Z | //
// CPUScatterNd.hpp
// MNN
//
// Created by MNN on 2019/11/28.
// Copyright © 2018, Alibaba Group Holding Limited
//
#ifndef CPUScatterNd_hpp
#define CPUScatterNd_hpp
#include "core/Execution.hpp"
namespace MNN {
class CPUScatterNd : public Execution {
public:
CPUScatterNd(Backend *bn):Execution(bn){
}
virtual ~CPUScatterNd() = default;
virtual ErrorCode onExecute(const std::vector<Tensor *> &inputs, const std::vector<Tensor *> &outputs) override;
};
} // namespace MNN
#endif /* CPUScatterNd_hpp */
| 20.461538 | 116 | 0.701128 | [
"vector"
] |
290593b6794b029a9498ce5cb74b9c52f6cc6b0c | 22,008 | cpp | C++ | docs/template_plugin/tests/functional/op_reference/loop.cpp | ryanloney/openvino-1 | 4e0a740eb3ee31062ba0df88fcf438564f67edb7 | [
"Apache-2.0"
] | 1,127 | 2018-10-15T14:36:58.000Z | 2020-04-20T09:29:44.000Z | docs/template_plugin/tests/functional/op_reference/loop.cpp | ryanloney/openvino-1 | 4e0a740eb3ee31062ba0df88fcf438564f67edb7 | [
"Apache-2.0"
] | 439 | 2018-10-20T04:40:35.000Z | 2020-04-19T05:56:25.000Z | docs/template_plugin/tests/functional/op_reference/loop.cpp | ryanloney/openvino-1 | 4e0a740eb3ee31062ba0df88fcf438564f67edb7 | [
"Apache-2.0"
] | 414 | 2018-10-17T05:53:46.000Z | 2020-04-16T17:29:53.000Z | // Copyright (C) 2018-2021 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#include <gtest/gtest.h>
#include <openvino/core/model.hpp>
#include <openvino/opsets/opset8.hpp>
#include "base_reference_test.hpp"
#include "functional_test_utils/skip_tests_config.hpp"
#include "common_test_utils/common_utils.hpp"
namespace {
enum LOOP_IN_TYPE {
INVARIANT,
MERGED
};
struct LoopFunctionalBase {
virtual std::shared_ptr<ov::Model> create_function(const std::vector<reference_tests::Tensor>& loop_inputs,
const std::vector<reference_tests::Tensor>& results,
const int64_t& trip_count_value = 1,
const std::vector<LOOP_IN_TYPE>& loop_in_type = {},
const ov::element::Type& net_type = ov::element::f32) = 0;
LoopFunctionalBase() = default;
virtual ~LoopFunctionalBase() = default;
};
struct LoopDynamicInputs : public LoopFunctionalBase {
std::shared_ptr<ov::Model> create_function(const std::vector<reference_tests::Tensor>& loop_inputs,
const std::vector<reference_tests::Tensor>& results,
const int64_t& trip_count_value,
const std::vector<LOOP_IN_TYPE>& loop_in_type,
const ov::element::Type& net_type) override {
auto X = std::make_shared<ov::opset8::Parameter>(ov::element::f32, ov::PartialShape::dynamic());
auto Y = std::make_shared<ov::opset8::Parameter>(ov::element::f32, ov::PartialShape::dynamic());
auto M = std::make_shared<ov::opset8::Parameter>(ov::element::f32, ov::PartialShape::dynamic());
// Set up the cell body, a function from (Xi, Yi) -> (Zo)
// Body parameters
auto Xi = std::make_shared<ov::opset8::Parameter>(ov::element::f32, ov::PartialShape::dynamic());
auto Yi = std::make_shared<ov::opset8::Parameter>(ov::element::f32, ov::PartialShape::dynamic());
auto M_body = std::make_shared<ov::opset8::Parameter>(ov::element::f32, ov::PartialShape::dynamic());
auto body_condition = std::make_shared<ov::opset8::Constant>(ov::element::boolean, ov::Shape{1}, true);
auto trip_count = std::make_shared<ov::opset8::Constant>(ngraph::element::i64, ov::Shape{1}, 3);
auto exec_condition = std::make_shared<ov::opset8::Constant>(ngraph::element::boolean, ov::Shape{1}, true);
// Body
auto sum = std::make_shared<ov::opset8::Add>(Xi, Yi);
auto Zo = std::make_shared<ov::opset8::Multiply>(sum, M_body);
auto body = std::make_shared<ov::Model>(ov::OutputVector{body_condition, Zo},
ov::ParameterVector{Xi, Yi, M_body});
auto loop = std::make_shared<ov::opset8::Loop>(trip_count, exec_condition);
loop->set_function(body);
loop->set_invariant_input(Xi, X);
loop->set_invariant_input(Yi, Y);
loop->set_merged_input(M_body, M, Zo);
loop->set_special_body_ports(ov::opset8::Loop::SpecialBodyPorts{-1, 0});
// Output is last Zo
auto result = std::make_shared<ov::opset8::Result>(loop->get_iter_value(Zo, -1));
return std::make_shared<ov::Model>(ov::ResultVector{result}, ov::ParameterVector{X, Y, M});
}
};
struct LoopParams {
LoopParams(const std::shared_ptr<LoopFunctionalBase>& functional,
const std::vector<reference_tests::Tensor>& loop_inputs,
const std::vector<reference_tests::Tensor>& expected_results,
const std::string& test_case_name)
: function(functional),
inputs(loop_inputs),
expected_results(expected_results),
test_case_name(test_case_name) {}
std::shared_ptr<LoopFunctionalBase> function;
std::vector<reference_tests::Tensor> inputs;
std::vector<reference_tests::Tensor> expected_results;
std::string test_case_name;
};
class ReferenceLoopLayerTest : public testing::TestWithParam<LoopParams>, public reference_tests::CommonReferenceTest {
public:
void SetUp() override {
SKIP_IF_CURRENT_TEST_IS_DISABLED()
auto params = GetParam();
function = params.function->create_function(params.inputs, params.expected_results);
inputData.reserve(params.inputs.size());
refOutData.reserve(params.expected_results.size());
for (auto& input_tensor : params.inputs) {
inputData.push_back(input_tensor.data);
}
for (auto& expected_tensor : params.expected_results) {
refOutData.push_back(expected_tensor.data);
}
}
static std::string getTestCaseName(const testing::TestParamInfo<LoopParams>& obj) {
auto param = obj.param;
return param.test_case_name;
}
};
TEST_P(ReferenceLoopLayerTest, TensorIteratorWithHardcodedRefs) {
Exec();
}
INSTANTIATE_TEST_SUITE_P(
smoke_TensorIterator_With_Hardcoded_Refs,
ReferenceLoopLayerTest,
::testing::Values(
LoopParams(
std::make_shared<LoopDynamicInputs>(),
std::vector<reference_tests::Tensor>{
reference_tests::Tensor(ov::element::f32, ov::Shape{2, 2}, std::vector<float>{0, 1, 2, 3}),
reference_tests::Tensor(ov::element::f32, ov::Shape{2, 2}, std::vector<float>{1, 2, 3, 4}),
reference_tests::Tensor(ov::element::f32, ov::Shape{2, 2}, std::vector<float>{5, 4, 3, 2})},
// 5*(0+1)*(0+1)*(0+1) = 5
// 4*(1+2)*(1+2)*(1+2) = 108
// 3*(2+3)*(2+3)*(2+3) = 375
// 2*(3+4)*(3+4)*(3+4) = 686
std::vector<reference_tests::Tensor>{
reference_tests::Tensor(ov::element::f32, ov::Shape{2, 2}, std::vector<float>{5, 108, 375, 686})},
"loop_dynamic_inputs")),
ReferenceLoopLayerTest::getTestCaseName);
struct LoopStaticInputs : public LoopFunctionalBase {
std::shared_ptr<ov::Model> create_function(const std::vector<reference_tests::Tensor>& loop_inputs,
const std::vector<reference_tests::Tensor>& results,
const int64_t& trip_count,
const std::vector<LOOP_IN_TYPE>& loop_in_type,
const ov::element::Type& net_type) override {
ov::ParameterVector loop_params;
for (auto&& input : loop_inputs) {
loop_params.emplace_back(std::make_shared<ov::opset8::Parameter>(input.type, input.shape));
}
// Set up the cell body, a function from (Xi, Yi) -> (Zo)
// Body parameters
const std::vector<ov::PartialShape> body_params_shapes(loop_inputs.size(), ov::PartialShape::dynamic());
ov::ParameterVector body_params;
for (const auto& pshape : body_params_shapes) {
body_params.emplace_back(std::make_shared<ov::opset8::Parameter>(net_type, pshape));
}
const auto body_condition_const = std::make_shared<ov::opset8::Constant>(ov::element::boolean, ov::Shape{1}, true);
const auto exec_condition = std::make_shared<ov::opset8::Constant>(ov::element::boolean, ov::Shape{1}, true);
std::shared_ptr<ov::Node> trip_count_input;
trip_count_input = std::make_shared<ov::opset8::Constant>(ov::element::i64, ov::Shape{1}, trip_count);
// Body
std::shared_ptr<ov::Node> Zo = body_params[0];
for (int i = 1; i < body_params.size(); ++i) {
Zo = std::make_shared<ov::opset8::Add>(body_params[i], Zo);
}
const auto body = std::make_shared<ov::Model>(ov::OutputVector{body_condition_const, Zo},
body_params);
const auto loop = std::make_shared<ov::opset8::Loop>(trip_count_input, exec_condition);
loop->set_function(body);
loop->set_special_body_ports(ov::opset8::Loop::SpecialBodyPorts{-1, 0});
for (int i = 0; i < body_params.size(); ++i) {
if (loop_in_type[i] == LOOP_IN_TYPE::INVARIANT) {
loop->set_invariant_input(body_params[i], loop_params[i]);
} else if (loop_in_type[i] == LOOP_IN_TYPE::MERGED) {
// todo: support several merged loop_inputs
// now supported only one in this sample
loop->set_merged_input(body_params[i], loop_params[i], Zo);
}
}
// Output 0 is last Zo
const auto out0 = loop->get_iter_value(body_condition_const, -1);
const auto out1 = loop->get_iter_value(Zo, -1);
// Output 1 is concat of Zos
// start=0, stride=1, part_size=1, end=-1, axis=1
const auto out2 = loop->get_concatenated_slices(Zo, 0, 1, 1, -1, 1);
const auto result0 = std::make_shared<ov::opset8::Result>(out0);
const auto result1 = std::make_shared<ov::opset8::Result>(out1);
const auto result2 = std::make_shared<ov::opset8::Result>(out2);
const auto function = std::make_shared<ov::Model>(ov::ResultVector{result0, result1, result2}, loop_params, "loop");
return function;
}
};
struct LoopStaticParams {
LoopStaticParams(
const std::shared_ptr<LoopFunctionalBase>& functional,
const std::vector<reference_tests::Tensor>& loop_inputs,
const std::vector<reference_tests::Tensor>& expected_results,
const int64_t& trip_count,
const std::vector<LOOP_IN_TYPE>& loop_in_type,
const ov::element::Type& net_type,
const std::string& test_case_name)
: function(functional),
inputs(loop_inputs),
expected_results(expected_results),
trip_count(trip_count),
loop_in_type(loop_in_type),
net_type(net_type),
test_case_name(test_case_name) {}
std::shared_ptr<LoopFunctionalBase> function;
std::vector<reference_tests::Tensor> inputs;
std::vector<reference_tests::Tensor> expected_results;
int64_t trip_count;
std::vector<LOOP_IN_TYPE> loop_in_type;
ov::element::Type net_type;
std::string test_case_name;
};
class ReferenceLoopLayerStaticTest : public testing::TestWithParam<LoopStaticParams>, public reference_tests::CommonReferenceTest {
public:
void SetUp() override {
SKIP_IF_CURRENT_TEST_IS_DISABLED()
auto params = GetParam();
function = params.function->create_function(params.inputs,
params.expected_results,
params.trip_count,
params.loop_in_type,
params.net_type);
inputData.reserve(params.inputs.size());
refOutData.reserve(params.expected_results.size());
for (auto& input : params.inputs) {
inputData.push_back(input.data);
}
for (auto& output : params.expected_results) {
refOutData.push_back(output.data);
}
}
static std::string getTestCaseName(const testing::TestParamInfo<LoopStaticParams>& obj) {
auto param = obj.param;
std::ostringstream result;
result << "TS=";
for (auto& input : param.inputs) {
result << CommonTestUtils::vec2str(input.shape) << "_";
}
result << "_tripCount=" << param.trip_count;
result << "_loopInType=";
for (auto& type : param.loop_in_type) {
result << "_" << type;
}
result << "_netType=" << param.net_type;
if (!param.test_case_name.empty()) {
result << "_" << param.test_case_name;
}
return result.str();
}
};
TEST_P(ReferenceLoopLayerStaticTest, CompareWithRefs) {
Exec();
}
template <ov::element::Type_t ET>
std::vector<LoopStaticParams> generateParams() {
using T = typename ov::element_type_traits<ET>::value_type;
std::vector<LoopStaticParams> params {
LoopStaticParams(
std::make_shared<LoopStaticInputs>(),
{reference_tests::Tensor(
ET,
{10, 1, 10},
std::vector<T>{
7, 4, 5, 2, 3, 0, 1, 6, 7, 4, 5, 2, 3, 0, 1, 6, 7, 4, 5, 2,
3, 0, 1, 6, 7, 4, 5, 2, 3, 0, 1, 6, 7, 4, 5, 2, 3, 0, 1, 6,
7, 4, 5, 2, 3, 0, 1, 6, 7, 4, 5, 2, 3, 0, 1, 6, 7, 4, 5, 2,
3, 0, 1, 6, 7, 4, 5, 2, 3, 0, 1, 6, 7, 4, 5, 2, 3, 0, 1, 6,
7, 4, 5, 2, 3, 0, 1, 6, 7, 4, 5, 2, 3, 0, 1, 6, 7, 4, 5, 2}),
reference_tests::Tensor(
ET,
{1, 1, 1},
std::vector<T>{7}),
reference_tests::Tensor(
ET,
{10, 1, 10},
std::vector<T>{
7, 4, 5, 2, 3, 0, 1, 6, 7, 4, 5, 2, 3, 0, 1, 6, 7, 4, 5, 2,
3, 0, 1, 6, 7, 4, 5, 2, 3, 0, 1, 6, 7, 4, 5, 2, 3, 0, 1, 6,
7, 4, 5, 2, 3, 0, 1, 6, 7, 4, 5, 2, 3, 0, 1, 6, 7, 4, 5, 2,
3, 0, 1, 6, 7, 4, 5, 2, 3, 0, 1, 6, 7, 4, 5, 2, 3, 0, 1, 6,
7, 4, 5, 2, 3, 0, 1, 6, 7, 4, 5, 2, 3, 0, 1, 6, 7, 4, 5, 2})},
{reference_tests::Tensor(
ov::element::Type_t::boolean,
{1},
std::vector<char>{1}),
reference_tests::Tensor(
ET,
{10, 1, 10},
std::vector<T>{
21, 15, 17, 11, 13, 7, 9, 19, 21, 15, 17, 11, 13, 7, 9, 19, 21, 15, 17, 11,
13, 7, 9, 19, 21, 15, 17, 11, 13, 7, 9, 19, 21, 15, 17, 11, 13, 7, 9, 19,
21, 15, 17, 11, 13, 7, 9, 19, 21, 15, 17, 11, 13, 7, 9, 19, 21, 15, 17, 11,
13, 7, 9, 19, 21, 15, 17, 11, 13, 7, 9, 19, 21, 15, 17, 11, 13, 7, 9, 19,
21, 15, 17, 11, 13, 7, 9, 19, 21, 15, 17, 11, 13, 7, 9, 19, 21, 15, 17, 11}),
reference_tests::Tensor(
ET,
{10, 1, 10},
std::vector<T>{
21, 15, 17, 11, 13, 7, 9, 19, 21, 15, 17, 11, 13, 7, 9, 19, 21, 15, 17, 11,
13, 7, 9, 19, 21, 15, 17, 11, 13, 7, 9, 19, 21, 15, 17, 11, 13, 7, 9, 19,
21, 15, 17, 11, 13, 7, 9, 19, 21, 15, 17, 11, 13, 7, 9, 19, 21, 15, 17, 11,
13, 7, 9, 19, 21, 15, 17, 11, 13, 7, 9, 19, 21, 15, 17, 11, 13, 7, 9, 19,
21, 15, 17, 11, 13, 7, 9, 19, 21, 15, 17, 11, 13, 7, 9, 19, 21, 15, 17, 11})},
1,
{LOOP_IN_TYPE::INVARIANT, LOOP_IN_TYPE::INVARIANT, LOOP_IN_TYPE::MERGED},
ET,
"loop_for_common"),
LoopStaticParams(
std::make_shared<LoopStaticInputs>(),
{reference_tests::Tensor(
ET,
{10, 1, 10},
std::vector<T>{
7, 4, 5, 2, 3, 0, 1, 6, 7, 4, 5, 2, 3, 0, 1, 6, 7, 4, 5, 2,
3, 0, 1, 6, 7, 4, 5, 2, 3, 0, 1, 6, 7, 4, 5, 2, 3, 0, 1, 6,
7, 4, 5, 2, 3, 0, 1, 6, 7, 4, 5, 2, 3, 0, 1, 6, 7, 4, 5, 2,
3, 0, 1, 6, 7, 4, 5, 2, 3, 0, 1, 6, 7, 4, 5, 2, 3, 0, 1, 6,
7, 4, 5, 2, 3, 0, 1, 6, 7, 4, 5, 2, 3, 0, 1, 6, 7, 4, 5, 2}),
reference_tests::Tensor(
ET,
{1, 1, 1},
std::vector<T>{7}),
reference_tests::Tensor(
ET,
{10, 1, 10},
std::vector<T>{
7, 4, 5, 2, 3, 0, 1, 6, 7, 4, 5, 2, 3, 0, 1, 6, 7, 4, 5, 2,
3, 0, 1, 6, 7, 4, 5, 2, 3, 0, 1, 6, 7, 4, 5, 2, 3, 0, 1, 6,
7, 4, 5, 2, 3, 0, 1, 6, 7, 4, 5, 2, 3, 0, 1, 6, 7, 4, 5, 2,
3, 0, 1, 6, 7, 4, 5, 2, 3, 0, 1, 6, 7, 4, 5, 2, 3, 0, 1, 6,
7, 4, 5, 2, 3, 0, 1, 6, 7, 4, 5, 2, 3, 0, 1, 6, 7, 4, 5, 2})},
{reference_tests::Tensor(
ov::element::Type_t::boolean,
{1},
std::vector<char>{1}),
reference_tests::Tensor(
ET,
{10, 1, 10},
std::vector<T>{
77, 59, 65, 47, 53, 35, 41, 71, 77, 59, 65, 47, 53, 35, 41, 71, 77, 59, 65, 47,
53, 35, 41, 71, 77, 59, 65, 47, 53, 35, 41, 71, 77, 59, 65, 47, 53, 35, 41, 71,
77, 59, 65, 47, 53, 35, 41, 71, 77, 59, 65, 47, 53, 35, 41, 71, 77, 59, 65, 47,
53, 35, 41, 71, 77, 59, 65, 47, 53, 35, 41, 71, 77, 59, 65, 47, 53, 35, 41, 71,
77, 59, 65, 47, 53, 35, 41, 71, 77, 59, 65, 47, 53, 35, 41, 71, 77, 59, 65, 47}),
reference_tests::Tensor(
ET,
{10, 5, 10},
std::vector<T>{
21, 15, 17, 11, 13, 7, 9, 19, 21, 15, 35, 26, 29, 20, 23, 14, 17, 32, 35, 26,
49, 37, 41, 29, 33, 21, 25, 45, 49, 37, 63, 48, 53, 38, 43, 28, 33, 58, 63, 48,
77, 59, 65, 47, 53, 35, 41, 71, 77, 59, 17, 11, 13, 7, 9, 19, 21, 15, 17, 11,
29, 20, 23, 14, 17, 32, 35, 26, 29, 20, 41, 29, 33, 21, 25, 45, 49, 37, 41, 29,
53, 38, 43, 28, 33, 58, 63, 48, 53, 38, 65, 47, 53, 35, 41, 71, 77, 59, 65, 47,
13, 7, 9, 19, 21, 15, 17, 11, 13, 7, 23, 14, 17, 32, 35, 26, 29, 20, 23, 14,
33, 21, 25, 45, 49, 37, 41, 29, 33, 21, 43, 28, 33, 58, 63, 48, 53, 38, 43, 28,
53, 35, 41, 71, 77, 59, 65, 47, 53, 35, 9, 19, 21, 15, 17, 11, 13, 7, 9, 19,
17, 32, 35, 26, 29, 20, 23, 14, 17, 32, 25, 45, 49, 37, 41, 29, 33, 21, 25, 45,
33, 58, 63, 48, 53, 38, 43, 28, 33, 58, 41, 71, 77, 59, 65, 47, 53, 35, 41, 71,
21, 15, 17, 11, 13, 7, 9, 19, 21, 15, 35, 26, 29, 20, 23, 14, 17, 32, 35, 26,
49, 37, 41, 29, 33, 21, 25, 45, 49, 37, 63, 48, 53, 38, 43, 28, 33, 58, 63, 48,
77, 59, 65, 47, 53, 35, 41, 71, 77, 59, 17, 11, 13, 7, 9, 19, 21, 15, 17, 11,
29, 20, 23, 14, 17, 32, 35, 26, 29, 20, 41, 29, 33, 21, 25, 45, 49, 37, 41, 29,
53, 38, 43, 28, 33, 58, 63, 48, 53, 38, 65, 47, 53, 35, 41, 71, 77, 59, 65, 47,
13, 7, 9, 19, 21, 15, 17, 11, 13, 7, 23, 14, 17, 32, 35, 26, 29, 20, 23, 14,
33, 21, 25, 45, 49, 37, 41, 29, 33, 21, 43, 28, 33, 58, 63, 48, 53, 38, 43, 28,
53, 35, 41, 71, 77, 59, 65, 47, 53, 35, 9, 19, 21, 15, 17, 11, 13, 7, 9, 19,
17, 32, 35, 26, 29, 20, 23, 14, 17, 32, 25, 45, 49, 37, 41, 29, 33, 21, 25, 45,
33, 58, 63, 48, 53, 38, 43, 28, 33, 58, 41, 71, 77, 59, 65, 47, 53, 35, 41, 71,
21, 15, 17, 11, 13, 7, 9, 19, 21, 15, 35, 26, 29, 20, 23, 14, 17, 32, 35, 26,
49, 37, 41, 29, 33, 21, 25, 45, 49, 37, 63, 48, 53, 38, 43, 28, 33, 58, 63, 48,
77, 59, 65, 47, 53, 35, 41, 71, 77, 59, 17, 11, 13, 7, 9, 19, 21, 15, 17, 11,
29, 20, 23, 14, 17, 32, 35, 26, 29, 20, 41, 29, 33, 21, 25, 45, 49, 37, 41, 29,
53, 38, 43, 28, 33, 58, 63, 48, 53, 38, 65, 47, 53, 35, 41, 71, 77, 59, 65, 47})},
5,
{LOOP_IN_TYPE::INVARIANT, LOOP_IN_TYPE::INVARIANT, LOOP_IN_TYPE::MERGED},
ET,
"loop_for_common"),
};
return params;
}
std::vector<LoopStaticParams> generateCombinedParams() {
const std::vector<std::vector<LoopStaticParams>> generatedParams {
generateParams<ov::element::Type_t::i8>(),
generateParams<ov::element::Type_t::i16>(),
generateParams<ov::element::Type_t::i32>(),
generateParams<ov::element::Type_t::i64>(),
generateParams<ov::element::Type_t::u8>(),
generateParams<ov::element::Type_t::u16>(),
generateParams<ov::element::Type_t::u32>(),
generateParams<ov::element::Type_t::u64>(),
generateParams<ov::element::Type_t::bf16>(),
generateParams<ov::element::Type_t::f16>(),
generateParams<ov::element::Type_t::f32>(),
};
std::vector<LoopStaticParams> combinedParams;
for (const auto& params : generatedParams) {
combinedParams.insert(combinedParams.end(), params.begin(), params.end());
}
return combinedParams;
}
INSTANTIATE_TEST_SUITE_P(smoke_Loop_With_Hardcoded_Refs, ReferenceLoopLayerStaticTest,
testing::ValuesIn(generateCombinedParams()), ReferenceLoopLayerStaticTest::getTestCaseName);
}
| 52.4 | 131 | 0.492866 | [
"shape",
"vector",
"model"
] |
290ac896add42e0d75771df77c79c855e46c42ed | 6,217 | cc | C++ | src/api/window/window.cc | greenheartgames/node-webkit | b1cba9fc1971932f3461edd259e5899d068c498f | [
"MIT"
] | 1 | 2019-05-07T15:01:26.000Z | 2019-05-07T15:01:26.000Z | src/api/window/window.cc | creativeprogramming/node-webkit | bd628533773e86687f27ce740f6d07689bd790d3 | [
"MIT"
] | null | null | null | src/api/window/window.cc | creativeprogramming/node-webkit | bd628533773e86687f27ce740f6d07689bd790d3 | [
"MIT"
] | 1 | 2019-09-14T19:58:45.000Z | 2019-09-14T19:58:45.000Z | // Copyright (c) 2012 Intel Corp
// Copyright (c) 2012 The Chromium Authors
//
// 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 co
// pies 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 al
// l copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IM
// PLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNES
// S FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
// OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WH
// ETHER 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 "content/nw/src/api/window/window.h"
#include "base/values.h"
#include "content/nw/src/api/dispatcher_host.h"
#include "content/nw/src/api/menu/menu.h"
#include "content/nw/src/browser/native_window.h"
#include "content/nw/src/nw_shell.h"
namespace api {
Window::Window(int id,
DispatcherHost* dispatcher_host,
const base::DictionaryValue& option)
: Base(id, dispatcher_host, option),
shell_(content::Shell::FromRenderViewHost(dispatcher_host->
render_view_host())) {
DVLOG(1) << "Window::Window(" << id << ")";
// Set ID for Shell
shell_->set_id(id);
}
Window::~Window() {
// Window object got deleted when we launch new render view host and
// delete the old one; at this time the Shell should be decoupled
// with the renderer side
DVLOG(1) << "Window::~Window(" << shell_->id() << ")";
shell_->set_id(-1);
}
void Window::Call(const std::string& method,
const base::ListValue& arguments) {
if (method == "Show") {
shell_->window()->Show();
} else if (method == "Close") {
bool force = false;
arguments.GetBoolean(0, &force);
shell_->set_force_close(force);
shell_->window()->Close();
} else if (method == "Hide") {
shell_->window()->Hide();
} else if (method == "Maximize") {
shell_->window()->Maximize();
} else if (method == "Unmaximize") {
shell_->window()->Unmaximize();
} else if (method == "Minimize") {
shell_->window()->Minimize();
} else if (method == "Restore") {
shell_->window()->Restore();
} else if (method == "EnterFullscreen") {
shell_->window()->SetFullscreen(true);
} else if (method == "LeaveFullscreen") {
shell_->window()->SetFullscreen(false);
} else if (method == "ToggleFullscreen") {
shell_->window()->SetFullscreen(!shell_->window()->IsFullscreen());
} else if (method == "EnterKioskMode") {
shell_->window()->SetKiosk(true);
} else if (method == "LeaveKioskMode") {
shell_->window()->SetKiosk(false);
} else if (method == "ToggleKioskMode") {
shell_->window()->SetKiosk(!shell_->window()->IsKiosk());
} else if (method == "ShowDevTools") {
std::string jail_id;
bool headless = false;
arguments.GetString(0, &jail_id);
arguments.GetBoolean(1, &headless);
shell_->ShowDevTools(jail_id.c_str(), headless);
} else if (method == "ResizeTo") {
int width, height;
if (arguments.GetInteger(0, &width) &&
arguments.GetInteger(1, &height))
shell_->window()->SetSize(gfx::Size(width, height));
} else if (method == "SetMaximumSize") {
int width, height;
if (arguments.GetInteger(0, &width) &&
arguments.GetInteger(1, &height))
shell_->window()->SetMaximumSize(width, height);
} else if (method == "SetMinimumSize") {
int width, height;
if (arguments.GetInteger(0, &width) &&
arguments.GetInteger(1, &height))
shell_->window()->SetMinimumSize(width, height);
} else if (method == "SetResizable") {
bool resizable;
if (arguments.GetBoolean(0, &resizable))
shell_->window()->SetResizable(resizable);
} else if (method == "SetAlwaysOnTop") {
bool top;
if (arguments.GetBoolean(0, &top))
shell_->window()->SetAlwaysOnTop(top);
} else if (method == "MoveTo") {
int x, y;
if (arguments.GetInteger(0, &x) &&
arguments.GetInteger(1, &y))
shell_->window()->SetPosition(gfx::Point(x, y));
} else if (method == "RequestAttention") {
bool flash;
if (arguments.GetBoolean(0, &flash))
shell_->window()->FlashFrame(flash);
} else if (method == "SetMenu") {
int id;
if (arguments.GetInteger(0, &id))
shell_->window()->SetMenu(dispatcher_host()->GetApiObject<Menu>(id));
} else if (method == "Reload") {
int type;
if (arguments.GetInteger(0, &type))
shell_->Reload(static_cast<content::Shell::ReloadType>(type));
} else if (method == "CapturePage") {
std::string image_format_str;
if (arguments.GetString(0, &image_format_str))
shell_->window()->CapturePage(image_format_str);
} else {
NOTREACHED() << "Invalid call to Window method:" << method
<< " arguments:" << arguments;
}
}
void Window::CallSync(const std::string& method,
const base::ListValue& arguments,
base::ListValue* result) {
if (method == "IsFullscreen") {
result->AppendBoolean(shell_->window()->IsFullscreen());
} else if (method == "IsKioskMode") {
result->AppendBoolean(shell_->window()->IsKiosk());
} else if (method == "GetSize") {
gfx::Size size = shell_->window()->GetSize();
result->AppendInteger(size.width());
result->AppendInteger(size.height());
} else if (method == "GetPosition") {
gfx::Point position = shell_->window()->GetPosition();
result->AppendInteger(position.x());
result->AppendInteger(position.y());
} else {
NOTREACHED() << "Invalid call to Window method:" << method
<< " arguments:" << arguments;
}
}
} // namespace api
| 39.100629 | 80 | 0.646453 | [
"render",
"object"
] |
290baa739e525074f71bbac2f147516bad18db01 | 3,234 | cpp | C++ | cfw/src/v20190904/model/ModifyResourceGroupRequest.cpp | suluner/tencentcloud-sdk-cpp | a56c73cc3f488c4d1e10755704107bb15c5e000d | [
"Apache-2.0"
] | 43 | 2019-08-14T08:14:12.000Z | 2022-03-30T12:35:09.000Z | cfw/src/v20190904/model/ModifyResourceGroupRequest.cpp | suluner/tencentcloud-sdk-cpp | a56c73cc3f488c4d1e10755704107bb15c5e000d | [
"Apache-2.0"
] | 12 | 2019-07-15T10:44:59.000Z | 2021-11-02T12:35:00.000Z | cfw/src/v20190904/model/ModifyResourceGroupRequest.cpp | suluner/tencentcloud-sdk-cpp | a56c73cc3f488c4d1e10755704107bb15c5e000d | [
"Apache-2.0"
] | 28 | 2019-07-12T09:06:22.000Z | 2022-03-30T08:04:18.000Z | /*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <tencentcloud/cfw/v20190904/model/ModifyResourceGroupRequest.h>
#include <tencentcloud/core/utils/rapidjson/document.h>
#include <tencentcloud/core/utils/rapidjson/writer.h>
#include <tencentcloud/core/utils/rapidjson/stringbuffer.h>
using namespace TencentCloud::Cfw::V20190904::Model;
using namespace std;
ModifyResourceGroupRequest::ModifyResourceGroupRequest() :
m_groupIdHasBeenSet(false),
m_groupNameHasBeenSet(false),
m_parentIdHasBeenSet(false)
{
}
string ModifyResourceGroupRequest::ToJsonString() const
{
rapidjson::Document d;
d.SetObject();
rapidjson::Document::AllocatorType& allocator = d.GetAllocator();
if (m_groupIdHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "GroupId";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, rapidjson::Value(m_groupId.c_str(), allocator).Move(), allocator);
}
if (m_groupNameHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "GroupName";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, rapidjson::Value(m_groupName.c_str(), allocator).Move(), allocator);
}
if (m_parentIdHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "ParentId";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, rapidjson::Value(m_parentId.c_str(), allocator).Move(), allocator);
}
rapidjson::StringBuffer buffer;
rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
d.Accept(writer);
return buffer.GetString();
}
string ModifyResourceGroupRequest::GetGroupId() const
{
return m_groupId;
}
void ModifyResourceGroupRequest::SetGroupId(const string& _groupId)
{
m_groupId = _groupId;
m_groupIdHasBeenSet = true;
}
bool ModifyResourceGroupRequest::GroupIdHasBeenSet() const
{
return m_groupIdHasBeenSet;
}
string ModifyResourceGroupRequest::GetGroupName() const
{
return m_groupName;
}
void ModifyResourceGroupRequest::SetGroupName(const string& _groupName)
{
m_groupName = _groupName;
m_groupNameHasBeenSet = true;
}
bool ModifyResourceGroupRequest::GroupNameHasBeenSet() const
{
return m_groupNameHasBeenSet;
}
string ModifyResourceGroupRequest::GetParentId() const
{
return m_parentId;
}
void ModifyResourceGroupRequest::SetParentId(const string& _parentId)
{
m_parentId = _parentId;
m_parentIdHasBeenSet = true;
}
bool ModifyResourceGroupRequest::ParentIdHasBeenSet() const
{
return m_parentIdHasBeenSet;
}
| 26.95 | 94 | 0.730983 | [
"model"
] |
290fe3243e81a91c7c38d5bb096816aa30e464cf | 3,491 | cpp | C++ | source/3rdparty/yaml-cpp/binary.cpp | izenecloud/izenelib | 9d5958100e2ce763fc75f27217adf982d7c9d902 | [
"Apache-2.0"
] | 31 | 2015-03-03T19:13:42.000Z | 2020-09-03T08:11:56.000Z | source/3rdparty/yaml-cpp/binary.cpp | izenecloud/izenelib | 9d5958100e2ce763fc75f27217adf982d7c9d902 | [
"Apache-2.0"
] | 1 | 2016-12-24T00:12:11.000Z | 2016-12-24T00:12:11.000Z | source/3rdparty/yaml-cpp/binary.cpp | izenecloud/izenelib | 9d5958100e2ce763fc75f27217adf982d7c9d902 | [
"Apache-2.0"
] | 8 | 2015-09-06T01:55:21.000Z | 2021-12-20T02:16:13.000Z | #include <3rdparty/yaml-cpp/binary.h>
namespace YAML
{
static const char encoding[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
std::string EncodeBase64(const unsigned char *data, std::size_t size)
{
const char PAD = '=';
std::string ret;
ret.resize(4 * size / 3 + 3);
char *out = &ret[0];
std::size_t chunks = size / 3;
std::size_t remainder = size % 3;
for(std::size_t i=0;i<chunks;i++, data += 3) {
*out++ = encoding[data[0] >> 2];
*out++ = encoding[((data[0] & 0x3) << 4) | (data[1] >> 4)];
*out++ = encoding[((data[1] & 0xf) << 2) | (data[2] >> 6)];
*out++ = encoding[data[2] & 0x3f];
}
switch(remainder) {
case 0:
break;
case 1:
*out++ = encoding[data[0] >> 2];
*out++ = encoding[((data[0] & 0x3) << 4)];
*out++ = PAD;
*out++ = PAD;
break;
case 2:
*out++ = encoding[data[0] >> 2];
*out++ = encoding[((data[0] & 0x3) << 4) | (data[1] >> 4)];
*out++ = encoding[((data[1] & 0xf) << 2)];
*out++ = PAD;
break;
}
ret.resize(out - &ret[0]);
return ret;
}
static const unsigned char decoding[] = {
255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
255,255,255,255,255,255,255,255,255,255,255, 62,255,255,255, 63,
52, 53, 54, 55, 56, 57, 58, 59, 60, 61,255,255,255, 0,255,255,
255, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,255,255,255,255,255,
255, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51,255,255,255,255,255,
255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
};
std::vector<unsigned char> DecodeBase64(const std::string& input)
{
typedef std::vector<unsigned char> ret_type;
if(input.empty())
return ret_type();
ret_type ret(3 * input.size() / 4 + 1);
unsigned char *out = &ret[0];
unsigned value = 0;
for(std::size_t i=0;i<input.size();i++) {
unsigned char d = decoding[static_cast<unsigned>(input[i])];
if(d == 255)
return ret_type();
value = (value << 6) | d;
if(i % 4 == 3) {
*out++ = value >> 16;
if(i > 0 && input[i - 1] != '=')
*out++ = value >> 8;
if(input[i] != '=')
*out++ = value;
}
}
ret.resize(out - &ret[0]);
return ret;
}
}
| 37.138298 | 102 | 0.473217 | [
"vector"
] |
29152f8d69a4e19389d69028c183af5c757bbfb4 | 6,301 | cpp | C++ | tools/PictureBenchmark.cpp | gw280/skia | 25fb2434460e7bf541d334ffaa421acb497b9a33 | [
"BSD-3-Clause"
] | null | null | null | tools/PictureBenchmark.cpp | gw280/skia | 25fb2434460e7bf541d334ffaa421acb497b9a33 | [
"BSD-3-Clause"
] | null | null | null | tools/PictureBenchmark.cpp | gw280/skia | 25fb2434460e7bf541d334ffaa421acb497b9a33 | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright 2012 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkTypes.h"
#include "BenchTimer.h"
#include "PictureBenchmark.h"
#include "SkCanvas.h"
#include "SkPicture.h"
#include "SkString.h"
#include "picture_utils.h"
namespace sk_tools {
BenchTimer* PictureBenchmark::setupTimer() {
#if SK_SUPPORT_GPU
PictureRenderer* renderer = getRenderer();
if (renderer != NULL && renderer->isUsingGpuDevice()) {
return SkNEW_ARGS(BenchTimer, (renderer->getGLContext()));
} else {
return SkNEW_ARGS(BenchTimer, (NULL));
}
#else
return SkNEW_ARGS(BenchTimer, (NULL));
#endif
}
void PipePictureBenchmark::run(SkPicture* pict) {
SkASSERT(pict);
if (NULL == pict) {
return;
}
fRenderer.init(pict);
// We throw this away to remove first time effects (such as paging in this
// program)
fRenderer.render();
fRenderer.resetState();
BenchTimer* timer = this->setupTimer();
double wall_time = 0, truncated_wall_time = 0;
#if SK_SUPPORT_GPU
double gpu_time = 0;
#endif
for (int i = 0; i < fRepeats; ++i) {
timer->start();
fRenderer.render();
timer->end();
fRenderer.resetState();
wall_time += timer->fWall;
truncated_wall_time += timer->fTruncatedWall;
#if SK_SUPPORT_GPU
if (fRenderer.isUsingGpuDevice()) {
gpu_time += timer->fGpu;
}
#endif
}
SkString result;
result.printf("pipe: msecs = %6.2f", wall_time / fRepeats);
#if SK_SUPPORT_GPU
if (fRenderer.isUsingGpuDevice()) {
result.appendf(" gmsecs = %6.2f", gpu_time / fRepeats);
}
#endif
result.appendf("\n");
sk_tools::print_msg(result.c_str());
fRenderer.end();
SkDELETE(timer);
}
void RecordPictureBenchmark::run(SkPicture* pict) {
SkASSERT(pict);
if (NULL == pict) {
return;
}
BenchTimer* timer = setupTimer();
double wall_time = 0, truncated_wall_time = 0;
for (int i = 0; i < fRepeats + 1; ++i) {
SkPicture replayer;
timer->start();
SkCanvas* recorder = replayer.beginRecording(pict->width(), pict->height());
pict->draw(recorder);
replayer.endRecording();
timer->end();
// We want to ignore first time effects
if (i > 0) {
wall_time += timer->fWall;
truncated_wall_time += timer->fTruncatedWall;
}
}
SkString result;
result.printf("record: msecs = %6.5f\n", wall_time / fRepeats);
sk_tools::print_msg(result.c_str());
SkDELETE(timer);
}
void SimplePictureBenchmark::run(SkPicture* pict) {
SkASSERT(pict);
if (NULL == pict) {
return;
}
fRenderer.init(pict);
// We throw this away to remove first time effects (such as paging in this
// program)
fRenderer.render();
fRenderer.resetState();
BenchTimer* timer = this->setupTimer();
double wall_time = 0, truncated_wall_time = 0;
#if SK_SUPPORT_GPU
double gpu_time = 0;
#endif
for (int i = 0; i < fRepeats; ++i) {
timer->start();
fRenderer.render();
timer->end();
fRenderer.resetState();
wall_time += timer->fWall;
truncated_wall_time += timer->fTruncatedWall;
#if SK_SUPPORT_GPU
if (fRenderer.isUsingGpuDevice()) {
gpu_time += timer->fGpu;
}
#endif
}
SkString result;
result.printf("simple: msecs = %6.2f", wall_time / fRepeats);
#if SK_SUPPORT_GPU
if (fRenderer.isUsingGpuDevice()) {
result.appendf(" gmsecs = %6.2f", gpu_time / fRepeats);
}
#endif
result.appendf("\n");
sk_tools::print_msg(result.c_str());
fRenderer.end();
SkDELETE(timer);
}
void TiledPictureBenchmark::run(SkPicture* pict) {
SkASSERT(pict);
if (NULL == pict) {
return;
}
fRenderer.init(pict);
// We throw this away to remove first time effects (such as paging in this
// program)
fRenderer.drawTiles();
fRenderer.resetState();
BenchTimer* timer = setupTimer();
double wall_time = 0, truncated_wall_time = 0;
#if SK_SUPPORT_GPU
double gpu_time = 0;
#endif
for (int i = 0; i < fRepeats; ++i) {
timer->start();
fRenderer.drawTiles();
timer->end();
fRenderer.resetState();
wall_time += timer->fWall;
truncated_wall_time += timer->fTruncatedWall;
#if SK_SUPPORT_GPU
if (fRenderer.isUsingGpuDevice()) {
gpu_time += timer->fGpu;
}
#endif
}
SkString result;
if (fRenderer.isMultiThreaded()) {
result.printf("multithreaded using %s ", (fRenderer.isUsePipe() ? "pipe" : "picture"));
}
if (fRenderer.getTileMinPowerOf2Width() > 0) {
result.appendf("%i_pow2tiles_%iminx%i: msecs = %6.2f", fRenderer.numTiles(),
fRenderer.getTileMinPowerOf2Width(), fRenderer.getTileHeight(),
wall_time / fRepeats);
} else {
result.appendf("%i_tiles_%ix%i: msecs = %6.2f", fRenderer.numTiles(),
fRenderer.getTileWidth(), fRenderer.getTileHeight(), wall_time / fRepeats);
}
#if SK_SUPPORT_GPU
if (fRenderer.isUsingGpuDevice()) {
result.appendf(" gmsecs = %6.2f", gpu_time / fRepeats);
}
#endif
result.appendf("\n");
sk_tools::print_msg(result.c_str());
fRenderer.end();
SkDELETE(timer);
}
void UnflattenPictureBenchmark::run(SkPicture* pict) {
SkASSERT(pict);
if (NULL == pict) {
return;
}
BenchTimer* timer = setupTimer();
double wall_time = 0, truncated_wall_time = 0;
for (int i = 0; i < fRepeats + 1; ++i) {
SkPicture replayer;
SkCanvas* recorder = replayer.beginRecording(pict->width(), pict->height());
recorder->drawPicture(*pict);
timer->start();
replayer.endRecording();
timer->end();
// We want to ignore first time effects
if (i > 0) {
wall_time += timer->fWall;
truncated_wall_time += timer->fTruncatedWall;
}
}
SkString result;
result.printf("unflatten: msecs = %6.4f\n", wall_time / fRepeats);
sk_tools::print_msg(result.c_str());
SkDELETE(timer);
}
}
| 24.807087 | 98 | 0.605301 | [
"render"
] |
2916d6d9aff96892c693256daeefeaba01b06eb8 | 8,182 | cpp | C++ | Source/GUI/Qt/prefs.cpp | buckmelanoma/MediaInfo | cf38b0e3d0e6ee2565f49276f423a5792ed62962 | [
"BSD-2-Clause"
] | 743 | 2015-01-13T23:16:53.000Z | 2022-03-31T22:56:27.000Z | Source/GUI/Qt/prefs.cpp | buckmelanoma/MediaInfo | cf38b0e3d0e6ee2565f49276f423a5792ed62962 | [
"BSD-2-Clause"
] | 317 | 2015-07-28T17:50:14.000Z | 2022-03-08T02:41:19.000Z | Source/GUI/Qt/prefs.cpp | buckmelanoma/MediaInfo | cf38b0e3d0e6ee2565f49276f423a5792ed62962 | [
"BSD-2-Clause"
] | 134 | 2015-01-30T05:33:51.000Z | 2022-03-21T09:39:38.000Z | /* Copyright (c) MediaArea.net SARL. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license that can
* be found in the License.html file in the root of the source tree.
*/
#include "prefs.h"
#include "translate.h"
#include "ui_prefs.h"
#include <QLabel>
#include "views.h"
#include "sheet.h"
#include "configtreetext.h"
#include "custom.h"
#include "editsheet.h"
#include "editconfigtreetext.h"
#include "editcustom.h"
Preferences::Preferences(QSettings* settings, Core* C, QWidget *parent) :
QDialog(parent),
ui(new Ui::Preferences)
{
this->settings=settings;
this->C = C;
ui->setupUi(this);
#if defined(_WIN32) && defined(WINAPI_FAMILY) && (WINAPI_FAMILY==WINAPI_FAMILY_APP) // Workaround render bug
QString style = "QComboBox QAbstractItemView { border: 1px solid gray }";
ui->comboBox_defaultview->setStyleSheet(style);
ui->comboBoxSheet->setStyleSheet(style);
ui->customComboBox->setStyleSheet(style);
ui->treeTextComboBox->setStyleSheet(style);
#else
setWindowTitle("Preferences");
#endif
ui->treeWidget->setColumnHidden(1,true);
ui->treeWidget->expandAll();
for(int v=VIEW_EASY;v<NB_VIEW;v++) {
ui->comboBox_defaultview->addItem(nameView((ViewMode)v),v);
}
ui->showMenu->setChecked(settings->value("showMenu",true).toBool());
ui->showToolbar->setChecked(settings->value("showToolbar",true).toBool());
ui->closeAllBeforeOpen->setChecked(settings->value("closeBeforeOpen",true).toBool());
ui->comboBox_defaultview->setCurrentIndex(settings->value("defaultView",VIEW_EASY).toInt());
#ifdef NEW_VERSION
ui->checkForNewVersion->setChecked(settings->value("checkForNewVersion",true).toBool());
#else
ui->checkForNewVersion->setVisible(false);
#endif
#if defined(_WIN32) && defined(WINAPI_FAMILY) && (WINAPI_FAMILY==WINAPI_FAMILY_APP) //Setup UI for winRT
ui->rememberToolBarPosition->setVisible(false);
ui->rememberGeometry->setVisible(false);
ui->showToolbar->setVisible(false);
ui->showMenu->setVisible(false);
ui->shellExtension->setVisible(false);
ui->shellInfoTip->setVisible(false);
#else
ui->rememberToolBarPosition->setChecked(settings->value("rememberToolBarPosition",true).toBool());
ui->rememberGeometry->setChecked(settings->value("rememberGeometry",false).toBool());
ui->showToolbar->setEnabled(ui->showMenu->isChecked());
ui->showMenu->setEnabled(ui->showToolbar->isChecked());
ui->rememberToolBarPosition->setEnabled(ui->showToolbar->isChecked());
#endif
refreshDisplay();
ui->stackedWidget->setCurrentIndex(0);
}
Preferences::~Preferences()
{
delete ui;
}
void Preferences::refreshDisplay() {
// Text&Tree
ConfigTreeText::fillComboBox(ui->treeTextComboBox);
ui->pushButton_editTreeText->setEnabled(ui->treeTextComboBox->itemData(ui->treeTextComboBox->currentIndex()).toInt()>0);
ui->pushButton_deleteTreeText->setEnabled( (ConfigTreeText::getNbConfigTreeTexts()>1) && (ui->treeTextComboBox->itemData(ui->treeTextComboBox->currentIndex()).toInt()>0) );
// Custom
Custom::fillComboBox(ui->customComboBox);
ui->pushButton_editCustom->setEnabled(ui->customComboBox->itemData(ui->customComboBox->currentIndex()).toInt()>0);
ui->pushButton_deleteCustom->setEnabled( (Custom::getNbCustoms()>1) && (ui->customComboBox->itemData(ui->customComboBox->currentIndex()).toInt()>0) );
// Sheets
ui->comboBoxSheet->clear();
for(int i=0;i<Sheet::getNbSheets();i++) {
ui->comboBoxSheet->addItem(Sheet::get(i)->getName(),i);
}
ui->comboBoxSheet->setCurrentIndex(Sheet::getIndex());
ui->pushButton_deleteSheet->setEnabled(Sheet::getNbSheets()>1);
}
void Preferences::saveSettings() {
settings->setValue("showMenu",ui->showMenu->isChecked());
settings->setValue("showToolbar",ui->showToolbar->isChecked());
settings->setValue("closeBeforeOpen",ui->closeAllBeforeOpen->isChecked());
settings->setValue("checkForNewVersion",ui->checkForNewVersion->isChecked());
settings->setValue("defaultView",ui->comboBox_defaultview->currentIndex());
settings->setValue("rememberToolBarPosition",ui->rememberToolBarPosition->isChecked());
settings->setValue("rememberGeometry",ui->rememberGeometry->isChecked());
Sheet::setDefault(ui->comboBoxSheet->itemData(ui->comboBoxSheet->currentIndex()).toInt());
Sheet::save(settings);
ConfigTreeText::setDefault(ui->treeTextComboBox->itemData(ui->treeTextComboBox->currentIndex()).toInt());
ConfigTreeText::save(settings);
Custom::setDefault(ui->customComboBox->itemData(ui->customComboBox->currentIndex()).toInt());
Custom::save(settings);
}
void Preferences::changeEvent(QEvent *e)
{
QDialog::changeEvent(e);
switch (e->type()) {
case QEvent::LanguageChange:
ui->retranslateUi(this);
break;
default:
break;
}
}
void Preferences::on_treeWidget_itemSelectionChanged()
{
if(!ui->treeWidget->selectedItems().first()->data(1,Qt::DisplayRole).isNull())
ui->stackedWidget->setCurrentIndex(ui->treeWidget->selectedItems().first()->data(1,Qt::DisplayRole).toInt());
}
void Preferences::on_pushButton_editSheet_clicked()
{
EditSheet es(Sheet::get(ui->comboBoxSheet->itemData(ui->comboBoxSheet->currentIndex()).toInt()), C, this);
if(es.exec() == QDialog::Accepted) {
es.apply();
refreshDisplay();
} else
qDebug() << "sheet editing cancelled";
}
void Preferences::on_pushButton_newSheet_clicked()
{
Sheet* s = Sheet::add("newsheet");
s->addColumn(Tr("File Name").toStdString().c_str(),300,Stream_General,"CompleteName");
EditSheet es(s, C, this);
if(es.exec() == QDialog::Accepted) {
es.apply();
refreshDisplay();
} else {
Sheet::removeLast();
qDebug() << "new sheet cancelled";
}
}
void Preferences::on_pushButton_deleteSheet_clicked()
{
Sheet::remove(ui->comboBoxSheet->itemData(ui->comboBoxSheet->currentIndex()).toInt());
refreshDisplay();
}
void Preferences::on_pushButton_editTreeText_clicked()
{
EditConfigTreeText ectt(ConfigTreeText::get(ui->treeTextComboBox->itemData(ui->treeTextComboBox->currentIndex()).toInt()), C, this);
if(ectt.exec() == QDialog::Accepted) {
ectt.apply();
refreshDisplay();
} else
qDebug() << "config editing cancelled";
}
void Preferences::on_pushButton_newTreeText_clicked()
{
ConfigTreeText* ctt = ConfigTreeText::add("newconfig");
EditConfigTreeText ectt(ctt, C, this);
if(ectt.exec() == QDialog::Accepted) {
ectt.apply();
refreshDisplay();
} else {
ConfigTreeText::removeLast();
qDebug() << "new config cancelled";
}
}
void Preferences::on_pushButton_deleteTreeText_clicked()
{
ConfigTreeText::remove(ui->treeTextComboBox->itemData(ui->treeTextComboBox->currentIndex()).toInt());
refreshDisplay();
}
void Preferences::on_treeTextComboBox_currentIndexChanged(int index)
{
ui->pushButton_editTreeText->setEnabled(index>0);
ui->pushButton_deleteTreeText->setEnabled( (ConfigTreeText::getNbConfigTreeTexts()>1) && (index>0) );
}
void Preferences::on_pushButton_newCustom_clicked()
{
Custom* c = Custom::add("newconfig");
EditCustom ec(c, C, this);
if(ec.exec() == QDialog::Accepted) {
ec.apply();
refreshDisplay();
} else {
Custom::removeLast();
qDebug() << "new config cancelled";
}
}
void Preferences::on_pushButton_editCustom_clicked()
{
EditCustom ec(Custom::get(ui->customComboBox->itemData(ui->customComboBox->currentIndex()).toInt()), C, this);
if(ec.exec() == QDialog::Accepted) {
ec.apply();
refreshDisplay();
} else
qDebug() << "config editing cancelled";
}
void Preferences::on_pushButton_deleteCustom_clicked()
{
Custom::remove(ui->customComboBox->itemData(ui->customComboBox->currentIndex()).toInt());
refreshDisplay();
}
void Preferences::on_customComboBox_currentIndexChanged(int index)
{
ui->pushButton_editCustom->setEnabled(index>0);
ui->pushButton_deleteCustom->setEnabled( (Custom::getNbCustoms()>1) && (index>0) );
}
| 34.523207 | 176 | 0.698484 | [
"render",
"solid"
] |
2918aeaede8622681cc9251662620d2ae24e6bf7 | 149,479 | cpp | C++ | exportNF/release/windows/obj/src/openfl/display/DisplayObject.cpp | theblobscp/NekoFreakMod-FridayNightFunkin | 232bcb08234cfe881fd6d52b13e6ae443e105fd1 | [
"BSD-3-Clause"
] | null | null | null | exportNF/release/windows/obj/src/openfl/display/DisplayObject.cpp | theblobscp/NekoFreakMod-FridayNightFunkin | 232bcb08234cfe881fd6d52b13e6ae443e105fd1 | [
"BSD-3-Clause"
] | null | null | null | exportNF/release/windows/obj/src/openfl/display/DisplayObject.cpp | theblobscp/NekoFreakMod-FridayNightFunkin | 232bcb08234cfe881fd6d52b13e6ae443e105fd1 | [
"BSD-3-Clause"
] | null | null | null | // Generated by Haxe 4.2.1+bf9ff69
#include <hxcpp.h>
#ifndef INCLUDED_95f339a1d026d52c
#define INCLUDED_95f339a1d026d52c
#include "hxMath.h"
#endif
#ifndef INCLUDED_Std
#include <Std.h>
#endif
#ifndef INCLUDED_haxe_Exception
#include <haxe/Exception.h>
#endif
#ifndef INCLUDED_haxe_IMap
#include <haxe/IMap.h>
#endif
#ifndef INCLUDED_haxe_ds_StringMap
#include <haxe/ds/StringMap.h>
#endif
#ifndef INCLUDED_lime_app_IModule
#include <lime/app/IModule.h>
#endif
#ifndef INCLUDED_lime_graphics_cairo_Cairo
#include <lime/graphics/cairo/Cairo.h>
#endif
#ifndef INCLUDED_lime_utils_ObjectPool
#include <lime/utils/ObjectPool.h>
#endif
#ifndef INCLUDED_openfl__Vector_IVector
#include <openfl/_Vector/IVector.h>
#endif
#ifndef INCLUDED_openfl__Vector_ObjectVector
#include <openfl/_Vector/ObjectVector.h>
#endif
#ifndef INCLUDED_openfl_display_Bitmap
#include <openfl/display/Bitmap.h>
#endif
#ifndef INCLUDED_openfl_display_BitmapData
#include <openfl/display/BitmapData.h>
#endif
#ifndef INCLUDED_openfl_display_DisplayObject
#include <openfl/display/DisplayObject.h>
#endif
#ifndef INCLUDED_openfl_display_DisplayObjectContainer
#include <openfl/display/DisplayObjectContainer.h>
#endif
#ifndef INCLUDED_openfl_display_DisplayObjectRenderer
#include <openfl/display/DisplayObjectRenderer.h>
#endif
#ifndef INCLUDED_openfl_display_Graphics
#include <openfl/display/Graphics.h>
#endif
#ifndef INCLUDED_openfl_display_IBitmapDrawable
#include <openfl/display/IBitmapDrawable.h>
#endif
#ifndef INCLUDED_openfl_display_InteractiveObject
#include <openfl/display/InteractiveObject.h>
#endif
#ifndef INCLUDED_openfl_display_LoaderInfo
#include <openfl/display/LoaderInfo.h>
#endif
#ifndef INCLUDED_openfl_display_MovieClip
#include <openfl/display/MovieClip.h>
#endif
#ifndef INCLUDED_openfl_display_Shader
#include <openfl/display/Shader.h>
#endif
#ifndef INCLUDED_openfl_display_Sprite
#include <openfl/display/Sprite.h>
#endif
#ifndef INCLUDED_openfl_display_Stage
#include <openfl/display/Stage.h>
#endif
#ifndef INCLUDED_openfl_errors_Error
#include <openfl/errors/Error.h>
#endif
#ifndef INCLUDED_openfl_errors_TypeError
#include <openfl/errors/TypeError.h>
#endif
#ifndef INCLUDED_openfl_events_Event
#include <openfl/events/Event.h>
#endif
#ifndef INCLUDED_openfl_events_EventDispatcher
#include <openfl/events/EventDispatcher.h>
#endif
#ifndef INCLUDED_openfl_events_IEventDispatcher
#include <openfl/events/IEventDispatcher.h>
#endif
#ifndef INCLUDED_openfl_events_MouseEvent
#include <openfl/events/MouseEvent.h>
#endif
#ifndef INCLUDED_openfl_events_RenderEvent
#include <openfl/events/RenderEvent.h>
#endif
#ifndef INCLUDED_openfl_events_TouchEvent
#include <openfl/events/TouchEvent.h>
#endif
#ifndef INCLUDED_openfl_filters_BitmapFilter
#include <openfl/filters/BitmapFilter.h>
#endif
#ifndef INCLUDED_openfl_geom_ColorTransform
#include <openfl/geom/ColorTransform.h>
#endif
#ifndef INCLUDED_openfl_geom_Matrix
#include <openfl/geom/Matrix.h>
#endif
#ifndef INCLUDED_openfl_geom_Point
#include <openfl/geom/Point.h>
#endif
#ifndef INCLUDED_openfl_geom_Rectangle
#include <openfl/geom/Rectangle.h>
#endif
#ifndef INCLUDED_openfl_geom_Transform
#include <openfl/geom/Transform.h>
#endif
#ifndef INCLUDED_openfl_utils__internal_Lib
#include <openfl/utils/_internal/Lib.h>
#endif
HX_DEFINE_STACK_FRAME(_hx_pos_26400284d5456c16_1050_new,"openfl.display.DisplayObject","new",0xb225b469,"openfl.display.DisplayObject.new","openfl/display/DisplayObject.hx",1050,0xc7539829)
HX_LOCAL_STACK_FRAME(_hx_pos_26400284d5456c16_1087_addEventListener,"openfl.display.DisplayObject","addEventListener",0xe74b9624,"openfl.display.DisplayObject.addEventListener","openfl/display/DisplayObject.hx",1087,0xc7539829)
HX_LOCAL_STACK_FRAME(_hx_pos_26400284d5456c16_1119_dispatchEvent,"openfl.display.DisplayObject","dispatchEvent",0xe6cd7049,"openfl.display.DisplayObject.dispatchEvent","openfl/display/DisplayObject.hx",1119,0xc7539829)
HX_LOCAL_STACK_FRAME(_hx_pos_26400284d5456c16_1163_getBounds,"openfl.display.DisplayObject","getBounds",0xdb0a2074,"openfl.display.DisplayObject.getBounds","openfl/display/DisplayObject.hx",1163,0xc7539829)
HX_LOCAL_STACK_FRAME(_hx_pos_26400284d5456c16_1213_getRect,"openfl.display.DisplayObject","getRect",0x17591963,"openfl.display.DisplayObject.getRect","openfl/display/DisplayObject.hx",1213,0xc7539829)
HX_LOCAL_STACK_FRAME(_hx_pos_26400284d5456c16_1235_globalToLocal,"openfl.display.DisplayObject","globalToLocal",0x8c16f816,"openfl.display.DisplayObject.globalToLocal","openfl/display/DisplayObject.hx",1235,0xc7539829)
HX_LOCAL_STACK_FRAME(_hx_pos_26400284d5456c16_1249_hitTestObject,"openfl.display.DisplayObject","hitTestObject",0xf7ccfe2d,"openfl.display.DisplayObject.hitTestObject","openfl/display/DisplayObject.hx",1249,0xc7539829)
HX_LOCAL_STACK_FRAME(_hx_pos_26400284d5456c16_1279_hitTestPoint,"openfl.display.DisplayObject","hitTestPoint",0x05917ca2,"openfl.display.DisplayObject.hitTestPoint","openfl/display/DisplayObject.hx",1279,0xc7539829)
HX_LOCAL_STACK_FRAME(_hx_pos_26400284d5456c16_1295_invalidate,"openfl.display.DisplayObject","invalidate",0x11e2b892,"openfl.display.DisplayObject.invalidate","openfl/display/DisplayObject.hx",1295,0xc7539829)
HX_LOCAL_STACK_FRAME(_hx_pos_26400284d5456c16_1323_localToGlobal,"openfl.display.DisplayObject","localToGlobal",0x6853eb12,"openfl.display.DisplayObject.localToGlobal","openfl/display/DisplayObject.hx",1323,0xc7539829)
HX_LOCAL_STACK_FRAME(_hx_pos_26400284d5456c16_1330_removeEventListener,"openfl.display.DisplayObject","removeEventListener",0x3ae1cdd3,"openfl.display.DisplayObject.removeEventListener","openfl/display/DisplayObject.hx",1330,0xc7539829)
HX_LOCAL_STACK_FRAME(_hx_pos_26400284d5456c16_1369___cleanup,"openfl.display.DisplayObject","__cleanup",0x25266dcd,"openfl.display.DisplayObject.__cleanup","openfl/display/DisplayObject.hx",1369,0xc7539829)
HX_LOCAL_STACK_FRAME(_hx_pos_26400284d5456c16_1396___dispatch,"openfl.display.DisplayObject","__dispatch",0x4c54e0f1,"openfl.display.DisplayObject.__dispatch","openfl/display/DisplayObject.hx",1396,0xc7539829)
HX_LOCAL_STACK_FRAME(_hx_pos_26400284d5456c16_1412___dispatchChildren,"openfl.display.DisplayObject","__dispatchChildren",0xdb948f50,"openfl.display.DisplayObject.__dispatchChildren","openfl/display/DisplayObject.hx",1412,0xc7539829)
HX_LOCAL_STACK_FRAME(_hx_pos_26400284d5456c16_1415___dispatchEvent,"openfl.display.DisplayObject","__dispatchEvent",0xd8f34d69,"openfl.display.DisplayObject.__dispatchEvent","openfl/display/DisplayObject.hx",1415,0xc7539829)
HX_LOCAL_STACK_FRAME(_hx_pos_26400284d5456c16_1440___dispatchWithCapture,"openfl.display.DisplayObject","__dispatchWithCapture",0x81f3d9af,"openfl.display.DisplayObject.__dispatchWithCapture","openfl/display/DisplayObject.hx",1440,0xc7539829)
HX_LOCAL_STACK_FRAME(_hx_pos_26400284d5456c16_1481___enterFrame,"openfl.display.DisplayObject","__enterFrame",0x5c5351ec,"openfl.display.DisplayObject.__enterFrame","openfl/display/DisplayObject.hx",1481,0xc7539829)
HX_LOCAL_STACK_FRAME(_hx_pos_26400284d5456c16_1485___getBounds,"openfl.display.DisplayObject","__getBounds",0xe772ed94,"openfl.display.DisplayObject.__getBounds","openfl/display/DisplayObject.hx",1485,0xc7539829)
HX_LOCAL_STACK_FRAME(_hx_pos_26400284d5456c16_1493___getCursor,"openfl.display.DisplayObject","__getCursor",0xc03df5f5,"openfl.display.DisplayObject.__getCursor","openfl/display/DisplayObject.hx",1493,0xc7539829)
HX_LOCAL_STACK_FRAME(_hx_pos_26400284d5456c16_1497___getFilterBounds,"openfl.display.DisplayObject","__getFilterBounds",0x4d6bbcac,"openfl.display.DisplayObject.__getFilterBounds","openfl/display/DisplayObject.hx",1497,0xc7539829)
HX_LOCAL_STACK_FRAME(_hx_pos_26400284d5456c16_1524___getInteractive,"openfl.display.DisplayObject","__getInteractive",0xee1ea663,"openfl.display.DisplayObject.__getInteractive","openfl/display/DisplayObject.hx",1524,0xc7539829)
HX_LOCAL_STACK_FRAME(_hx_pos_26400284d5456c16_1528___getLocalBounds,"openfl.display.DisplayObject","__getLocalBounds",0xd51d8ec1,"openfl.display.DisplayObject.__getLocalBounds","openfl/display/DisplayObject.hx",1528,0xc7539829)
HX_LOCAL_STACK_FRAME(_hx_pos_26400284d5456c16_1544___getRenderBounds,"openfl.display.DisplayObject","__getRenderBounds",0xb06992ca,"openfl.display.DisplayObject.__getRenderBounds","openfl/display/DisplayObject.hx",1544,0xc7539829)
HX_LOCAL_STACK_FRAME(_hx_pos_26400284d5456c16_1561___getRenderTransform,"openfl.display.DisplayObject","__getRenderTransform",0x9985c437,"openfl.display.DisplayObject.__getRenderTransform","openfl/display/DisplayObject.hx",1561,0xc7539829)
HX_LOCAL_STACK_FRAME(_hx_pos_26400284d5456c16_1567___getWorldTransform,"openfl.display.DisplayObject","__getWorldTransform",0x71693ad9,"openfl.display.DisplayObject.__getWorldTransform","openfl/display/DisplayObject.hx",1567,0xc7539829)
HX_LOCAL_STACK_FRAME(_hx_pos_26400284d5456c16_1602___globalToLocal,"openfl.display.DisplayObject","__globalToLocal",0x7e3cd536,"openfl.display.DisplayObject.__globalToLocal","openfl/display/DisplayObject.hx",1602,0xc7539829)
HX_LOCAL_STACK_FRAME(_hx_pos_26400284d5456c16_1619___hitTest,"openfl.display.DisplayObject","__hitTest",0x5c63c1ee,"openfl.display.DisplayObject.__hitTest","openfl/display/DisplayObject.hx",1619,0xc7539829)
HX_LOCAL_STACK_FRAME(_hx_pos_26400284d5456c16_1640___hitTestMask,"openfl.display.DisplayObject","__hitTestMask",0x5c65bdfa,"openfl.display.DisplayObject.__hitTestMask","openfl/display/DisplayObject.hx",1640,0xc7539829)
HX_LOCAL_STACK_FRAME(_hx_pos_26400284d5456c16_1654___readGraphicsData,"openfl.display.DisplayObject","__readGraphicsData",0xd9311e42,"openfl.display.DisplayObject.__readGraphicsData","openfl/display/DisplayObject.hx",1654,0xc7539829)
HX_LOCAL_STACK_FRAME(_hx_pos_26400284d5456c16_1661___setParentRenderDirty,"openfl.display.DisplayObject","__setParentRenderDirty",0x844e2287,"openfl.display.DisplayObject.__setParentRenderDirty","openfl/display/DisplayObject.hx",1661,0xc7539829)
HX_LOCAL_STACK_FRAME(_hx_pos_26400284d5456c16_1672___setRenderDirty,"openfl.display.DisplayObject","__setRenderDirty",0x7766cdd1,"openfl.display.DisplayObject.__setRenderDirty","openfl/display/DisplayObject.hx",1672,0xc7539829)
HX_LOCAL_STACK_FRAME(_hx_pos_26400284d5456c16_1681___setStageReference,"openfl.display.DisplayObject","__setStageReference",0xda522b58,"openfl.display.DisplayObject.__setStageReference","openfl/display/DisplayObject.hx",1681,0xc7539829)
HX_LOCAL_STACK_FRAME(_hx_pos_26400284d5456c16_1686___setTransformDirty,"openfl.display.DisplayObject","__setTransformDirty",0x7e906131,"openfl.display.DisplayObject.__setTransformDirty","openfl/display/DisplayObject.hx",1686,0xc7539829)
HX_LOCAL_STACK_FRAME(_hx_pos_26400284d5456c16_1697___setWorldTransformInvalid,"openfl.display.DisplayObject","__setWorldTransformInvalid",0x82c84692,"openfl.display.DisplayObject.__setWorldTransformInvalid","openfl/display/DisplayObject.hx",1697,0xc7539829)
HX_LOCAL_STACK_FRAME(_hx_pos_26400284d5456c16_1700___stopAllMovieClips,"openfl.display.DisplayObject","__stopAllMovieClips",0x3954cfdb,"openfl.display.DisplayObject.__stopAllMovieClips","openfl/display/DisplayObject.hx",1700,0xc7539829)
HX_LOCAL_STACK_FRAME(_hx_pos_26400284d5456c16_1703___update,"openfl.display.DisplayObject","__update",0x3f3ecc80,"openfl.display.DisplayObject.__update","openfl/display/DisplayObject.hx",1703,0xc7539829)
HX_LOCAL_STACK_FRAME(_hx_pos_26400284d5456c16_1828___updateTransforms,"openfl.display.DisplayObject","__updateTransforms",0x37510227,"openfl.display.DisplayObject.__updateTransforms","openfl/display/DisplayObject.hx",1828,0xc7539829)
HX_LOCAL_STACK_FRAME(_hx_pos_26400284d5456c16_1871_get_alpha,"openfl.display.DisplayObject","get_alpha",0x5dd6147e,"openfl.display.DisplayObject.get_alpha","openfl/display/DisplayObject.hx",1871,0xc7539829)
HX_LOCAL_STACK_FRAME(_hx_pos_26400284d5456c16_1875_set_alpha,"openfl.display.DisplayObject","set_alpha",0x4127008a,"openfl.display.DisplayObject.set_alpha","openfl/display/DisplayObject.hx",1875,0xc7539829)
HX_LOCAL_STACK_FRAME(_hx_pos_26400284d5456c16_1885_get_blendMode,"openfl.display.DisplayObject","get_blendMode",0xee046174,"openfl.display.DisplayObject.get_blendMode","openfl/display/DisplayObject.hx",1885,0xc7539829)
HX_LOCAL_STACK_FRAME(_hx_pos_26400284d5456c16_1889_set_blendMode,"openfl.display.DisplayObject","set_blendMode",0x330a4380,"openfl.display.DisplayObject.set_blendMode","openfl/display/DisplayObject.hx",1889,0xc7539829)
HX_LOCAL_STACK_FRAME(_hx_pos_26400284d5456c16_1898_get_cacheAsBitmap,"openfl.display.DisplayObject","get_cacheAsBitmap",0xa5311003,"openfl.display.DisplayObject.get_cacheAsBitmap","openfl/display/DisplayObject.hx",1898,0xc7539829)
HX_LOCAL_STACK_FRAME(_hx_pos_26400284d5456c16_1902_set_cacheAsBitmap,"openfl.display.DisplayObject","set_cacheAsBitmap",0xc89ee80f,"openfl.display.DisplayObject.set_cacheAsBitmap","openfl/display/DisplayObject.hx",1902,0xc7539829)
HX_LOCAL_STACK_FRAME(_hx_pos_26400284d5456c16_1913_get_cacheAsBitmapMatrix,"openfl.display.DisplayObject","get_cacheAsBitmapMatrix",0xe47a1ea4,"openfl.display.DisplayObject.get_cacheAsBitmapMatrix","openfl/display/DisplayObject.hx",1913,0xc7539829)
HX_LOCAL_STACK_FRAME(_hx_pos_26400284d5456c16_1917_set_cacheAsBitmapMatrix,"openfl.display.DisplayObject","set_cacheAsBitmapMatrix",0xe6db87b0,"openfl.display.DisplayObject.set_cacheAsBitmapMatrix","openfl/display/DisplayObject.hx",1917,0xc7539829)
HX_LOCAL_STACK_FRAME(_hx_pos_26400284d5456c16_1924_get_filters,"openfl.display.DisplayObject","get_filters",0x661396db,"openfl.display.DisplayObject.get_filters","openfl/display/DisplayObject.hx",1924,0xc7539829)
HX_LOCAL_STACK_FRAME(_hx_pos_26400284d5456c16_1935_set_filters,"openfl.display.DisplayObject","set_filters",0x70809de7,"openfl.display.DisplayObject.set_filters","openfl/display/DisplayObject.hx",1935,0xc7539829)
HX_LOCAL_STACK_FRAME(_hx_pos_26400284d5456c16_1955_get_height,"openfl.display.DisplayObject","get_height",0x7d8c16c7,"openfl.display.DisplayObject.get_height","openfl/display/DisplayObject.hx",1955,0xc7539829)
HX_LOCAL_STACK_FRAME(_hx_pos_26400284d5456c16_1964_set_height,"openfl.display.DisplayObject","set_height",0x8109b53b,"openfl.display.DisplayObject.set_height","openfl/display/DisplayObject.hx",1964,0xc7539829)
HX_LOCAL_STACK_FRAME(_hx_pos_26400284d5456c16_1987_get_loaderInfo,"openfl.display.DisplayObject","get_loaderInfo",0x6805b101,"openfl.display.DisplayObject.get_loaderInfo","openfl/display/DisplayObject.hx",1987,0xc7539829)
HX_LOCAL_STACK_FRAME(_hx_pos_26400284d5456c16_1998_get_mask,"openfl.display.DisplayObject","get_mask",0xd81ad7cc,"openfl.display.DisplayObject.get_mask","openfl/display/DisplayObject.hx",1998,0xc7539829)
HX_LOCAL_STACK_FRAME(_hx_pos_26400284d5456c16_2002_set_mask,"openfl.display.DisplayObject","set_mask",0x86783140,"openfl.display.DisplayObject.set_mask","openfl/display/DisplayObject.hx",2002,0xc7539829)
HX_LOCAL_STACK_FRAME(_hx_pos_26400284d5456c16_2038_get_mouseX,"openfl.display.DisplayObject","get_mouseX",0x474e5973,"openfl.display.DisplayObject.get_mouseX","openfl/display/DisplayObject.hx",2038,0xc7539829)
HX_LOCAL_STACK_FRAME(_hx_pos_26400284d5456c16_2046_get_mouseY,"openfl.display.DisplayObject","get_mouseY",0x474e5974,"openfl.display.DisplayObject.get_mouseY","openfl/display/DisplayObject.hx",2046,0xc7539829)
HX_LOCAL_STACK_FRAME(_hx_pos_26400284d5456c16_2055_get_name,"openfl.display.DisplayObject","get_name",0xd8c4092b,"openfl.display.DisplayObject.get_name","openfl/display/DisplayObject.hx",2055,0xc7539829)
HX_LOCAL_STACK_FRAME(_hx_pos_26400284d5456c16_2060_set_name,"openfl.display.DisplayObject","set_name",0x8721629f,"openfl.display.DisplayObject.set_name","openfl/display/DisplayObject.hx",2060,0xc7539829)
HX_LOCAL_STACK_FRAME(_hx_pos_26400284d5456c16_2064_get_root,"openfl.display.DisplayObject","get_root",0xdb738502,"openfl.display.DisplayObject.get_root","openfl/display/DisplayObject.hx",2064,0xc7539829)
HX_LOCAL_STACK_FRAME(_hx_pos_26400284d5456c16_2075_get_rotation,"openfl.display.DisplayObject","get_rotation",0xdf0fc41e,"openfl.display.DisplayObject.get_rotation","openfl/display/DisplayObject.hx",2075,0xc7539829)
HX_LOCAL_STACK_FRAME(_hx_pos_26400284d5456c16_2079_set_rotation,"openfl.display.DisplayObject","set_rotation",0xf408e792,"openfl.display.DisplayObject.set_rotation","openfl/display/DisplayObject.hx",2079,0xc7539829)
HX_LOCAL_STACK_FRAME(_hx_pos_26400284d5456c16_2099_get_scale9Grid,"openfl.display.DisplayObject","get_scale9Grid",0x40434fb5,"openfl.display.DisplayObject.get_scale9Grid","openfl/display/DisplayObject.hx",2099,0xc7539829)
HX_LOCAL_STACK_FRAME(_hx_pos_26400284d5456c16_2109_set_scale9Grid,"openfl.display.DisplayObject","set_scale9Grid",0x60633829,"openfl.display.DisplayObject.set_scale9Grid","openfl/display/DisplayObject.hx",2109,0xc7539829)
HX_LOCAL_STACK_FRAME(_hx_pos_26400284d5456c16_2130_get_scaleX,"openfl.display.DisplayObject","get_scaleX",0xb765f96e,"openfl.display.DisplayObject.get_scaleX","openfl/display/DisplayObject.hx",2130,0xc7539829)
HX_LOCAL_STACK_FRAME(_hx_pos_26400284d5456c16_2134_set_scaleX,"openfl.display.DisplayObject","set_scaleX",0xbae397e2,"openfl.display.DisplayObject.set_scaleX","openfl/display/DisplayObject.hx",2134,0xc7539829)
HX_LOCAL_STACK_FRAME(_hx_pos_26400284d5456c16_2164_get_scaleY,"openfl.display.DisplayObject","get_scaleY",0xb765f96f,"openfl.display.DisplayObject.get_scaleY","openfl/display/DisplayObject.hx",2164,0xc7539829)
HX_LOCAL_STACK_FRAME(_hx_pos_26400284d5456c16_2168_set_scaleY,"openfl.display.DisplayObject","set_scaleY",0xbae397e3,"openfl.display.DisplayObject.set_scaleY","openfl/display/DisplayObject.hx",2168,0xc7539829)
HX_LOCAL_STACK_FRAME(_hx_pos_26400284d5456c16_2197_get_scrollRect,"openfl.display.DisplayObject","get_scrollRect",0xba87dab1,"openfl.display.DisplayObject.get_scrollRect","openfl/display/DisplayObject.hx",2197,0xc7539829)
HX_LOCAL_STACK_FRAME(_hx_pos_26400284d5456c16_2207_set_scrollRect,"openfl.display.DisplayObject","set_scrollRect",0xdaa7c325,"openfl.display.DisplayObject.set_scrollRect","openfl/display/DisplayObject.hx",2207,0xc7539829)
HX_LOCAL_STACK_FRAME(_hx_pos_26400284d5456c16_2233_get_shader,"openfl.display.DisplayObject","get_shader",0x9860ce05,"openfl.display.DisplayObject.get_shader","openfl/display/DisplayObject.hx",2233,0xc7539829)
HX_LOCAL_STACK_FRAME(_hx_pos_26400284d5456c16_2237_set_shader,"openfl.display.DisplayObject","set_shader",0x9bde6c79,"openfl.display.DisplayObject.set_shader","openfl/display/DisplayObject.hx",2237,0xc7539829)
HX_LOCAL_STACK_FRAME(_hx_pos_26400284d5456c16_2244_get_transform,"openfl.display.DisplayObject","get_transform",0x275faa8c,"openfl.display.DisplayObject.get_transform","openfl/display/DisplayObject.hx",2244,0xc7539829)
HX_LOCAL_STACK_FRAME(_hx_pos_26400284d5456c16_2254_set_transform,"openfl.display.DisplayObject","set_transform",0x6c658c98,"openfl.display.DisplayObject.set_transform","openfl/display/DisplayObject.hx",2254,0xc7539829)
HX_LOCAL_STACK_FRAME(_hx_pos_26400284d5456c16_2280_get_visible,"openfl.display.DisplayObject","get_visible",0xfff16d92,"openfl.display.DisplayObject.get_visible","openfl/display/DisplayObject.hx",2280,0xc7539829)
HX_LOCAL_STACK_FRAME(_hx_pos_26400284d5456c16_2284_set_visible,"openfl.display.DisplayObject","set_visible",0x0a5e749e,"openfl.display.DisplayObject.set_visible","openfl/display/DisplayObject.hx",2284,0xc7539829)
HX_LOCAL_STACK_FRAME(_hx_pos_26400284d5456c16_2290_get_width,"openfl.display.DisplayObject","get_width",0x06a22326,"openfl.display.DisplayObject.get_width","openfl/display/DisplayObject.hx",2290,0xc7539829)
HX_LOCAL_STACK_FRAME(_hx_pos_26400284d5456c16_2299_set_width,"openfl.display.DisplayObject","set_width",0xe9f30f32,"openfl.display.DisplayObject.set_width","openfl/display/DisplayObject.hx",2299,0xc7539829)
HX_LOCAL_STACK_FRAME(_hx_pos_26400284d5456c16_2323_get_x,"openfl.display.DisplayObject","get_x",0xc67a5d98,"openfl.display.DisplayObject.get_x","openfl/display/DisplayObject.hx",2323,0xc7539829)
HX_LOCAL_STACK_FRAME(_hx_pos_26400284d5456c16_2327_set_x,"openfl.display.DisplayObject","set_x",0xaf4953a4,"openfl.display.DisplayObject.set_x","openfl/display/DisplayObject.hx",2327,0xc7539829)
HX_LOCAL_STACK_FRAME(_hx_pos_26400284d5456c16_2334_get_y,"openfl.display.DisplayObject","get_y",0xc67a5d99,"openfl.display.DisplayObject.get_y","openfl/display/DisplayObject.hx",2334,0xc7539829)
HX_LOCAL_STACK_FRAME(_hx_pos_26400284d5456c16_2338_set_y,"openfl.display.DisplayObject","set_y",0xaf4953a5,"openfl.display.DisplayObject.set_y","openfl/display/DisplayObject.hx",2338,0xc7539829)
HX_LOCAL_STACK_FRAME(_hx_pos_26400284d5456c16_1359___calculateAbsoluteTransform,"openfl.display.DisplayObject","__calculateAbsoluteTransform",0xba65dba6,"openfl.display.DisplayObject.__calculateAbsoluteTransform","openfl/display/DisplayObject.hx",1359,0xc7539829)
HX_LOCAL_STACK_FRAME(_hx_pos_26400284d5456c16_182_boot,"openfl.display.DisplayObject","boot",0x26f12809,"openfl.display.DisplayObject.boot","openfl/display/DisplayObject.hx",182,0xc7539829)
HX_LOCAL_STACK_FRAME(_hx_pos_26400284d5456c16_184_boot,"openfl.display.DisplayObject","boot",0x26f12809,"openfl.display.DisplayObject.boot","openfl/display/DisplayObject.hx",184,0xc7539829)
HX_LOCAL_STACK_FRAME(_hx_pos_26400284d5456c16_186_boot,"openfl.display.DisplayObject","boot",0x26f12809,"openfl.display.DisplayObject.boot","openfl/display/DisplayObject.hx",186,0xc7539829)
HX_LOCAL_STACK_FRAME(_hx_pos_26400284d5456c16_189_boot,"openfl.display.DisplayObject","boot",0x26f12809,"openfl.display.DisplayObject.boot","openfl/display/DisplayObject.hx",189,0xc7539829)
HX_LOCAL_STACK_FRAME(_hx_pos_26400284d5456c16_191_boot,"openfl.display.DisplayObject","boot",0x26f12809,"openfl.display.DisplayObject.boot","openfl/display/DisplayObject.hx",191,0xc7539829)
HX_LOCAL_STACK_FRAME(_hx_pos_26400284d5456c16_192_boot,"openfl.display.DisplayObject","boot",0x26f12809,"openfl.display.DisplayObject.boot","openfl/display/DisplayObject.hx",192,0xc7539829)
namespace openfl{
namespace display{
void DisplayObject_obj::__construct(){
HX_GC_STACKFRAME(&_hx_pos_26400284d5456c16_1050_new)
HXLINE(1051) super::__construct(null());
HXLINE(1053) this->_hx___drawableType = 1;
HXLINE(1055) this->_hx___alpha = ( (Float)(1) );
HXLINE(1056) this->_hx___blendMode = 10;
HXLINE(1057) this->_hx___cacheAsBitmap = false;
HXLINE(1058) this->_hx___transform = ::openfl::geom::Matrix_obj::__alloc( HX_CTX ,null(),null(),null(),null(),null(),null());
HXLINE(1059) this->_hx___visible = true;
HXLINE(1061) this->_hx___rotation = ( (Float)(0) );
HXLINE(1062) this->_hx___rotationSine = ( (Float)(0) );
HXLINE(1063) this->_hx___rotationCosine = ( (Float)(1) );
HXLINE(1064) this->_hx___scaleX = ( (Float)(1) );
HXLINE(1065) this->_hx___scaleY = ( (Float)(1) );
HXLINE(1067) this->_hx___worldAlpha = ( (Float)(1) );
HXLINE(1068) this->_hx___worldBlendMode = 10;
HXLINE(1069) this->_hx___worldTransform = ::openfl::geom::Matrix_obj::__alloc( HX_CTX ,null(),null(),null(),null(),null(),null());
HXLINE(1070) this->_hx___worldColorTransform = ::openfl::geom::ColorTransform_obj::__alloc( HX_CTX ,null(),null(),null(),null(),null(),null(),null(),null());
HXLINE(1071) this->_hx___renderTransform = ::openfl::geom::Matrix_obj::__alloc( HX_CTX ,null(),null(),null(),null(),null(),null());
HXLINE(1072) this->_hx___worldVisible = true;
HXLINE(1074) this->set_name((HX_("instance",95,1f,e1,59) + ++::openfl::display::DisplayObject_obj::_hx___instanceCount));
HXLINE(1076) if (::hx::IsNotNull( ::openfl::display::DisplayObject_obj::_hx___initStage )) {
HXLINE(1078) this->stage = ::openfl::display::DisplayObject_obj::_hx___initStage;
HXLINE(1079) ::openfl::display::DisplayObject_obj::_hx___initStage = null();
HXLINE(1080) this->stage->addChild(::hx::ObjectPtr<OBJ_>(this));
}
}
Dynamic DisplayObject_obj::__CreateEmpty() { return new DisplayObject_obj; }
void *DisplayObject_obj::_hx_vtable = 0;
Dynamic DisplayObject_obj::__Create(::hx::DynamicArray inArgs)
{
::hx::ObjectPtr< DisplayObject_obj > _hx_result = new DisplayObject_obj();
_hx_result->__construct();
return _hx_result;
}
bool DisplayObject_obj::_hx_isInstanceOf(int inClassId) {
if (inClassId<=(int)0x0c89e854) {
return inClassId==(int)0x00000001 || inClassId==(int)0x0c89e854;
} else {
return inClassId==(int)0x6b353933;
}
}
static ::openfl::display::IBitmapDrawable_obj _hx_openfl_display_DisplayObject__hx_openfl_display_IBitmapDrawable= {
( void (::hx::Object::*)( ::openfl::geom::Rectangle, ::openfl::geom::Matrix))&::openfl::display::DisplayObject_obj::_hx___getBounds,
( void (::hx::Object::*)(bool,bool))&::openfl::display::DisplayObject_obj::_hx___update,
( void (::hx::Object::*)( ::openfl::geom::Matrix))&::openfl::display::DisplayObject_obj::_hx___updateTransforms,
};
void *DisplayObject_obj::_hx_getInterface(int inHash) {
switch(inHash) {
case (int)0xc1c6fbe4: return &_hx_openfl_display_DisplayObject__hx_openfl_display_IBitmapDrawable;
}
return super::_hx_getInterface(inHash);
}
void DisplayObject_obj::addEventListener(::String type, ::Dynamic listener,::hx::Null< bool > __o_useCapture,::hx::Null< int > __o_priority,::hx::Null< bool > __o_useWeakReference){
bool useCapture = __o_useCapture.Default(false);
int priority = __o_priority.Default(0);
bool useWeakReference = __o_useWeakReference.Default(false);
HX_GC_STACKFRAME(&_hx_pos_26400284d5456c16_1087_addEventListener)
HXLINE(1088) ::String _hx_switch_0 = type;
if ( (_hx_switch_0==HX_("activate",b3,1b,ac,e5)) || (_hx_switch_0==HX_("deactivate",34,5c,01,3c)) || (_hx_switch_0==HX_("enterFrame",f5,03,50,02)) || (_hx_switch_0==HX_("exitFrame",2f,64,48,12)) || (_hx_switch_0==HX_("frameConstructed",09,89,5d,98)) || (_hx_switch_0==HX_("render",56,6b,29,05)) ){
HXLINE(1091) if (!(::openfl::display::DisplayObject_obj::_hx___broadcastEvents->exists(type))) {
HXLINE(1093) ::openfl::display::DisplayObject_obj::_hx___broadcastEvents->set(type,::Array_obj< ::Dynamic>::__new(0));
}
HXLINE(1096) ::Array< ::Dynamic> dispatchers = ( (::Array< ::Dynamic>)(::openfl::display::DisplayObject_obj::_hx___broadcastEvents->get(type)) );
HXLINE(1098) if ((dispatchers->indexOf(::hx::ObjectPtr<OBJ_>(this),null()) == -1)) {
HXLINE(1100) dispatchers->push(::hx::ObjectPtr<OBJ_>(this));
}
HXLINE(1090) goto _hx_goto_1;
}
if ( (_hx_switch_0==HX_("clearDOM",f5,22,08,31)) || (_hx_switch_0==HX_("renderCairo",52,5d,ca,0c)) || (_hx_switch_0==HX_("renderCanvas",ce,58,98,27)) || (_hx_switch_0==HX_("renderDOM",cc,ac,57,cd)) || (_hx_switch_0==HX_("renderOpenGL",65,4c,ea,90)) ){
HXLINE(1104) if (::hx::IsNull( this->_hx___customRenderEvent )) {
HXLINE(1106) this->_hx___customRenderEvent = ::openfl::events::RenderEvent_obj::__alloc( HX_CTX ,null(),null(),null(),null(),null(),null());
HXLINE(1107) this->_hx___customRenderEvent->objectColorTransform = ::openfl::geom::ColorTransform_obj::__alloc( HX_CTX ,null(),null(),null(),null(),null(),null(),null(),null());
HXLINE(1108) this->_hx___customRenderEvent->objectMatrix = ::openfl::geom::Matrix_obj::__alloc( HX_CTX ,null(),null(),null(),null(),null(),null());
HXLINE(1109) this->_hx___customRenderClear = true;
}
HXLINE(1104) goto _hx_goto_1;
}
/* default */{
}
_hx_goto_1:;
HXLINE(1115) this->super::addEventListener(type,listener,useCapture,priority,useWeakReference);
}
bool DisplayObject_obj::dispatchEvent( ::openfl::events::Event event){
HX_STACKFRAME(&_hx_pos_26400284d5456c16_1119_dispatchEvent)
HXLINE(1120) if (::Std_obj::isOfType(event,::hx::ClassOf< ::openfl::events::MouseEvent >())) {
HXLINE(1122) ::openfl::events::MouseEvent mouseEvent = ( ( ::openfl::events::MouseEvent)(event) );
HXLINE(1123) ::openfl::geom::Matrix _this = this->_hx___getRenderTransform();
HXDLIN(1123) mouseEvent->stageX = (((mouseEvent->localX * _this->a) + (mouseEvent->localY * _this->c)) + _this->tx);
HXLINE(1124) ::openfl::geom::Matrix _this1 = this->_hx___getRenderTransform();
HXDLIN(1124) mouseEvent->stageY = (((mouseEvent->localX * _this1->b) + (mouseEvent->localY * _this1->d)) + _this1->ty);
}
else {
HXLINE(1126) if (::Std_obj::isOfType(event,::hx::ClassOf< ::openfl::events::TouchEvent >())) {
HXLINE(1128) ::openfl::events::TouchEvent touchEvent = ( ( ::openfl::events::TouchEvent)(event) );
HXLINE(1129) ::openfl::geom::Matrix _this = this->_hx___getRenderTransform();
HXDLIN(1129) touchEvent->stageX = (((touchEvent->localX * _this->a) + (touchEvent->localY * _this->c)) + _this->tx);
HXLINE(1130) ::openfl::geom::Matrix _this1 = this->_hx___getRenderTransform();
HXDLIN(1130) touchEvent->stageY = (((touchEvent->localX * _this1->b) + (touchEvent->localY * _this1->d)) + _this1->ty);
}
}
HXLINE(1133) event->target = ::hx::ObjectPtr<OBJ_>(this);
HXLINE(1135) return this->_hx___dispatchWithCapture(event);
}
::openfl::geom::Rectangle DisplayObject_obj::getBounds( ::openfl::display::DisplayObject targetCoordinateSpace){
HX_GC_STACKFRAME(&_hx_pos_26400284d5456c16_1163_getBounds)
HXLINE(1164) ::openfl::geom::Matrix matrix = ::openfl::geom::Matrix_obj::_hx___pool->get().StaticCast< ::openfl::geom::Matrix >();
HXLINE(1166) bool _hx_tmp;
HXDLIN(1166) if (::hx::IsNotNull( targetCoordinateSpace )) {
HXLINE(1166) _hx_tmp = ::hx::IsInstanceNotEq( targetCoordinateSpace,::hx::ObjectPtr<OBJ_>(this) );
}
else {
HXLINE(1166) _hx_tmp = false;
}
HXDLIN(1166) if (_hx_tmp) {
HXLINE(1168) matrix->copyFrom(this->_hx___getWorldTransform());
HXLINE(1170) ::openfl::geom::Matrix targetMatrix = ::openfl::geom::Matrix_obj::_hx___pool->get().StaticCast< ::openfl::geom::Matrix >();
HXLINE(1172) targetMatrix->copyFrom(targetCoordinateSpace->_hx___getWorldTransform());
HXLINE(1173) targetMatrix->invert();
HXLINE(1175) matrix->concat(targetMatrix);
HXLINE(1177) ::openfl::geom::Matrix_obj::_hx___pool->release(targetMatrix);
}
else {
HXLINE(1181) matrix->identity();
}
HXLINE(1184) ::openfl::geom::Rectangle bounds = ::openfl::geom::Rectangle_obj::__alloc( HX_CTX ,null(),null(),null(),null());
HXLINE(1185) this->_hx___getBounds(bounds,matrix);
HXLINE(1187) ::openfl::geom::Matrix_obj::_hx___pool->release(matrix);
HXLINE(1189) return bounds;
}
HX_DEFINE_DYNAMIC_FUNC1(DisplayObject_obj,getBounds,return )
::openfl::geom::Rectangle DisplayObject_obj::getRect( ::openfl::display::DisplayObject targetCoordinateSpace){
HX_STACKFRAME(&_hx_pos_26400284d5456c16_1213_getRect)
HXDLIN(1213) return this->getBounds(targetCoordinateSpace);
}
HX_DEFINE_DYNAMIC_FUNC1(DisplayObject_obj,getRect,return )
::openfl::geom::Point DisplayObject_obj::globalToLocal( ::openfl::geom::Point pos){
HX_GC_STACKFRAME(&_hx_pos_26400284d5456c16_1235_globalToLocal)
HXDLIN(1235) return this->_hx___globalToLocal(pos, ::openfl::geom::Point_obj::__alloc( HX_CTX ,null(),null()));
}
HX_DEFINE_DYNAMIC_FUNC1(DisplayObject_obj,globalToLocal,return )
bool DisplayObject_obj::hitTestObject( ::openfl::display::DisplayObject obj){
HX_STACKFRAME(&_hx_pos_26400284d5456c16_1249_hitTestObject)
HXLINE(1250) bool _hx_tmp;
HXDLIN(1250) bool _hx_tmp1;
HXDLIN(1250) if (::hx::IsNotNull( obj )) {
HXLINE(1250) _hx_tmp1 = ::hx::IsNotNull( obj->parent );
}
else {
HXLINE(1250) _hx_tmp1 = false;
}
HXDLIN(1250) if (_hx_tmp1) {
HXLINE(1250) _hx_tmp = ::hx::IsNotNull( this->parent );
}
else {
HXLINE(1250) _hx_tmp = false;
}
HXDLIN(1250) if (_hx_tmp) {
HXLINE(1252) ::openfl::geom::Rectangle currentBounds = this->getBounds(::hx::ObjectPtr<OBJ_>(this));
HXLINE(1253) ::openfl::geom::Rectangle targetBounds = obj->getBounds(::hx::ObjectPtr<OBJ_>(this));
HXLINE(1255) return currentBounds->intersects(targetBounds);
}
HXLINE(1258) return false;
}
HX_DEFINE_DYNAMIC_FUNC1(DisplayObject_obj,hitTestObject,return )
bool DisplayObject_obj::hitTestPoint(Float x,Float y,::hx::Null< bool > __o_shapeFlag){
bool shapeFlag = __o_shapeFlag.Default(false);
HX_STACKFRAME(&_hx_pos_26400284d5456c16_1279_hitTestPoint)
HXDLIN(1279) if (::hx::IsNotNull( this->stage )) {
HXLINE(1281) return this->_hx___hitTest(x,y,shapeFlag,null(),false,::hx::ObjectPtr<OBJ_>(this));
}
else {
HXLINE(1285) return false;
}
HXLINE(1279) return false;
}
HX_DEFINE_DYNAMIC_FUNC3(DisplayObject_obj,hitTestPoint,return )
void DisplayObject_obj::invalidate(){
HX_STACKFRAME(&_hx_pos_26400284d5456c16_1295_invalidate)
HXDLIN(1295) if (!(this->_hx___renderDirty)) {
HXDLIN(1295) this->_hx___renderDirty = true;
HXDLIN(1295) this->_hx___setParentRenderDirty();
}
}
HX_DEFINE_DYNAMIC_FUNC0(DisplayObject_obj,invalidate,(void))
::openfl::geom::Point DisplayObject_obj::localToGlobal( ::openfl::geom::Point point){
HX_STACKFRAME(&_hx_pos_26400284d5456c16_1323_localToGlobal)
HXDLIN(1323) return this->_hx___getRenderTransform()->transformPoint(point);
}
HX_DEFINE_DYNAMIC_FUNC1(DisplayObject_obj,localToGlobal,return )
void DisplayObject_obj::removeEventListener(::String type, ::Dynamic listener,::hx::Null< bool > __o_useCapture){
bool useCapture = __o_useCapture.Default(false);
HX_STACKFRAME(&_hx_pos_26400284d5456c16_1330_removeEventListener)
HXLINE(1331) this->super::removeEventListener(type,listener,useCapture);
HXLINE(1333) ::String _hx_switch_0 = type;
if ( (_hx_switch_0==HX_("activate",b3,1b,ac,e5)) || (_hx_switch_0==HX_("deactivate",34,5c,01,3c)) || (_hx_switch_0==HX_("enterFrame",f5,03,50,02)) || (_hx_switch_0==HX_("exitFrame",2f,64,48,12)) || (_hx_switch_0==HX_("frameConstructed",09,89,5d,98)) || (_hx_switch_0==HX_("render",56,6b,29,05)) ){
HXLINE(1336) if (!(this->hasEventListener(type))) {
HXLINE(1338) if (::openfl::display::DisplayObject_obj::_hx___broadcastEvents->exists(type)) {
HXLINE(1340) ( (::Array< ::Dynamic>)(::openfl::display::DisplayObject_obj::_hx___broadcastEvents->get(type)) )->remove(::hx::ObjectPtr<OBJ_>(this));
}
}
HXLINE(1336) goto _hx_goto_11;
}
if ( (_hx_switch_0==HX_("clearDOM",f5,22,08,31)) || (_hx_switch_0==HX_("renderCairo",52,5d,ca,0c)) || (_hx_switch_0==HX_("renderCanvas",ce,58,98,27)) || (_hx_switch_0==HX_("renderDOM",cc,ac,57,cd)) || (_hx_switch_0==HX_("renderOpenGL",65,4c,ea,90)) ){
HXLINE(1345) bool _hx_tmp;
HXDLIN(1345) bool _hx_tmp1;
HXDLIN(1345) bool _hx_tmp2;
HXDLIN(1345) bool _hx_tmp3;
HXDLIN(1345) if (!(this->hasEventListener(HX_("clearDOM",f5,22,08,31)))) {
HXLINE(1345) _hx_tmp3 = !(this->hasEventListener(HX_("renderCairo",52,5d,ca,0c)));
}
else {
HXLINE(1345) _hx_tmp3 = false;
}
HXDLIN(1345) if (_hx_tmp3) {
HXLINE(1345) _hx_tmp2 = !(this->hasEventListener(HX_("renderCanvas",ce,58,98,27)));
}
else {
HXLINE(1345) _hx_tmp2 = false;
}
HXDLIN(1345) if (_hx_tmp2) {
HXLINE(1345) _hx_tmp1 = !(this->hasEventListener(HX_("renderDOM",cc,ac,57,cd)));
}
else {
HXLINE(1345) _hx_tmp1 = false;
}
HXDLIN(1345) if (_hx_tmp1) {
HXLINE(1345) _hx_tmp = !(this->hasEventListener(HX_("renderOpenGL",65,4c,ea,90)));
}
else {
HXLINE(1345) _hx_tmp = false;
}
HXDLIN(1345) if (_hx_tmp) {
HXLINE(1351) this->_hx___customRenderEvent = null();
}
HXLINE(1345) goto _hx_goto_11;
}
/* default */{
}
_hx_goto_11:;
}
void DisplayObject_obj::_hx___cleanup(){
HX_STACKFRAME(&_hx_pos_26400284d5456c16_1369___cleanup)
HXLINE(1370) this->_hx___cairo = null();
HXLINE(1377) if (::hx::IsNotNull( this->_hx___graphics )) {
HXLINE(1379) this->_hx___graphics->_hx___cleanup();
}
HXLINE(1382) if (::hx::IsNotNull( this->_hx___cacheBitmap )) {
HXLINE(1384) this->_hx___cacheBitmap->_hx___cleanup();
HXLINE(1385) this->_hx___cacheBitmap = null();
}
HXLINE(1388) if (::hx::IsNotNull( this->_hx___cacheBitmapData )) {
HXLINE(1390) this->_hx___cacheBitmapData->dispose();
HXLINE(1391) this->_hx___cacheBitmapData = null();
}
}
HX_DEFINE_DYNAMIC_FUNC0(DisplayObject_obj,_hx___cleanup,(void))
bool DisplayObject_obj::_hx___dispatch( ::openfl::events::Event event){
HX_STACKFRAME(&_hx_pos_26400284d5456c16_1396___dispatch)
HXLINE(1397) bool _hx_tmp;
HXDLIN(1397) if (::hx::IsNotNull( this->_hx___eventMap )) {
HXLINE(1397) _hx_tmp = this->hasEventListener(event->type);
}
else {
HXLINE(1397) _hx_tmp = false;
}
HXDLIN(1397) if (_hx_tmp) {
HXLINE(1399) bool result = this->super::_hx___dispatchEvent(event);
HXLINE(1401) if (event->_hx___isCanceled) {
HXLINE(1403) return true;
}
HXLINE(1406) return result;
}
HXLINE(1409) return true;
}
HX_DEFINE_DYNAMIC_FUNC1(DisplayObject_obj,_hx___dispatch,return )
void DisplayObject_obj::_hx___dispatchChildren( ::openfl::events::Event event){
HX_STACKFRAME(&_hx_pos_26400284d5456c16_1412___dispatchChildren)
}
HX_DEFINE_DYNAMIC_FUNC1(DisplayObject_obj,_hx___dispatchChildren,(void))
bool DisplayObject_obj::_hx___dispatchEvent( ::openfl::events::Event event){
HX_STACKFRAME(&_hx_pos_26400284d5456c16_1415___dispatchEvent)
HXLINE(1416) ::openfl::display::DisplayObjectContainer parent;
HXDLIN(1416) if (event->bubbles) {
HXLINE(1416) parent = this->parent;
}
else {
HXLINE(1416) parent = null();
}
HXLINE(1417) bool result = this->super::_hx___dispatchEvent(event);
HXLINE(1419) if (event->_hx___isCanceled) {
HXLINE(1421) return true;
}
HXLINE(1424) bool _hx_tmp;
HXDLIN(1424) if (::hx::IsNotNull( parent )) {
HXLINE(1424) _hx_tmp = ::hx::IsInstanceNotEq( parent,::hx::ObjectPtr<OBJ_>(this) );
}
else {
HXLINE(1424) _hx_tmp = false;
}
HXDLIN(1424) if (_hx_tmp) {
HXLINE(1426) event->eventPhase = 3;
HXLINE(1428) if (::hx::IsNull( event->target )) {
HXLINE(1430) event->target = ::hx::ObjectPtr<OBJ_>(this);
}
HXLINE(1433) parent->_hx___dispatchEvent(event);
}
HXLINE(1436) return result;
}
bool DisplayObject_obj::_hx___dispatchWithCapture( ::openfl::events::Event event){
HX_STACKFRAME(&_hx_pos_26400284d5456c16_1440___dispatchWithCapture)
HXLINE(1441) if (::hx::IsNull( event->target )) {
HXLINE(1443) event->target = ::hx::ObjectPtr<OBJ_>(this);
}
HXLINE(1446) if (::hx::IsNotNull( this->parent )) {
HXLINE(1448) event->eventPhase = 1;
HXLINE(1450) if (::hx::IsInstanceEq( this->parent,this->stage )) {
HXLINE(1452) this->parent->_hx___dispatch(event);
}
else {
HXLINE(1456) ::openfl::_Vector::ObjectVector stack = ::openfl::display::DisplayObject_obj::_hx___tempStack->get().StaticCast< ::openfl::_Vector::ObjectVector >();
HXLINE(1457) ::openfl::display::DisplayObjectContainer parent = this->parent;
HXLINE(1458) int i = 0;
HXLINE(1460) while(::hx::IsNotNull( parent )){
HXLINE(1462) stack->set(i,( ( ::openfl::display::DisplayObject)(parent) )).StaticCast< ::openfl::display::DisplayObject >();
HXLINE(1463) parent = parent->parent;
HXLINE(1464) i = (i + 1);
}
HXLINE(1467) {
HXLINE(1467) int _g = 0;
HXDLIN(1467) int _g1 = i;
HXDLIN(1467) while((_g < _g1)){
HXLINE(1467) _g = (_g + 1);
HXDLIN(1467) int j = (_g - 1);
HXLINE(1469) stack->get(((i - j) - 1)).StaticCast< ::openfl::display::DisplayObject >()->_hx___dispatch(event);
}
}
HXLINE(1472) ::openfl::display::DisplayObject_obj::_hx___tempStack->release(stack);
}
}
HXLINE(1476) event->eventPhase = 2;
HXLINE(1478) return this->_hx___dispatchEvent(event);
}
HX_DEFINE_DYNAMIC_FUNC1(DisplayObject_obj,_hx___dispatchWithCapture,return )
void DisplayObject_obj::_hx___enterFrame(int deltaTime){
HX_STACKFRAME(&_hx_pos_26400284d5456c16_1481___enterFrame)
}
HX_DEFINE_DYNAMIC_FUNC1(DisplayObject_obj,_hx___enterFrame,(void))
void DisplayObject_obj::_hx___getBounds( ::openfl::geom::Rectangle rect, ::openfl::geom::Matrix matrix){
HX_STACKFRAME(&_hx_pos_26400284d5456c16_1485___getBounds)
HXDLIN(1485) if (::hx::IsNotNull( this->_hx___graphics )) {
HXLINE(1487) this->_hx___graphics->_hx___getBounds(rect,matrix);
}
}
HX_DEFINE_DYNAMIC_FUNC2(DisplayObject_obj,_hx___getBounds,(void))
::String DisplayObject_obj::_hx___getCursor(){
HX_STACKFRAME(&_hx_pos_26400284d5456c16_1493___getCursor)
HXDLIN(1493) return null();
}
HX_DEFINE_DYNAMIC_FUNC0(DisplayObject_obj,_hx___getCursor,return )
void DisplayObject_obj::_hx___getFilterBounds( ::openfl::geom::Rectangle rect, ::openfl::geom::Matrix matrix){
HX_STACKFRAME(&_hx_pos_26400284d5456c16_1497___getFilterBounds)
HXLINE(1498) this->_hx___getRenderBounds(rect,matrix);
HXLINE(1500) if (::hx::IsNotNull( this->_hx___filters )) {
HXLINE(1502) ::openfl::geom::Rectangle extension = ::openfl::geom::Rectangle_obj::_hx___pool->get().StaticCast< ::openfl::geom::Rectangle >();
HXLINE(1504) {
HXLINE(1504) int _g = 0;
HXDLIN(1504) ::Array< ::Dynamic> _g1 = this->_hx___filters;
HXDLIN(1504) while((_g < _g1->length)){
HXLINE(1504) ::openfl::filters::BitmapFilter filter = _g1->__get(_g).StaticCast< ::openfl::filters::BitmapFilter >();
HXDLIN(1504) _g = (_g + 1);
HXLINE(1506) extension->_hx___expand(( (Float)(-(filter->_hx___leftExtension)) ),( (Float)(-(filter->_hx___topExtension)) ),( (Float)((filter->_hx___leftExtension + filter->_hx___rightExtension)) ),( (Float)((filter->_hx___topExtension + filter->_hx___bottomExtension)) ));
}
}
HXLINE(1513) ::openfl::geom::Rectangle rect1 = rect;
HXDLIN(1513) rect1->width = (rect1->width + extension->width);
HXLINE(1514) ::openfl::geom::Rectangle rect2 = rect;
HXDLIN(1514) rect2->height = (rect2->height + extension->height);
HXLINE(1515) ::openfl::geom::Rectangle rect3 = rect;
HXDLIN(1515) rect3->x = (rect3->x + extension->x);
HXLINE(1516) ::openfl::geom::Rectangle rect4 = rect;
HXDLIN(1516) rect4->y = (rect4->y + extension->y);
HXLINE(1518) ::openfl::geom::Rectangle_obj::_hx___pool->release(extension);
}
}
HX_DEFINE_DYNAMIC_FUNC2(DisplayObject_obj,_hx___getFilterBounds,(void))
bool DisplayObject_obj::_hx___getInteractive(::Array< ::Dynamic> stack){
HX_STACKFRAME(&_hx_pos_26400284d5456c16_1524___getInteractive)
HXDLIN(1524) return false;
}
HX_DEFINE_DYNAMIC_FUNC1(DisplayObject_obj,_hx___getInteractive,return )
void DisplayObject_obj::_hx___getLocalBounds( ::openfl::geom::Rectangle rect){
HX_STACKFRAME(&_hx_pos_26400284d5456c16_1528___getLocalBounds)
HXLINE(1533) this->_hx___getBounds(rect,this->_hx___transform);
HXLINE(1538) ::openfl::geom::Rectangle rect1 = rect;
HXDLIN(1538) rect1->x = (rect1->x - this->_hx___transform->tx);
HXLINE(1539) ::openfl::geom::Rectangle rect2 = rect;
HXDLIN(1539) rect2->y = (rect2->y - this->_hx___transform->ty);
}
HX_DEFINE_DYNAMIC_FUNC1(DisplayObject_obj,_hx___getLocalBounds,(void))
void DisplayObject_obj::_hx___getRenderBounds( ::openfl::geom::Rectangle rect, ::openfl::geom::Matrix matrix){
HX_STACKFRAME(&_hx_pos_26400284d5456c16_1544___getRenderBounds)
HXDLIN(1544) if (::hx::IsNull( this->_hx___scrollRect )) {
HXLINE(1546) this->_hx___getBounds(rect,matrix);
}
else {
HXLINE(1552) ::openfl::geom::Rectangle r = ::openfl::geom::Rectangle_obj::_hx___pool->get().StaticCast< ::openfl::geom::Rectangle >();
HXLINE(1553) r->copyFrom(this->_hx___scrollRect);
HXLINE(1554) r->_hx___transform(r,matrix);
HXLINE(1555) rect->_hx___expand(r->x,r->y,r->width,r->height);
HXLINE(1556) ::openfl::geom::Rectangle_obj::_hx___pool->release(r);
}
}
HX_DEFINE_DYNAMIC_FUNC2(DisplayObject_obj,_hx___getRenderBounds,(void))
::openfl::geom::Matrix DisplayObject_obj::_hx___getRenderTransform(){
HX_STACKFRAME(&_hx_pos_26400284d5456c16_1561___getRenderTransform)
HXLINE(1562) this->_hx___getWorldTransform();
HXLINE(1563) return this->_hx___renderTransform;
}
HX_DEFINE_DYNAMIC_FUNC0(DisplayObject_obj,_hx___getRenderTransform,return )
::openfl::geom::Matrix DisplayObject_obj::_hx___getWorldTransform(){
HX_STACKFRAME(&_hx_pos_26400284d5456c16_1567___getWorldTransform)
HXLINE(1568) bool transformDirty;
HXDLIN(1568) if (!(this->_hx___transformDirty)) {
HXLINE(1568) transformDirty = this->_hx___worldTransformInvalid;
}
else {
HXLINE(1568) transformDirty = true;
}
HXLINE(1570) if (transformDirty) {
HXLINE(1572) ::Array< ::Dynamic> list = ::Array_obj< ::Dynamic>::__new(0);
HXLINE(1573) ::openfl::display::DisplayObject current = ::hx::ObjectPtr<OBJ_>(this);
HXLINE(1575) if (::hx::IsNull( this->parent )) {
HXLINE(1577) this->_hx___update(true,false);
}
else {
HXLINE(1581) while(::hx::IsInstanceNotEq( current,this->stage )){
HXLINE(1583) list->push(current);
HXLINE(1584) current = current->parent;
HXLINE(1586) if (::hx::IsNull( current )) {
HXLINE(1586) goto _hx_goto_29;
}
}
_hx_goto_29:;
}
HXLINE(1590) int i = list->length;
HXLINE(1591) while(true){
HXLINE(1591) i = (i - 1);
HXDLIN(1591) if (!((i >= 0))) {
HXLINE(1591) goto _hx_goto_30;
}
HXLINE(1593) current = list->__get(i).StaticCast< ::openfl::display::DisplayObject >();
HXLINE(1594) current->_hx___update(true,false);
}
_hx_goto_30:;
}
HXLINE(1598) return this->_hx___worldTransform;
}
HX_DEFINE_DYNAMIC_FUNC0(DisplayObject_obj,_hx___getWorldTransform,return )
::openfl::geom::Point DisplayObject_obj::_hx___globalToLocal( ::openfl::geom::Point global, ::openfl::geom::Point local){
HX_STACKFRAME(&_hx_pos_26400284d5456c16_1602___globalToLocal)
HXLINE(1603) this->_hx___getRenderTransform();
HXLINE(1605) if (::hx::IsInstanceEq( global,local )) {
HXLINE(1607) ::openfl::geom::Matrix _this = this->_hx___renderTransform;
HXDLIN(1607) Float norm = ((_this->a * _this->d) - (_this->b * _this->c));
HXDLIN(1607) if ((norm == 0)) {
HXLINE(1607) global->x = -(_this->tx);
HXDLIN(1607) global->y = -(_this->ty);
}
else {
HXLINE(1607) Float px = ((((Float)1.0) / norm) * ((_this->c * (_this->ty - global->y)) + (_this->d * (global->x - _this->tx))));
HXDLIN(1607) global->y = ((((Float)1.0) / norm) * ((_this->a * (global->y - _this->ty)) + (_this->b * (_this->tx - global->x))));
HXDLIN(1607) global->x = px;
}
}
else {
HXLINE(1611) ::openfl::geom::Matrix _this = this->_hx___renderTransform;
HXDLIN(1611) Float norm = ((_this->a * _this->d) - (_this->b * _this->c));
HXDLIN(1611) Float _hx_tmp;
HXDLIN(1611) if ((norm == 0)) {
HXLINE(1611) _hx_tmp = -(_this->tx);
}
else {
HXLINE(1611) _hx_tmp = ((((Float)1.0) / norm) * ((_this->c * (_this->ty - global->y)) + (_this->d * (global->x - _this->tx))));
}
HXDLIN(1611) local->x = _hx_tmp;
HXLINE(1612) ::openfl::geom::Matrix _this1 = this->_hx___renderTransform;
HXDLIN(1612) Float norm1 = ((_this1->a * _this1->d) - (_this1->b * _this1->c));
HXDLIN(1612) Float _hx_tmp1;
HXDLIN(1612) if ((norm1 == 0)) {
HXLINE(1612) _hx_tmp1 = -(_this1->ty);
}
else {
HXLINE(1612) _hx_tmp1 = ((((Float)1.0) / norm1) * ((_this1->a * (global->y - _this1->ty)) + (_this1->b * (_this1->tx - global->x))));
}
HXDLIN(1612) local->y = _hx_tmp1;
}
HXLINE(1615) return local;
}
HX_DEFINE_DYNAMIC_FUNC2(DisplayObject_obj,_hx___globalToLocal,return )
bool DisplayObject_obj::_hx___hitTest(Float x,Float y,bool shapeFlag,::Array< ::Dynamic> stack,bool interactiveOnly, ::openfl::display::DisplayObject hitObject){
HX_STACKFRAME(&_hx_pos_26400284d5456c16_1619___hitTest)
HXLINE(1620) if (::hx::IsNotNull( this->_hx___graphics )) {
HXLINE(1622) bool _hx_tmp;
HXDLIN(1622) if (hitObject->_hx___visible) {
HXLINE(1622) _hx_tmp = this->_hx___isMask;
}
else {
HXLINE(1622) _hx_tmp = true;
}
HXDLIN(1622) if (_hx_tmp) {
HXLINE(1622) return false;
}
HXLINE(1623) bool _hx_tmp1;
HXDLIN(1623) if (::hx::IsNotNull( this->get_mask() )) {
HXLINE(1623) _hx_tmp1 = !(this->get_mask()->_hx___hitTestMask(x,y));
}
else {
HXLINE(1623) _hx_tmp1 = false;
}
HXDLIN(1623) if (_hx_tmp1) {
HXLINE(1623) return false;
}
HXLINE(1625) ::openfl::display::Graphics _hx_tmp2 = this->_hx___graphics;
HXDLIN(1625) if (_hx_tmp2->_hx___hitTest(x,y,shapeFlag,this->_hx___getRenderTransform())) {
HXLINE(1627) bool _hx_tmp;
HXDLIN(1627) if (::hx::IsNotNull( stack )) {
HXLINE(1627) _hx_tmp = !(interactiveOnly);
}
else {
HXLINE(1627) _hx_tmp = false;
}
HXDLIN(1627) if (_hx_tmp) {
HXLINE(1629) stack->push(hitObject);
}
HXLINE(1632) return true;
}
}
HXLINE(1636) return false;
}
HX_DEFINE_DYNAMIC_FUNC6(DisplayObject_obj,_hx___hitTest,return )
bool DisplayObject_obj::_hx___hitTestMask(Float x,Float y){
HX_STACKFRAME(&_hx_pos_26400284d5456c16_1640___hitTestMask)
HXLINE(1641) if (::hx::IsNotNull( this->_hx___graphics )) {
HXLINE(1643) ::openfl::display::Graphics _hx_tmp = this->_hx___graphics;
HXDLIN(1643) if (_hx_tmp->_hx___hitTest(x,y,true,this->_hx___getRenderTransform())) {
HXLINE(1645) return true;
}
}
HXLINE(1649) return false;
}
HX_DEFINE_DYNAMIC_FUNC2(DisplayObject_obj,_hx___hitTestMask,return )
void DisplayObject_obj::_hx___readGraphicsData( ::openfl::_Vector::ObjectVector graphicsData,bool recurse){
HX_STACKFRAME(&_hx_pos_26400284d5456c16_1654___readGraphicsData)
HXDLIN(1654) if (::hx::IsNotNull( this->_hx___graphics )) {
HXLINE(1656) this->_hx___graphics->_hx___readGraphicsData(graphicsData);
}
}
HX_DEFINE_DYNAMIC_FUNC2(DisplayObject_obj,_hx___readGraphicsData,(void))
void DisplayObject_obj::_hx___setParentRenderDirty(){
HX_STACKFRAME(&_hx_pos_26400284d5456c16_1661___setParentRenderDirty)
HXLINE(1662) ::openfl::display::DisplayObject renderParent;
HXDLIN(1662) if (::hx::IsNotNull( this->_hx___renderParent )) {
HXLINE(1662) renderParent = this->_hx___renderParent;
}
else {
HXLINE(1662) renderParent = this->parent;
}
HXLINE(1663) bool _hx_tmp;
HXDLIN(1663) if (::hx::IsNotNull( renderParent )) {
HXLINE(1663) _hx_tmp = !(renderParent->_hx___renderDirty);
}
else {
HXLINE(1663) _hx_tmp = false;
}
HXDLIN(1663) if (_hx_tmp) {
HXLINE(1665) renderParent->_hx___renderDirty = true;
HXLINE(1666) renderParent->_hx___setParentRenderDirty();
}
}
HX_DEFINE_DYNAMIC_FUNC0(DisplayObject_obj,_hx___setParentRenderDirty,(void))
void DisplayObject_obj::_hx___setRenderDirty(){
HX_STACKFRAME(&_hx_pos_26400284d5456c16_1672___setRenderDirty)
HXDLIN(1672) if (!(this->_hx___renderDirty)) {
HXLINE(1674) this->_hx___renderDirty = true;
HXLINE(1675) this->_hx___setParentRenderDirty();
}
}
HX_DEFINE_DYNAMIC_FUNC0(DisplayObject_obj,_hx___setRenderDirty,(void))
void DisplayObject_obj::_hx___setStageReference( ::openfl::display::Stage stage){
HX_STACKFRAME(&_hx_pos_26400284d5456c16_1681___setStageReference)
HXDLIN(1681) this->stage = stage;
}
HX_DEFINE_DYNAMIC_FUNC1(DisplayObject_obj,_hx___setStageReference,(void))
void DisplayObject_obj::_hx___setTransformDirty(){
HX_STACKFRAME(&_hx_pos_26400284d5456c16_1686___setTransformDirty)
HXDLIN(1686) if (!(this->_hx___transformDirty)) {
HXLINE(1688) this->_hx___transformDirty = true;
HXLINE(1690) this->_hx___setWorldTransformInvalid();
HXLINE(1691) this->_hx___setParentRenderDirty();
}
}
HX_DEFINE_DYNAMIC_FUNC0(DisplayObject_obj,_hx___setTransformDirty,(void))
void DisplayObject_obj::_hx___setWorldTransformInvalid(){
HX_STACKFRAME(&_hx_pos_26400284d5456c16_1697___setWorldTransformInvalid)
HXDLIN(1697) this->_hx___worldTransformInvalid = true;
}
HX_DEFINE_DYNAMIC_FUNC0(DisplayObject_obj,_hx___setWorldTransformInvalid,(void))
void DisplayObject_obj::_hx___stopAllMovieClips(){
HX_STACKFRAME(&_hx_pos_26400284d5456c16_1700___stopAllMovieClips)
}
HX_DEFINE_DYNAMIC_FUNC0(DisplayObject_obj,_hx___stopAllMovieClips,(void))
void DisplayObject_obj::_hx___update(bool transformOnly,bool updateChildren){
HX_STACKFRAME(&_hx_pos_26400284d5456c16_1703___update)
HXLINE(1704) ::openfl::display::DisplayObject renderParent;
HXDLIN(1704) if (::hx::IsNotNull( this->_hx___renderParent )) {
HXLINE(1704) renderParent = this->_hx___renderParent;
}
else {
HXLINE(1704) renderParent = this->parent;
}
HXLINE(1705) bool _hx_tmp;
HXDLIN(1705) if (this->_hx___isMask) {
HXLINE(1705) _hx_tmp = ::hx::IsNull( renderParent );
}
else {
HXLINE(1705) _hx_tmp = false;
}
HXDLIN(1705) if (_hx_tmp) {
HXLINE(1705) renderParent = this->_hx___maskTarget;
}
HXLINE(1706) bool _hx_tmp1;
HXDLIN(1706) bool _hx_tmp2;
HXDLIN(1706) bool _hx_tmp3;
HXDLIN(1706) bool _hx_tmp4;
HXDLIN(1706) if (this->_hx___visible) {
HXLINE(1706) _hx_tmp4 = (this->_hx___scaleX != 0);
}
else {
HXLINE(1706) _hx_tmp4 = false;
}
HXDLIN(1706) if (_hx_tmp4) {
HXLINE(1706) _hx_tmp3 = (this->_hx___scaleY != 0);
}
else {
HXLINE(1706) _hx_tmp3 = false;
}
HXDLIN(1706) if (_hx_tmp3) {
HXLINE(1706) _hx_tmp2 = !(this->_hx___isMask);
}
else {
HXLINE(1706) _hx_tmp2 = false;
}
HXDLIN(1706) if (_hx_tmp2) {
HXLINE(1706) if (::hx::IsNotNull( renderParent )) {
HXLINE(1706) _hx_tmp1 = !(renderParent->_hx___isMask);
}
else {
HXLINE(1706) _hx_tmp1 = true;
}
}
else {
HXLINE(1706) _hx_tmp1 = false;
}
HXDLIN(1706) this->_hx___renderable = _hx_tmp1;
HXLINE(1707) this->_hx___updateTransforms(null());
HXLINE(1711) this->_hx___transformDirty = false;
HXLINE(1715) this->_hx___worldTransformInvalid = false;
HXLINE(1717) if (!(transformOnly)) {
HXLINE(1733) if (::hx::IsNotNull( renderParent )) {
HXLINE(1747) Float _hx_tmp = this->get_alpha();
HXDLIN(1747) this->_hx___worldAlpha = (_hx_tmp * renderParent->_hx___worldAlpha);
HXLINE(1750) if (::hx::IsNotNull( this->_hx___objectTransform )) {
HXLINE(1752) this->_hx___worldColorTransform->_hx___copyFrom(this->_hx___objectTransform->_hx___colorTransform);
HXLINE(1753) this->_hx___worldColorTransform->_hx___combine(renderParent->_hx___worldColorTransform);
}
else {
HXLINE(1757) this->_hx___worldColorTransform->_hx___copyFrom(renderParent->_hx___worldColorTransform);
}
HXLINE(1760) bool _hx_tmp1;
HXDLIN(1760) if (::hx::IsNotNull( this->_hx___blendMode )) {
HXLINE(1760) _hx_tmp1 = ::hx::IsEq( this->_hx___blendMode,10 );
}
else {
HXLINE(1760) _hx_tmp1 = true;
}
HXDLIN(1760) if (_hx_tmp1) {
HXLINE(1763) this->_hx___worldBlendMode = renderParent->_hx___worldBlendMode;
}
else {
HXLINE(1767) this->_hx___worldBlendMode = this->_hx___blendMode;
}
HXLINE(1770) if (::hx::IsNull( this->_hx___shader )) {
HXLINE(1772) this->_hx___worldShader = renderParent->_hx___shader;
}
else {
HXLINE(1776) this->_hx___worldShader = this->_hx___shader;
}
HXLINE(1779) if (::hx::IsNull( this->_hx___scale9Grid )) {
HXLINE(1781) this->_hx___worldScale9Grid = renderParent->_hx___scale9Grid;
}
else {
HXLINE(1785) this->_hx___worldScale9Grid = this->_hx___scale9Grid;
}
}
else {
HXLINE(1790) this->_hx___worldAlpha = this->get_alpha();
HXLINE(1800) if (::hx::IsNotNull( this->_hx___objectTransform )) {
HXLINE(1802) this->_hx___worldColorTransform->_hx___copyFrom(this->_hx___objectTransform->_hx___colorTransform);
}
else {
HXLINE(1806) this->_hx___worldColorTransform->_hx___identity();
}
HXLINE(1809) this->_hx___worldBlendMode = this->_hx___blendMode;
HXLINE(1810) this->_hx___worldShader = this->_hx___shader;
HXLINE(1811) this->_hx___worldScale9Grid = this->_hx___scale9Grid;
}
}
HXLINE(1821) bool _hx_tmp5;
HXDLIN(1821) if (updateChildren) {
HXLINE(1821) _hx_tmp5 = ::hx::IsNotNull( this->get_mask() );
}
else {
HXLINE(1821) _hx_tmp5 = false;
}
HXDLIN(1821) if (_hx_tmp5) {
HXLINE(1823) this->get_mask()->_hx___update(transformOnly,true);
}
}
HX_DEFINE_DYNAMIC_FUNC2(DisplayObject_obj,_hx___update,(void))
void DisplayObject_obj::_hx___updateTransforms( ::openfl::geom::Matrix overrideTransform){
HX_GC_STACKFRAME(&_hx_pos_26400284d5456c16_1828___updateTransforms)
HXLINE(1829) bool overrided = ::hx::IsNotNull( overrideTransform );
HXLINE(1830) ::openfl::geom::Matrix local;
HXDLIN(1830) if (overrided) {
HXLINE(1830) local = overrideTransform;
}
else {
HXLINE(1830) local = this->_hx___transform;
}
HXLINE(1832) if (::hx::IsNull( this->_hx___worldTransform )) {
HXLINE(1834) this->_hx___worldTransform = ::openfl::geom::Matrix_obj::__alloc( HX_CTX ,null(),null(),null(),null(),null(),null());
}
HXLINE(1837) if (::hx::IsNull( this->_hx___renderTransform )) {
HXLINE(1839) this->_hx___renderTransform = ::openfl::geom::Matrix_obj::__alloc( HX_CTX ,null(),null(),null(),null(),null(),null());
}
HXLINE(1842) ::openfl::display::DisplayObject renderParent;
HXDLIN(1842) if (::hx::IsNotNull( this->_hx___renderParent )) {
HXLINE(1842) renderParent = this->_hx___renderParent;
}
else {
HXLINE(1842) renderParent = this->parent;
}
HXLINE(1844) bool _hx_tmp;
HXDLIN(1844) if (!(overrided)) {
HXLINE(1844) _hx_tmp = ::hx::IsNotNull( this->parent );
}
else {
HXLINE(1844) _hx_tmp = false;
}
HXDLIN(1844) if (_hx_tmp) {
HXLINE(1846) ::openfl::geom::Matrix parentTransform = this->parent->_hx___worldTransform;
HXDLIN(1846) ::openfl::geom::Matrix target = this->_hx___worldTransform;
HXDLIN(1846) target->a = ((local->a * parentTransform->a) + (local->b * parentTransform->c));
HXDLIN(1846) target->b = ((local->a * parentTransform->b) + (local->b * parentTransform->d));
HXDLIN(1846) target->c = ((local->c * parentTransform->a) + (local->d * parentTransform->c));
HXDLIN(1846) target->d = ((local->c * parentTransform->b) + (local->d * parentTransform->d));
HXDLIN(1846) target->tx = (((local->tx * parentTransform->a) + (local->ty * parentTransform->c)) + parentTransform->tx);
HXDLIN(1846) target->ty = (((local->tx * parentTransform->b) + (local->ty * parentTransform->d)) + parentTransform->ty);
}
else {
HXLINE(1850) this->_hx___worldTransform->copyFrom(local);
}
HXLINE(1853) bool _hx_tmp1;
HXDLIN(1853) if (!(overrided)) {
HXLINE(1853) _hx_tmp1 = ::hx::IsNotNull( renderParent );
}
else {
HXLINE(1853) _hx_tmp1 = false;
}
HXDLIN(1853) if (_hx_tmp1) {
HXLINE(1855) ::openfl::geom::Matrix parentTransform = renderParent->_hx___renderTransform;
HXDLIN(1855) ::openfl::geom::Matrix target = this->_hx___renderTransform;
HXDLIN(1855) target->a = ((local->a * parentTransform->a) + (local->b * parentTransform->c));
HXDLIN(1855) target->b = ((local->a * parentTransform->b) + (local->b * parentTransform->d));
HXDLIN(1855) target->c = ((local->c * parentTransform->a) + (local->d * parentTransform->c));
HXDLIN(1855) target->d = ((local->c * parentTransform->b) + (local->d * parentTransform->d));
HXDLIN(1855) target->tx = (((local->tx * parentTransform->a) + (local->ty * parentTransform->c)) + parentTransform->tx);
HXDLIN(1855) target->ty = (((local->tx * parentTransform->b) + (local->ty * parentTransform->d)) + parentTransform->ty);
}
else {
HXLINE(1859) this->_hx___renderTransform->copyFrom(local);
}
HXLINE(1862) if (::hx::IsNotNull( this->_hx___scrollRect )) {
HXLINE(1864) ::openfl::geom::Matrix _this = this->_hx___renderTransform;
HXDLIN(1864) Float px = -(this->_hx___scrollRect->x);
HXDLIN(1864) Float py = -(this->_hx___scrollRect->y);
HXDLIN(1864) _this->tx = (((px * _this->a) + (py * _this->c)) + _this->tx);
HXDLIN(1864) _this->ty = (((px * _this->b) + (py * _this->d)) + _this->ty);
}
}
HX_DEFINE_DYNAMIC_FUNC1(DisplayObject_obj,_hx___updateTransforms,(void))
Float DisplayObject_obj::get_alpha(){
HX_STACKFRAME(&_hx_pos_26400284d5456c16_1871_get_alpha)
HXDLIN(1871) return this->_hx___alpha;
}
HX_DEFINE_DYNAMIC_FUNC0(DisplayObject_obj,get_alpha,return )
Float DisplayObject_obj::set_alpha(Float value){
HX_STACKFRAME(&_hx_pos_26400284d5456c16_1875_set_alpha)
HXLINE(1876) if ((value > ((Float)1.0))) {
HXLINE(1876) value = ((Float)1.0);
}
HXLINE(1877) if ((value < ((Float)0.0))) {
HXLINE(1877) value = ((Float)0.0);
}
HXLINE(1879) bool _hx_tmp;
HXDLIN(1879) if ((value != this->_hx___alpha)) {
HXLINE(1879) _hx_tmp = !(this->get_cacheAsBitmap());
}
else {
HXLINE(1879) _hx_tmp = false;
}
HXDLIN(1879) if (_hx_tmp) {
HXLINE(1879) if (!(this->_hx___renderDirty)) {
HXLINE(1879) this->_hx___renderDirty = true;
HXDLIN(1879) this->_hx___setParentRenderDirty();
}
}
HXLINE(1880) return (this->_hx___alpha = value);
}
HX_DEFINE_DYNAMIC_FUNC1(DisplayObject_obj,set_alpha,return )
::Dynamic DisplayObject_obj::get_blendMode(){
HX_STACKFRAME(&_hx_pos_26400284d5456c16_1885_get_blendMode)
HXDLIN(1885) return this->_hx___blendMode;
}
HX_DEFINE_DYNAMIC_FUNC0(DisplayObject_obj,get_blendMode,return )
::Dynamic DisplayObject_obj::set_blendMode( ::Dynamic value){
HX_STACKFRAME(&_hx_pos_26400284d5456c16_1889_set_blendMode)
HXLINE(1890) if (::hx::IsNull( value )) {
HXLINE(1890) value = 10;
}
HXLINE(1892) if (::hx::IsNotEq( value,this->_hx___blendMode )) {
HXLINE(1892) if (!(this->_hx___renderDirty)) {
HXLINE(1892) this->_hx___renderDirty = true;
HXDLIN(1892) this->_hx___setParentRenderDirty();
}
}
HXLINE(1893) return (this->_hx___blendMode = value);
}
HX_DEFINE_DYNAMIC_FUNC1(DisplayObject_obj,set_blendMode,return )
bool DisplayObject_obj::get_cacheAsBitmap(){
HX_STACKFRAME(&_hx_pos_26400284d5456c16_1898_get_cacheAsBitmap)
HXDLIN(1898) if (::hx::IsNull( this->_hx___filters )) {
HXDLIN(1898) return this->_hx___cacheAsBitmap;
}
else {
HXDLIN(1898) return true;
}
HXDLIN(1898) return false;
}
HX_DEFINE_DYNAMIC_FUNC0(DisplayObject_obj,get_cacheAsBitmap,return )
bool DisplayObject_obj::set_cacheAsBitmap(bool value){
HX_STACKFRAME(&_hx_pos_26400284d5456c16_1902_set_cacheAsBitmap)
HXLINE(1903) if ((value != this->_hx___cacheAsBitmap)) {
HXLINE(1905) if (!(this->_hx___renderDirty)) {
HXLINE(1905) this->_hx___renderDirty = true;
HXDLIN(1905) this->_hx___setParentRenderDirty();
}
}
HXLINE(1908) return (this->_hx___cacheAsBitmap = value);
}
HX_DEFINE_DYNAMIC_FUNC1(DisplayObject_obj,set_cacheAsBitmap,return )
::openfl::geom::Matrix DisplayObject_obj::get_cacheAsBitmapMatrix(){
HX_STACKFRAME(&_hx_pos_26400284d5456c16_1913_get_cacheAsBitmapMatrix)
HXDLIN(1913) return this->_hx___cacheAsBitmapMatrix;
}
HX_DEFINE_DYNAMIC_FUNC0(DisplayObject_obj,get_cacheAsBitmapMatrix,return )
::openfl::geom::Matrix DisplayObject_obj::set_cacheAsBitmapMatrix( ::openfl::geom::Matrix value){
HX_STACKFRAME(&_hx_pos_26400284d5456c16_1917_set_cacheAsBitmapMatrix)
HXLINE(1918) if (!(this->_hx___renderDirty)) {
HXLINE(1918) this->_hx___renderDirty = true;
HXDLIN(1918) this->_hx___setParentRenderDirty();
}
HXLINE(1919) ::openfl::geom::Matrix _hx_tmp;
HXDLIN(1919) if (::hx::IsNotNull( value )) {
HXLINE(1919) _hx_tmp = value->clone();
}
else {
HXLINE(1919) _hx_tmp = value;
}
HXDLIN(1919) return (this->_hx___cacheAsBitmapMatrix = _hx_tmp);
}
HX_DEFINE_DYNAMIC_FUNC1(DisplayObject_obj,set_cacheAsBitmapMatrix,return )
::Array< ::Dynamic> DisplayObject_obj::get_filters(){
HX_STACKFRAME(&_hx_pos_26400284d5456c16_1924_get_filters)
HXDLIN(1924) if (::hx::IsNull( this->_hx___filters )) {
HXLINE(1926) return ::Array_obj< ::Dynamic>::__new();
}
else {
HXLINE(1930) return this->_hx___filters->copy();
}
HXLINE(1924) return null();
}
HX_DEFINE_DYNAMIC_FUNC0(DisplayObject_obj,get_filters,return )
::Array< ::Dynamic> DisplayObject_obj::set_filters(::Array< ::Dynamic> value){
HX_STACKFRAME(&_hx_pos_26400284d5456c16_1935_set_filters)
HXLINE(1936) bool _hx_tmp;
HXDLIN(1936) if (::hx::IsNotNull( value )) {
HXLINE(1936) _hx_tmp = (value->length > 0);
}
else {
HXLINE(1936) _hx_tmp = false;
}
HXDLIN(1936) if (_hx_tmp) {
HXLINE(1940) this->_hx___filters = value;
HXLINE(1942) if (!(this->_hx___renderDirty)) {
HXLINE(1942) this->_hx___renderDirty = true;
HXDLIN(1942) this->_hx___setParentRenderDirty();
}
}
else {
HXLINE(1944) if (::hx::IsNotNull( this->_hx___filters )) {
HXLINE(1946) this->_hx___filters = null();
HXLINE(1948) if (!(this->_hx___renderDirty)) {
HXLINE(1948) this->_hx___renderDirty = true;
HXDLIN(1948) this->_hx___setParentRenderDirty();
}
}
}
HXLINE(1951) return value;
}
HX_DEFINE_DYNAMIC_FUNC1(DisplayObject_obj,set_filters,return )
Float DisplayObject_obj::get_height(){
HX_STACKFRAME(&_hx_pos_26400284d5456c16_1955_get_height)
HXLINE(1956) ::openfl::geom::Rectangle rect = ::openfl::geom::Rectangle_obj::_hx___pool->get().StaticCast< ::openfl::geom::Rectangle >();
HXLINE(1957) this->_hx___getLocalBounds(rect);
HXLINE(1958) Float height = rect->height;
HXLINE(1959) ::openfl::geom::Rectangle_obj::_hx___pool->release(rect);
HXLINE(1960) return height;
}
HX_DEFINE_DYNAMIC_FUNC0(DisplayObject_obj,get_height,return )
Float DisplayObject_obj::set_height(Float value){
HX_STACKFRAME(&_hx_pos_26400284d5456c16_1964_set_height)
HXLINE(1965) ::openfl::geom::Rectangle rect = ::openfl::geom::Rectangle_obj::_hx___pool->get().StaticCast< ::openfl::geom::Rectangle >();
HXLINE(1966) ::openfl::geom::Matrix matrix = ::openfl::geom::Matrix_obj::_hx___pool->get().StaticCast< ::openfl::geom::Matrix >();
HXLINE(1967) matrix->identity();
HXLINE(1969) this->_hx___getBounds(rect,matrix);
HXLINE(1971) if ((value != rect->height)) {
HXLINE(1973) this->set_scaleY((value / rect->height));
}
else {
HXLINE(1977) this->set_scaleY(( (Float)(1) ));
}
HXLINE(1980) ::openfl::geom::Rectangle_obj::_hx___pool->release(rect);
HXLINE(1981) ::openfl::geom::Matrix_obj::_hx___pool->release(matrix);
HXLINE(1983) return value;
}
HX_DEFINE_DYNAMIC_FUNC1(DisplayObject_obj,set_height,return )
::openfl::display::LoaderInfo DisplayObject_obj::get_loaderInfo(){
HX_STACKFRAME(&_hx_pos_26400284d5456c16_1987_get_loaderInfo)
HXLINE(1988) if (::hx::IsNotNull( this->stage )) {
HXLINE(1990) return ::openfl::utils::_internal::Lib_obj::current->_hx___loaderInfo;
}
HXLINE(1993) return null();
}
HX_DEFINE_DYNAMIC_FUNC0(DisplayObject_obj,get_loaderInfo,return )
::openfl::display::DisplayObject DisplayObject_obj::get_mask(){
HX_STACKFRAME(&_hx_pos_26400284d5456c16_1998_get_mask)
HXDLIN(1998) return this->_hx___mask;
}
HX_DEFINE_DYNAMIC_FUNC0(DisplayObject_obj,get_mask,return )
::openfl::display::DisplayObject DisplayObject_obj::set_mask( ::openfl::display::DisplayObject value){
HX_STACKFRAME(&_hx_pos_26400284d5456c16_2002_set_mask)
HXLINE(2003) if (::hx::IsInstanceEq( value,this->_hx___mask )) {
HXLINE(2005) return value;
}
HXLINE(2008) if (::hx::IsInstanceNotEq( value,this->_hx___mask )) {
HXLINE(2010) this->_hx___setTransformDirty();
HXLINE(2011) if (!(this->_hx___renderDirty)) {
HXLINE(2011) this->_hx___renderDirty = true;
HXDLIN(2011) this->_hx___setParentRenderDirty();
}
}
HXLINE(2014) if (::hx::IsNotNull( this->_hx___mask )) {
HXLINE(2016) this->_hx___mask->_hx___isMask = false;
HXLINE(2017) this->_hx___mask->_hx___maskTarget = null();
HXLINE(2018) this->_hx___mask->_hx___setTransformDirty();
HXLINE(2019) {
HXLINE(2019) ::openfl::display::DisplayObject _this = this->_hx___mask;
HXDLIN(2019) if (!(_this->_hx___renderDirty)) {
HXLINE(2019) _this->_hx___renderDirty = true;
HXDLIN(2019) _this->_hx___setParentRenderDirty();
}
}
}
HXLINE(2022) if (::hx::IsNotNull( value )) {
HXLINE(2024) value->_hx___isMask = true;
HXLINE(2025) value->_hx___maskTarget = ::hx::ObjectPtr<OBJ_>(this);
HXLINE(2026) value->_hx___setWorldTransformInvalid();
}
HXLINE(2029) bool _hx_tmp;
HXDLIN(2029) if (::hx::IsNotNull( this->_hx___cacheBitmap )) {
HXLINE(2029) _hx_tmp = ::hx::IsInstanceNotEq( this->_hx___cacheBitmap->get_mask(),value );
}
else {
HXLINE(2029) _hx_tmp = false;
}
HXDLIN(2029) if (_hx_tmp) {
HXLINE(2031) this->_hx___cacheBitmap->set_mask(value);
}
HXLINE(2034) return (this->_hx___mask = value);
}
HX_DEFINE_DYNAMIC_FUNC1(DisplayObject_obj,set_mask,return )
Float DisplayObject_obj::get_mouseX(){
HX_STACKFRAME(&_hx_pos_26400284d5456c16_2038_get_mouseX)
HXLINE(2039) Float mouseX;
HXDLIN(2039) if (::hx::IsNotNull( this->stage )) {
HXLINE(2039) mouseX = this->stage->_hx___mouseX;
}
else {
HXLINE(2039) mouseX = ::openfl::utils::_internal::Lib_obj::current->stage->_hx___mouseX;
}
HXLINE(2040) Float mouseY;
HXDLIN(2040) if (::hx::IsNotNull( this->stage )) {
HXLINE(2040) mouseY = this->stage->_hx___mouseY;
}
else {
HXLINE(2040) mouseY = ::openfl::utils::_internal::Lib_obj::current->stage->_hx___mouseY;
}
HXLINE(2042) ::openfl::geom::Matrix _this = this->_hx___getRenderTransform();
HXDLIN(2042) Float norm = ((_this->a * _this->d) - (_this->b * _this->c));
HXDLIN(2042) if ((norm == 0)) {
HXLINE(2042) return -(_this->tx);
}
else {
HXLINE(2042) return ((((Float)1.0) / norm) * ((_this->c * (_this->ty - mouseY)) + (_this->d * (mouseX - _this->tx))));
}
HXDLIN(2042) return ((Float)0.);
}
HX_DEFINE_DYNAMIC_FUNC0(DisplayObject_obj,get_mouseX,return )
Float DisplayObject_obj::get_mouseY(){
HX_STACKFRAME(&_hx_pos_26400284d5456c16_2046_get_mouseY)
HXLINE(2047) Float mouseX;
HXDLIN(2047) if (::hx::IsNotNull( this->stage )) {
HXLINE(2047) mouseX = this->stage->_hx___mouseX;
}
else {
HXLINE(2047) mouseX = ::openfl::utils::_internal::Lib_obj::current->stage->_hx___mouseX;
}
HXLINE(2048) Float mouseY;
HXDLIN(2048) if (::hx::IsNotNull( this->stage )) {
HXLINE(2048) mouseY = this->stage->_hx___mouseY;
}
else {
HXLINE(2048) mouseY = ::openfl::utils::_internal::Lib_obj::current->stage->_hx___mouseY;
}
HXLINE(2050) ::openfl::geom::Matrix _this = this->_hx___getRenderTransform();
HXDLIN(2050) Float norm = ((_this->a * _this->d) - (_this->b * _this->c));
HXDLIN(2050) if ((norm == 0)) {
HXLINE(2050) return -(_this->ty);
}
else {
HXLINE(2050) return ((((Float)1.0) / norm) * ((_this->a * (mouseY - _this->ty)) + (_this->b * (_this->tx - mouseX))));
}
HXDLIN(2050) return ((Float)0.);
}
HX_DEFINE_DYNAMIC_FUNC0(DisplayObject_obj,get_mouseY,return )
::String DisplayObject_obj::get_name(){
HX_STACKFRAME(&_hx_pos_26400284d5456c16_2055_get_name)
HXDLIN(2055) return this->_hx___name;
}
HX_DEFINE_DYNAMIC_FUNC0(DisplayObject_obj,get_name,return )
::String DisplayObject_obj::set_name(::String value){
HX_STACKFRAME(&_hx_pos_26400284d5456c16_2060_set_name)
HXDLIN(2060) return (this->_hx___name = value);
}
HX_DEFINE_DYNAMIC_FUNC1(DisplayObject_obj,set_name,return )
::openfl::display::DisplayObject DisplayObject_obj::get_root(){
HX_STACKFRAME(&_hx_pos_26400284d5456c16_2064_get_root)
HXLINE(2065) if (::hx::IsNotNull( this->stage )) {
HXLINE(2067) return ::openfl::utils::_internal::Lib_obj::current;
}
HXLINE(2070) return null();
}
HX_DEFINE_DYNAMIC_FUNC0(DisplayObject_obj,get_root,return )
Float DisplayObject_obj::get_rotation(){
HX_STACKFRAME(&_hx_pos_26400284d5456c16_2075_get_rotation)
HXDLIN(2075) return this->_hx___rotation;
}
HX_DEFINE_DYNAMIC_FUNC0(DisplayObject_obj,get_rotation,return )
Float DisplayObject_obj::set_rotation(Float value){
HX_STACKFRAME(&_hx_pos_26400284d5456c16_2079_set_rotation)
HXLINE(2080) if ((value != this->_hx___rotation)) {
HXLINE(2082) this->_hx___rotation = value;
HXLINE(2083) Float radians = (this->_hx___rotation * (::Math_obj::PI / ( (Float)(180) )));
HXLINE(2084) this->_hx___rotationSine = ::Math_obj::sin(radians);
HXLINE(2085) this->_hx___rotationCosine = ::Math_obj::cos(radians);
HXLINE(2087) this->_hx___transform->a = (this->_hx___rotationCosine * this->_hx___scaleX);
HXLINE(2088) this->_hx___transform->b = (this->_hx___rotationSine * this->_hx___scaleX);
HXLINE(2089) this->_hx___transform->c = (-(this->_hx___rotationSine) * this->_hx___scaleY);
HXLINE(2090) this->_hx___transform->d = (this->_hx___rotationCosine * this->_hx___scaleY);
HXLINE(2092) this->_hx___setTransformDirty();
}
HXLINE(2095) return value;
}
HX_DEFINE_DYNAMIC_FUNC1(DisplayObject_obj,set_rotation,return )
::openfl::geom::Rectangle DisplayObject_obj::get_scale9Grid(){
HX_STACKFRAME(&_hx_pos_26400284d5456c16_2099_get_scale9Grid)
HXLINE(2100) if (::hx::IsNull( this->_hx___scale9Grid )) {
HXLINE(2102) return null();
}
HXLINE(2105) return this->_hx___scale9Grid->clone();
}
HX_DEFINE_DYNAMIC_FUNC0(DisplayObject_obj,get_scale9Grid,return )
::openfl::geom::Rectangle DisplayObject_obj::set_scale9Grid( ::openfl::geom::Rectangle value){
HX_GC_STACKFRAME(&_hx_pos_26400284d5456c16_2109_set_scale9Grid)
HXLINE(2110) bool _hx_tmp;
HXDLIN(2110) if (::hx::IsNull( value )) {
HXLINE(2110) _hx_tmp = ::hx::IsNull( this->_hx___scale9Grid );
}
else {
HXLINE(2110) _hx_tmp = false;
}
HXDLIN(2110) if (_hx_tmp) {
HXLINE(2110) return value;
}
HXLINE(2111) bool _hx_tmp1;
HXDLIN(2111) bool _hx_tmp2;
HXDLIN(2111) if (::hx::IsNotNull( value )) {
HXLINE(2111) _hx_tmp2 = ::hx::IsNotNull( this->_hx___scale9Grid );
}
else {
HXLINE(2111) _hx_tmp2 = false;
}
HXDLIN(2111) if (_hx_tmp2) {
HXLINE(2111) _hx_tmp1 = this->_hx___scale9Grid->equals(value);
}
else {
HXLINE(2111) _hx_tmp1 = false;
}
HXDLIN(2111) if (_hx_tmp1) {
HXLINE(2111) return value;
}
HXLINE(2113) if (::hx::IsNotNull( value )) {
HXLINE(2115) if (::hx::IsNull( this->_hx___scale9Grid )) {
HXLINE(2115) this->_hx___scale9Grid = ::openfl::geom::Rectangle_obj::__alloc( HX_CTX ,null(),null(),null(),null());
}
HXLINE(2116) this->_hx___scale9Grid->copyFrom(value);
}
else {
HXLINE(2120) this->_hx___scale9Grid = null();
}
HXLINE(2123) if (!(this->_hx___renderDirty)) {
HXLINE(2123) this->_hx___renderDirty = true;
HXDLIN(2123) this->_hx___setParentRenderDirty();
}
HXLINE(2125) return value;
}
HX_DEFINE_DYNAMIC_FUNC1(DisplayObject_obj,set_scale9Grid,return )
Float DisplayObject_obj::get_scaleX(){
HX_STACKFRAME(&_hx_pos_26400284d5456c16_2130_get_scaleX)
HXDLIN(2130) return this->_hx___scaleX;
}
HX_DEFINE_DYNAMIC_FUNC0(DisplayObject_obj,get_scaleX,return )
Float DisplayObject_obj::set_scaleX(Float value){
HX_STACKFRAME(&_hx_pos_26400284d5456c16_2134_set_scaleX)
HXLINE(2135) if ((value != this->_hx___scaleX)) {
HXLINE(2137) this->_hx___scaleX = value;
HXLINE(2139) if ((this->_hx___transform->b == 0)) {
HXLINE(2141) if ((value != this->_hx___transform->a)) {
HXLINE(2141) this->_hx___setTransformDirty();
}
HXLINE(2142) this->_hx___transform->a = value;
}
else {
HXLINE(2146) Float a = (this->_hx___rotationCosine * value);
HXLINE(2147) Float b = (this->_hx___rotationSine * value);
HXLINE(2149) bool _hx_tmp;
HXDLIN(2149) if ((this->_hx___transform->a == a)) {
HXLINE(2149) _hx_tmp = (this->_hx___transform->b != b);
}
else {
HXLINE(2149) _hx_tmp = true;
}
HXDLIN(2149) if (_hx_tmp) {
HXLINE(2151) this->_hx___setTransformDirty();
}
HXLINE(2154) this->_hx___transform->a = a;
HXLINE(2155) this->_hx___transform->b = b;
}
}
HXLINE(2159) return value;
}
HX_DEFINE_DYNAMIC_FUNC1(DisplayObject_obj,set_scaleX,return )
Float DisplayObject_obj::get_scaleY(){
HX_STACKFRAME(&_hx_pos_26400284d5456c16_2164_get_scaleY)
HXDLIN(2164) return this->_hx___scaleY;
}
HX_DEFINE_DYNAMIC_FUNC0(DisplayObject_obj,get_scaleY,return )
Float DisplayObject_obj::set_scaleY(Float value){
HX_STACKFRAME(&_hx_pos_26400284d5456c16_2168_set_scaleY)
HXLINE(2169) if ((value != this->_hx___scaleY)) {
HXLINE(2171) this->_hx___scaleY = value;
HXLINE(2173) if ((this->_hx___transform->c == 0)) {
HXLINE(2175) if ((value != this->_hx___transform->d)) {
HXLINE(2175) this->_hx___setTransformDirty();
}
HXLINE(2176) this->_hx___transform->d = value;
}
else {
HXLINE(2180) Float c = (-(this->_hx___rotationSine) * value);
HXLINE(2181) Float d = (this->_hx___rotationCosine * value);
HXLINE(2183) bool _hx_tmp;
HXDLIN(2183) if ((this->_hx___transform->d == d)) {
HXLINE(2183) _hx_tmp = (this->_hx___transform->c != c);
}
else {
HXLINE(2183) _hx_tmp = true;
}
HXDLIN(2183) if (_hx_tmp) {
HXLINE(2185) this->_hx___setTransformDirty();
}
HXLINE(2188) this->_hx___transform->c = c;
HXLINE(2189) this->_hx___transform->d = d;
}
}
HXLINE(2193) return value;
}
HX_DEFINE_DYNAMIC_FUNC1(DisplayObject_obj,set_scaleY,return )
::openfl::geom::Rectangle DisplayObject_obj::get_scrollRect(){
HX_STACKFRAME(&_hx_pos_26400284d5456c16_2197_get_scrollRect)
HXLINE(2198) if (::hx::IsNull( this->_hx___scrollRect )) {
HXLINE(2200) return null();
}
HXLINE(2203) return this->_hx___scrollRect->clone();
}
HX_DEFINE_DYNAMIC_FUNC0(DisplayObject_obj,get_scrollRect,return )
::openfl::geom::Rectangle DisplayObject_obj::set_scrollRect( ::openfl::geom::Rectangle value){
HX_GC_STACKFRAME(&_hx_pos_26400284d5456c16_2207_set_scrollRect)
HXLINE(2208) bool _hx_tmp;
HXDLIN(2208) if (::hx::IsNull( value )) {
HXLINE(2208) _hx_tmp = ::hx::IsNull( this->_hx___scrollRect );
}
else {
HXLINE(2208) _hx_tmp = false;
}
HXDLIN(2208) if (_hx_tmp) {
HXLINE(2208) return value;
}
HXLINE(2209) bool _hx_tmp1;
HXDLIN(2209) bool _hx_tmp2;
HXDLIN(2209) if (::hx::IsNotNull( value )) {
HXLINE(2209) _hx_tmp2 = ::hx::IsNotNull( this->_hx___scrollRect );
}
else {
HXLINE(2209) _hx_tmp2 = false;
}
HXDLIN(2209) if (_hx_tmp2) {
HXLINE(2209) _hx_tmp1 = this->_hx___scrollRect->equals(value);
}
else {
HXLINE(2209) _hx_tmp1 = false;
}
HXDLIN(2209) if (_hx_tmp1) {
HXLINE(2209) return value;
}
HXLINE(2211) if (::hx::IsNotNull( value )) {
HXLINE(2213) if (::hx::IsNull( this->_hx___scrollRect )) {
HXLINE(2213) this->_hx___scrollRect = ::openfl::geom::Rectangle_obj::__alloc( HX_CTX ,null(),null(),null(),null());
}
HXLINE(2214) this->_hx___scrollRect->copyFrom(value);
}
else {
HXLINE(2218) this->_hx___scrollRect = null();
}
HXLINE(2221) this->_hx___setTransformDirty();
HXLINE(2228) return value;
}
HX_DEFINE_DYNAMIC_FUNC1(DisplayObject_obj,set_scrollRect,return )
::openfl::display::Shader DisplayObject_obj::get_shader(){
HX_STACKFRAME(&_hx_pos_26400284d5456c16_2233_get_shader)
HXDLIN(2233) return this->_hx___shader;
}
HX_DEFINE_DYNAMIC_FUNC0(DisplayObject_obj,get_shader,return )
::openfl::display::Shader DisplayObject_obj::set_shader( ::openfl::display::Shader value){
HX_STACKFRAME(&_hx_pos_26400284d5456c16_2237_set_shader)
HXLINE(2238) this->_hx___shader = value;
HXLINE(2239) if (!(this->_hx___renderDirty)) {
HXLINE(2239) this->_hx___renderDirty = true;
HXDLIN(2239) this->_hx___setParentRenderDirty();
}
HXLINE(2240) return value;
}
HX_DEFINE_DYNAMIC_FUNC1(DisplayObject_obj,set_shader,return )
::openfl::geom::Transform DisplayObject_obj::get_transform(){
HX_GC_STACKFRAME(&_hx_pos_26400284d5456c16_2244_get_transform)
HXLINE(2245) if (::hx::IsNull( this->_hx___objectTransform )) {
HXLINE(2247) this->_hx___objectTransform = ::openfl::geom::Transform_obj::__alloc( HX_CTX ,::hx::ObjectPtr<OBJ_>(this));
}
HXLINE(2250) return this->_hx___objectTransform;
}
HX_DEFINE_DYNAMIC_FUNC0(DisplayObject_obj,get_transform,return )
::openfl::geom::Transform DisplayObject_obj::set_transform( ::openfl::geom::Transform value){
HX_GC_STACKFRAME(&_hx_pos_26400284d5456c16_2254_set_transform)
HXLINE(2255) if (::hx::IsNull( value )) {
HXLINE(2257) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown( ::openfl::errors::TypeError_obj::__alloc( HX_CTX ,HX_("Parameter transform must be non-null.",56,12,fe,6e))));
}
HXLINE(2260) if (::hx::IsNull( this->_hx___objectTransform )) {
HXLINE(2262) this->_hx___objectTransform = ::openfl::geom::Transform_obj::__alloc( HX_CTX ,::hx::ObjectPtr<OBJ_>(this));
}
HXLINE(2265) this->_hx___setTransformDirty();
HXLINE(2266) ::openfl::geom::Transform _hx_tmp = this->_hx___objectTransform;
HXDLIN(2266) _hx_tmp->set_matrix(value->get_matrix());
HXLINE(2268) bool _hx_tmp1;
HXDLIN(2268) if (this->_hx___objectTransform->_hx___colorTransform->_hx___equals(value->_hx___colorTransform,true)) {
HXLINE(2269) if (!(this->get_cacheAsBitmap())) {
HXLINE(2268) _hx_tmp1 = (this->_hx___objectTransform->_hx___colorTransform->alphaMultiplier != value->_hx___colorTransform->alphaMultiplier);
}
else {
HXLINE(2268) _hx_tmp1 = false;
}
}
else {
HXLINE(2268) _hx_tmp1 = true;
}
HXDLIN(2268) if (_hx_tmp1) {
HXLINE(2271) ::openfl::geom::ColorTransform _hx_tmp = this->_hx___objectTransform->_hx___colorTransform;
HXDLIN(2271) _hx_tmp->_hx___copyFrom(value->get_colorTransform());
HXLINE(2272) if (!(this->_hx___renderDirty)) {
HXLINE(2272) this->_hx___renderDirty = true;
HXDLIN(2272) this->_hx___setParentRenderDirty();
}
}
HXLINE(2275) return this->_hx___objectTransform;
}
HX_DEFINE_DYNAMIC_FUNC1(DisplayObject_obj,set_transform,return )
bool DisplayObject_obj::get_visible(){
HX_STACKFRAME(&_hx_pos_26400284d5456c16_2280_get_visible)
HXDLIN(2280) return this->_hx___visible;
}
HX_DEFINE_DYNAMIC_FUNC0(DisplayObject_obj,get_visible,return )
bool DisplayObject_obj::set_visible(bool value){
HX_STACKFRAME(&_hx_pos_26400284d5456c16_2284_set_visible)
HXLINE(2285) if ((value != this->_hx___visible)) {
HXLINE(2285) if (!(this->_hx___renderDirty)) {
HXLINE(2285) this->_hx___renderDirty = true;
HXDLIN(2285) this->_hx___setParentRenderDirty();
}
}
HXLINE(2286) return (this->_hx___visible = value);
}
HX_DEFINE_DYNAMIC_FUNC1(DisplayObject_obj,set_visible,return )
Float DisplayObject_obj::get_width(){
HX_STACKFRAME(&_hx_pos_26400284d5456c16_2290_get_width)
HXLINE(2291) ::openfl::geom::Rectangle rect = ::openfl::geom::Rectangle_obj::_hx___pool->get().StaticCast< ::openfl::geom::Rectangle >();
HXLINE(2292) this->_hx___getLocalBounds(rect);
HXLINE(2293) Float width = rect->width;
HXLINE(2294) ::openfl::geom::Rectangle_obj::_hx___pool->release(rect);
HXLINE(2295) return width;
}
HX_DEFINE_DYNAMIC_FUNC0(DisplayObject_obj,get_width,return )
Float DisplayObject_obj::set_width(Float value){
HX_STACKFRAME(&_hx_pos_26400284d5456c16_2299_set_width)
HXLINE(2300) ::openfl::geom::Rectangle rect = ::openfl::geom::Rectangle_obj::_hx___pool->get().StaticCast< ::openfl::geom::Rectangle >();
HXLINE(2301) ::openfl::geom::Matrix matrix = ::openfl::geom::Matrix_obj::_hx___pool->get().StaticCast< ::openfl::geom::Matrix >();
HXLINE(2302) matrix->identity();
HXLINE(2304) this->_hx___getBounds(rect,matrix);
HXLINE(2306) if ((value != rect->width)) {
HXLINE(2308) this->set_scaleX((value / rect->width));
}
else {
HXLINE(2312) this->set_scaleX(( (Float)(1) ));
}
HXLINE(2315) ::openfl::geom::Rectangle_obj::_hx___pool->release(rect);
HXLINE(2316) ::openfl::geom::Matrix_obj::_hx___pool->release(matrix);
HXLINE(2318) return value;
}
HX_DEFINE_DYNAMIC_FUNC1(DisplayObject_obj,set_width,return )
Float DisplayObject_obj::get_x(){
HX_STACKFRAME(&_hx_pos_26400284d5456c16_2323_get_x)
HXDLIN(2323) return this->_hx___transform->tx;
}
HX_DEFINE_DYNAMIC_FUNC0(DisplayObject_obj,get_x,return )
Float DisplayObject_obj::set_x(Float value){
HX_STACKFRAME(&_hx_pos_26400284d5456c16_2327_set_x)
HXLINE(2328) if ((value != this->_hx___transform->tx)) {
HXLINE(2328) this->_hx___setTransformDirty();
}
HXLINE(2329) return (this->_hx___transform->tx = value);
}
HX_DEFINE_DYNAMIC_FUNC1(DisplayObject_obj,set_x,return )
Float DisplayObject_obj::get_y(){
HX_STACKFRAME(&_hx_pos_26400284d5456c16_2334_get_y)
HXDLIN(2334) return this->_hx___transform->ty;
}
HX_DEFINE_DYNAMIC_FUNC0(DisplayObject_obj,get_y,return )
Float DisplayObject_obj::set_y(Float value){
HX_STACKFRAME(&_hx_pos_26400284d5456c16_2338_set_y)
HXLINE(2339) if ((value != this->_hx___transform->ty)) {
HXLINE(2339) this->_hx___setTransformDirty();
}
HXLINE(2340) return (this->_hx___transform->ty = value);
}
HX_DEFINE_DYNAMIC_FUNC1(DisplayObject_obj,set_y,return )
::haxe::ds::StringMap DisplayObject_obj::_hx___broadcastEvents;
::openfl::display::Stage DisplayObject_obj::_hx___initStage;
int DisplayObject_obj::_hx___instanceCount;
bool DisplayObject_obj::_hx___supportDOM;
::lime::utils::ObjectPool DisplayObject_obj::_hx___tempStack;
void DisplayObject_obj::_hx___calculateAbsoluteTransform( ::openfl::geom::Matrix local, ::openfl::geom::Matrix parentTransform, ::openfl::geom::Matrix target){
HX_STACKFRAME(&_hx_pos_26400284d5456c16_1359___calculateAbsoluteTransform)
HXLINE(1360) target->a = ((local->a * parentTransform->a) + (local->b * parentTransform->c));
HXLINE(1361) target->b = ((local->a * parentTransform->b) + (local->b * parentTransform->d));
HXLINE(1362) target->c = ((local->c * parentTransform->a) + (local->d * parentTransform->c));
HXLINE(1363) target->d = ((local->c * parentTransform->b) + (local->d * parentTransform->d));
HXLINE(1364) target->tx = (((local->tx * parentTransform->a) + (local->ty * parentTransform->c)) + parentTransform->tx);
HXLINE(1365) target->ty = (((local->tx * parentTransform->b) + (local->ty * parentTransform->d)) + parentTransform->ty);
}
STATIC_HX_DEFINE_DYNAMIC_FUNC3(DisplayObject_obj,_hx___calculateAbsoluteTransform,(void))
::hx::ObjectPtr< DisplayObject_obj > DisplayObject_obj::__new() {
::hx::ObjectPtr< DisplayObject_obj > __this = new DisplayObject_obj();
__this->__construct();
return __this;
}
::hx::ObjectPtr< DisplayObject_obj > DisplayObject_obj::__alloc(::hx::Ctx *_hx_ctx) {
DisplayObject_obj *__this = (DisplayObject_obj*)(::hx::Ctx::alloc(_hx_ctx, sizeof(DisplayObject_obj), true, "openfl.display.DisplayObject"));
*(void **)__this = DisplayObject_obj::_hx_vtable;
__this->__construct();
return __this;
}
DisplayObject_obj::DisplayObject_obj()
{
}
void DisplayObject_obj::__Mark(HX_MARK_PARAMS)
{
HX_MARK_BEGIN_CLASS(DisplayObject);
HX_MARK_MEMBER_NAME(opaqueBackground,"opaqueBackground");
HX_MARK_MEMBER_NAME(parent,"parent");
HX_MARK_MEMBER_NAME(stage,"stage");
HX_MARK_MEMBER_NAME(_hx___alpha,"__alpha");
HX_MARK_MEMBER_NAME(_hx___blendMode,"__blendMode");
HX_MARK_MEMBER_NAME(_hx___cacheAsBitmap,"__cacheAsBitmap");
HX_MARK_MEMBER_NAME(_hx___cacheAsBitmapMatrix,"__cacheAsBitmapMatrix");
HX_MARK_MEMBER_NAME(_hx___cacheBitmap,"__cacheBitmap");
HX_MARK_MEMBER_NAME(_hx___cacheBitmapBackground,"__cacheBitmapBackground");
HX_MARK_MEMBER_NAME(_hx___cacheBitmapColorTransform,"__cacheBitmapColorTransform");
HX_MARK_MEMBER_NAME(_hx___cacheBitmapData,"__cacheBitmapData");
HX_MARK_MEMBER_NAME(_hx___cacheBitmapData2,"__cacheBitmapData2");
HX_MARK_MEMBER_NAME(_hx___cacheBitmapData3,"__cacheBitmapData3");
HX_MARK_MEMBER_NAME(_hx___cacheBitmapMatrix,"__cacheBitmapMatrix");
HX_MARK_MEMBER_NAME(_hx___cacheBitmapRenderer,"__cacheBitmapRenderer");
HX_MARK_MEMBER_NAME(_hx___cairo,"__cairo");
HX_MARK_MEMBER_NAME(_hx___children,"__children");
HX_MARK_MEMBER_NAME(_hx___customRenderClear,"__customRenderClear");
HX_MARK_MEMBER_NAME(_hx___customRenderEvent,"__customRenderEvent");
HX_MARK_MEMBER_NAME(_hx___drawableType,"__drawableType");
HX_MARK_MEMBER_NAME(_hx___filters,"__filters");
HX_MARK_MEMBER_NAME(_hx___graphics,"__graphics");
HX_MARK_MEMBER_NAME(_hx___interactive,"__interactive");
HX_MARK_MEMBER_NAME(_hx___isCacheBitmapRender,"__isCacheBitmapRender");
HX_MARK_MEMBER_NAME(_hx___isMask,"__isMask");
HX_MARK_MEMBER_NAME(_hx___loaderInfo,"__loaderInfo");
HX_MARK_MEMBER_NAME(_hx___mask,"__mask");
HX_MARK_MEMBER_NAME(_hx___maskTarget,"__maskTarget");
HX_MARK_MEMBER_NAME(_hx___name,"__name");
HX_MARK_MEMBER_NAME(_hx___objectTransform,"__objectTransform");
HX_MARK_MEMBER_NAME(_hx___renderable,"__renderable");
HX_MARK_MEMBER_NAME(_hx___renderDirty,"__renderDirty");
HX_MARK_MEMBER_NAME(_hx___renderParent,"__renderParent");
HX_MARK_MEMBER_NAME(_hx___renderTransform,"__renderTransform");
HX_MARK_MEMBER_NAME(_hx___renderTransformCache,"__renderTransformCache");
HX_MARK_MEMBER_NAME(_hx___renderTransformChanged,"__renderTransformChanged");
HX_MARK_MEMBER_NAME(_hx___rotation,"__rotation");
HX_MARK_MEMBER_NAME(_hx___rotationCosine,"__rotationCosine");
HX_MARK_MEMBER_NAME(_hx___rotationSine,"__rotationSine");
HX_MARK_MEMBER_NAME(_hx___scale9Grid,"__scale9Grid");
HX_MARK_MEMBER_NAME(_hx___scaleX,"__scaleX");
HX_MARK_MEMBER_NAME(_hx___scaleY,"__scaleY");
HX_MARK_MEMBER_NAME(_hx___scrollRect,"__scrollRect");
HX_MARK_MEMBER_NAME(_hx___shader,"__shader");
HX_MARK_MEMBER_NAME(_hx___tempPoint,"__tempPoint");
HX_MARK_MEMBER_NAME(_hx___transform,"__transform");
HX_MARK_MEMBER_NAME(_hx___transformDirty,"__transformDirty");
HX_MARK_MEMBER_NAME(_hx___visible,"__visible");
HX_MARK_MEMBER_NAME(_hx___worldAlpha,"__worldAlpha");
HX_MARK_MEMBER_NAME(_hx___worldAlphaChanged,"__worldAlphaChanged");
HX_MARK_MEMBER_NAME(_hx___worldBlendMode,"__worldBlendMode");
HX_MARK_MEMBER_NAME(_hx___worldClip,"__worldClip");
HX_MARK_MEMBER_NAME(_hx___worldClipChanged,"__worldClipChanged");
HX_MARK_MEMBER_NAME(_hx___worldColorTransform,"__worldColorTransform");
HX_MARK_MEMBER_NAME(_hx___worldShader,"__worldShader");
HX_MARK_MEMBER_NAME(_hx___worldScale9Grid,"__worldScale9Grid");
HX_MARK_MEMBER_NAME(_hx___worldTransform,"__worldTransform");
HX_MARK_MEMBER_NAME(_hx___worldVisible,"__worldVisible");
HX_MARK_MEMBER_NAME(_hx___worldVisibleChanged,"__worldVisibleChanged");
HX_MARK_MEMBER_NAME(_hx___worldTransformInvalid,"__worldTransformInvalid");
HX_MARK_MEMBER_NAME(_hx___worldZ,"__worldZ");
::openfl::events::EventDispatcher_obj::__Mark(HX_MARK_ARG);
HX_MARK_END_CLASS();
}
void DisplayObject_obj::__Visit(HX_VISIT_PARAMS)
{
HX_VISIT_MEMBER_NAME(opaqueBackground,"opaqueBackground");
HX_VISIT_MEMBER_NAME(parent,"parent");
HX_VISIT_MEMBER_NAME(stage,"stage");
HX_VISIT_MEMBER_NAME(_hx___alpha,"__alpha");
HX_VISIT_MEMBER_NAME(_hx___blendMode,"__blendMode");
HX_VISIT_MEMBER_NAME(_hx___cacheAsBitmap,"__cacheAsBitmap");
HX_VISIT_MEMBER_NAME(_hx___cacheAsBitmapMatrix,"__cacheAsBitmapMatrix");
HX_VISIT_MEMBER_NAME(_hx___cacheBitmap,"__cacheBitmap");
HX_VISIT_MEMBER_NAME(_hx___cacheBitmapBackground,"__cacheBitmapBackground");
HX_VISIT_MEMBER_NAME(_hx___cacheBitmapColorTransform,"__cacheBitmapColorTransform");
HX_VISIT_MEMBER_NAME(_hx___cacheBitmapData,"__cacheBitmapData");
HX_VISIT_MEMBER_NAME(_hx___cacheBitmapData2,"__cacheBitmapData2");
HX_VISIT_MEMBER_NAME(_hx___cacheBitmapData3,"__cacheBitmapData3");
HX_VISIT_MEMBER_NAME(_hx___cacheBitmapMatrix,"__cacheBitmapMatrix");
HX_VISIT_MEMBER_NAME(_hx___cacheBitmapRenderer,"__cacheBitmapRenderer");
HX_VISIT_MEMBER_NAME(_hx___cairo,"__cairo");
HX_VISIT_MEMBER_NAME(_hx___children,"__children");
HX_VISIT_MEMBER_NAME(_hx___customRenderClear,"__customRenderClear");
HX_VISIT_MEMBER_NAME(_hx___customRenderEvent,"__customRenderEvent");
HX_VISIT_MEMBER_NAME(_hx___drawableType,"__drawableType");
HX_VISIT_MEMBER_NAME(_hx___filters,"__filters");
HX_VISIT_MEMBER_NAME(_hx___graphics,"__graphics");
HX_VISIT_MEMBER_NAME(_hx___interactive,"__interactive");
HX_VISIT_MEMBER_NAME(_hx___isCacheBitmapRender,"__isCacheBitmapRender");
HX_VISIT_MEMBER_NAME(_hx___isMask,"__isMask");
HX_VISIT_MEMBER_NAME(_hx___loaderInfo,"__loaderInfo");
HX_VISIT_MEMBER_NAME(_hx___mask,"__mask");
HX_VISIT_MEMBER_NAME(_hx___maskTarget,"__maskTarget");
HX_VISIT_MEMBER_NAME(_hx___name,"__name");
HX_VISIT_MEMBER_NAME(_hx___objectTransform,"__objectTransform");
HX_VISIT_MEMBER_NAME(_hx___renderable,"__renderable");
HX_VISIT_MEMBER_NAME(_hx___renderDirty,"__renderDirty");
HX_VISIT_MEMBER_NAME(_hx___renderParent,"__renderParent");
HX_VISIT_MEMBER_NAME(_hx___renderTransform,"__renderTransform");
HX_VISIT_MEMBER_NAME(_hx___renderTransformCache,"__renderTransformCache");
HX_VISIT_MEMBER_NAME(_hx___renderTransformChanged,"__renderTransformChanged");
HX_VISIT_MEMBER_NAME(_hx___rotation,"__rotation");
HX_VISIT_MEMBER_NAME(_hx___rotationCosine,"__rotationCosine");
HX_VISIT_MEMBER_NAME(_hx___rotationSine,"__rotationSine");
HX_VISIT_MEMBER_NAME(_hx___scale9Grid,"__scale9Grid");
HX_VISIT_MEMBER_NAME(_hx___scaleX,"__scaleX");
HX_VISIT_MEMBER_NAME(_hx___scaleY,"__scaleY");
HX_VISIT_MEMBER_NAME(_hx___scrollRect,"__scrollRect");
HX_VISIT_MEMBER_NAME(_hx___shader,"__shader");
HX_VISIT_MEMBER_NAME(_hx___tempPoint,"__tempPoint");
HX_VISIT_MEMBER_NAME(_hx___transform,"__transform");
HX_VISIT_MEMBER_NAME(_hx___transformDirty,"__transformDirty");
HX_VISIT_MEMBER_NAME(_hx___visible,"__visible");
HX_VISIT_MEMBER_NAME(_hx___worldAlpha,"__worldAlpha");
HX_VISIT_MEMBER_NAME(_hx___worldAlphaChanged,"__worldAlphaChanged");
HX_VISIT_MEMBER_NAME(_hx___worldBlendMode,"__worldBlendMode");
HX_VISIT_MEMBER_NAME(_hx___worldClip,"__worldClip");
HX_VISIT_MEMBER_NAME(_hx___worldClipChanged,"__worldClipChanged");
HX_VISIT_MEMBER_NAME(_hx___worldColorTransform,"__worldColorTransform");
HX_VISIT_MEMBER_NAME(_hx___worldShader,"__worldShader");
HX_VISIT_MEMBER_NAME(_hx___worldScale9Grid,"__worldScale9Grid");
HX_VISIT_MEMBER_NAME(_hx___worldTransform,"__worldTransform");
HX_VISIT_MEMBER_NAME(_hx___worldVisible,"__worldVisible");
HX_VISIT_MEMBER_NAME(_hx___worldVisibleChanged,"__worldVisibleChanged");
HX_VISIT_MEMBER_NAME(_hx___worldTransformInvalid,"__worldTransformInvalid");
HX_VISIT_MEMBER_NAME(_hx___worldZ,"__worldZ");
::openfl::events::EventDispatcher_obj::__Visit(HX_VISIT_ARG);
}
::hx::Val DisplayObject_obj::__Field(const ::String &inName,::hx::PropertyAccess inCallProp)
{
switch(inName.length) {
case 1:
if (HX_FIELD_EQ(inName,"x") ) { if (inCallProp == ::hx::paccAlways) return ::hx::Val( get_x() ); }
if (HX_FIELD_EQ(inName,"y") ) { if (inCallProp == ::hx::paccAlways) return ::hx::Val( get_y() ); }
break;
case 4:
if (HX_FIELD_EQ(inName,"mask") ) { if (inCallProp == ::hx::paccAlways) return ::hx::Val( get_mask() ); }
if (HX_FIELD_EQ(inName,"name") ) { if (inCallProp == ::hx::paccAlways) return ::hx::Val( get_name() ); }
if (HX_FIELD_EQ(inName,"root") ) { if (inCallProp == ::hx::paccAlways) return ::hx::Val( get_root() ); }
break;
case 5:
if (HX_FIELD_EQ(inName,"alpha") ) { if (inCallProp == ::hx::paccAlways) return ::hx::Val( get_alpha() ); }
if (HX_FIELD_EQ(inName,"stage") ) { return ::hx::Val( stage ); }
if (HX_FIELD_EQ(inName,"width") ) { if (inCallProp == ::hx::paccAlways) return ::hx::Val( get_width() ); }
if (HX_FIELD_EQ(inName,"get_x") ) { return ::hx::Val( get_x_dyn() ); }
if (HX_FIELD_EQ(inName,"set_x") ) { return ::hx::Val( set_x_dyn() ); }
if (HX_FIELD_EQ(inName,"get_y") ) { return ::hx::Val( get_y_dyn() ); }
if (HX_FIELD_EQ(inName,"set_y") ) { return ::hx::Val( set_y_dyn() ); }
break;
case 6:
if (HX_FIELD_EQ(inName,"height") ) { if (inCallProp == ::hx::paccAlways) return ::hx::Val( get_height() ); }
if (HX_FIELD_EQ(inName,"mouseX") ) { if (inCallProp == ::hx::paccAlways) return ::hx::Val( get_mouseX() ); }
if (HX_FIELD_EQ(inName,"mouseY") ) { if (inCallProp == ::hx::paccAlways) return ::hx::Val( get_mouseY() ); }
if (HX_FIELD_EQ(inName,"parent") ) { return ::hx::Val( parent ); }
if (HX_FIELD_EQ(inName,"scaleX") ) { if (inCallProp == ::hx::paccAlways) return ::hx::Val( get_scaleX() ); }
if (HX_FIELD_EQ(inName,"scaleY") ) { if (inCallProp == ::hx::paccAlways) return ::hx::Val( get_scaleY() ); }
if (HX_FIELD_EQ(inName,"shader") ) { if (inCallProp == ::hx::paccAlways) return ::hx::Val( get_shader() ); }
if (HX_FIELD_EQ(inName,"__mask") ) { return ::hx::Val( _hx___mask ); }
if (HX_FIELD_EQ(inName,"__name") ) { return ::hx::Val( _hx___name ); }
break;
case 7:
if (HX_FIELD_EQ(inName,"filters") ) { if (inCallProp == ::hx::paccAlways) return ::hx::Val( get_filters() ); }
if (HX_FIELD_EQ(inName,"visible") ) { if (inCallProp == ::hx::paccAlways) return ::hx::Val( get_visible() ); }
if (HX_FIELD_EQ(inName,"__alpha") ) { return ::hx::Val( _hx___alpha ); }
if (HX_FIELD_EQ(inName,"__cairo") ) { return ::hx::Val( _hx___cairo ); }
if (HX_FIELD_EQ(inName,"getRect") ) { return ::hx::Val( getRect_dyn() ); }
break;
case 8:
if (HX_FIELD_EQ(inName,"rotation") ) { if (inCallProp == ::hx::paccAlways) return ::hx::Val( get_rotation() ); }
if (HX_FIELD_EQ(inName,"__isMask") ) { return ::hx::Val( _hx___isMask ); }
if (HX_FIELD_EQ(inName,"__scaleX") ) { return ::hx::Val( _hx___scaleX ); }
if (HX_FIELD_EQ(inName,"__scaleY") ) { return ::hx::Val( _hx___scaleY ); }
if (HX_FIELD_EQ(inName,"__shader") ) { return ::hx::Val( _hx___shader ); }
if (HX_FIELD_EQ(inName,"__worldZ") ) { return ::hx::Val( _hx___worldZ ); }
if (HX_FIELD_EQ(inName,"__update") ) { return ::hx::Val( _hx___update_dyn() ); }
if (HX_FIELD_EQ(inName,"get_mask") ) { return ::hx::Val( get_mask_dyn() ); }
if (HX_FIELD_EQ(inName,"set_mask") ) { return ::hx::Val( set_mask_dyn() ); }
if (HX_FIELD_EQ(inName,"get_name") ) { return ::hx::Val( get_name_dyn() ); }
if (HX_FIELD_EQ(inName,"set_name") ) { return ::hx::Val( set_name_dyn() ); }
if (HX_FIELD_EQ(inName,"get_root") ) { return ::hx::Val( get_root_dyn() ); }
break;
case 9:
if (HX_FIELD_EQ(inName,"blendMode") ) { if (inCallProp == ::hx::paccAlways) return ::hx::Val( get_blendMode() ); }
if (HX_FIELD_EQ(inName,"transform") ) { if (inCallProp == ::hx::paccAlways) return ::hx::Val( get_transform() ); }
if (HX_FIELD_EQ(inName,"__filters") ) { return ::hx::Val( _hx___filters ); }
if (HX_FIELD_EQ(inName,"__visible") ) { return ::hx::Val( _hx___visible ); }
if (HX_FIELD_EQ(inName,"getBounds") ) { return ::hx::Val( getBounds_dyn() ); }
if (HX_FIELD_EQ(inName,"__cleanup") ) { return ::hx::Val( _hx___cleanup_dyn() ); }
if (HX_FIELD_EQ(inName,"__hitTest") ) { return ::hx::Val( _hx___hitTest_dyn() ); }
if (HX_FIELD_EQ(inName,"get_alpha") ) { return ::hx::Val( get_alpha_dyn() ); }
if (HX_FIELD_EQ(inName,"set_alpha") ) { return ::hx::Val( set_alpha_dyn() ); }
if (HX_FIELD_EQ(inName,"get_width") ) { return ::hx::Val( get_width_dyn() ); }
if (HX_FIELD_EQ(inName,"set_width") ) { return ::hx::Val( set_width_dyn() ); }
break;
case 10:
if (HX_FIELD_EQ(inName,"loaderInfo") ) { if (inCallProp == ::hx::paccAlways) return ::hx::Val( get_loaderInfo() ); }
if (HX_FIELD_EQ(inName,"scale9Grid") ) { if (inCallProp == ::hx::paccAlways) return ::hx::Val( get_scale9Grid() ); }
if (HX_FIELD_EQ(inName,"scrollRect") ) { if (inCallProp == ::hx::paccAlways) return ::hx::Val( get_scrollRect() ); }
if (HX_FIELD_EQ(inName,"__children") ) { return ::hx::Val( _hx___children ); }
if (HX_FIELD_EQ(inName,"__graphics") ) { return ::hx::Val( _hx___graphics ); }
if (HX_FIELD_EQ(inName,"__rotation") ) { return ::hx::Val( _hx___rotation ); }
if (HX_FIELD_EQ(inName,"invalidate") ) { return ::hx::Val( invalidate_dyn() ); }
if (HX_FIELD_EQ(inName,"__dispatch") ) { return ::hx::Val( _hx___dispatch_dyn() ); }
if (HX_FIELD_EQ(inName,"get_height") ) { return ::hx::Val( get_height_dyn() ); }
if (HX_FIELD_EQ(inName,"set_height") ) { return ::hx::Val( set_height_dyn() ); }
if (HX_FIELD_EQ(inName,"get_mouseX") ) { return ::hx::Val( get_mouseX_dyn() ); }
if (HX_FIELD_EQ(inName,"get_mouseY") ) { return ::hx::Val( get_mouseY_dyn() ); }
if (HX_FIELD_EQ(inName,"get_scaleX") ) { return ::hx::Val( get_scaleX_dyn() ); }
if (HX_FIELD_EQ(inName,"set_scaleX") ) { return ::hx::Val( set_scaleX_dyn() ); }
if (HX_FIELD_EQ(inName,"get_scaleY") ) { return ::hx::Val( get_scaleY_dyn() ); }
if (HX_FIELD_EQ(inName,"set_scaleY") ) { return ::hx::Val( set_scaleY_dyn() ); }
if (HX_FIELD_EQ(inName,"get_shader") ) { return ::hx::Val( get_shader_dyn() ); }
if (HX_FIELD_EQ(inName,"set_shader") ) { return ::hx::Val( set_shader_dyn() ); }
break;
case 11:
if (HX_FIELD_EQ(inName,"__blendMode") ) { return ::hx::Val( _hx___blendMode ); }
if (HX_FIELD_EQ(inName,"__tempPoint") ) { return ::hx::Val( _hx___tempPoint ); }
if (HX_FIELD_EQ(inName,"__transform") ) { return ::hx::Val( _hx___transform ); }
if (HX_FIELD_EQ(inName,"__worldClip") ) { return ::hx::Val( _hx___worldClip ); }
if (HX_FIELD_EQ(inName,"__getBounds") ) { return ::hx::Val( _hx___getBounds_dyn() ); }
if (HX_FIELD_EQ(inName,"__getCursor") ) { return ::hx::Val( _hx___getCursor_dyn() ); }
if (HX_FIELD_EQ(inName,"get_filters") ) { return ::hx::Val( get_filters_dyn() ); }
if (HX_FIELD_EQ(inName,"set_filters") ) { return ::hx::Val( set_filters_dyn() ); }
if (HX_FIELD_EQ(inName,"get_visible") ) { return ::hx::Val( get_visible_dyn() ); }
if (HX_FIELD_EQ(inName,"set_visible") ) { return ::hx::Val( set_visible_dyn() ); }
break;
case 12:
if (HX_FIELD_EQ(inName,"__loaderInfo") ) { return ::hx::Val( _hx___loaderInfo ); }
if (HX_FIELD_EQ(inName,"__maskTarget") ) { return ::hx::Val( _hx___maskTarget ); }
if (HX_FIELD_EQ(inName,"__renderable") ) { return ::hx::Val( _hx___renderable ); }
if (HX_FIELD_EQ(inName,"__scale9Grid") ) { return ::hx::Val( _hx___scale9Grid ); }
if (HX_FIELD_EQ(inName,"__scrollRect") ) { return ::hx::Val( _hx___scrollRect ); }
if (HX_FIELD_EQ(inName,"__worldAlpha") ) { return ::hx::Val( _hx___worldAlpha ); }
if (HX_FIELD_EQ(inName,"hitTestPoint") ) { return ::hx::Val( hitTestPoint_dyn() ); }
if (HX_FIELD_EQ(inName,"__enterFrame") ) { return ::hx::Val( _hx___enterFrame_dyn() ); }
if (HX_FIELD_EQ(inName,"get_rotation") ) { return ::hx::Val( get_rotation_dyn() ); }
if (HX_FIELD_EQ(inName,"set_rotation") ) { return ::hx::Val( set_rotation_dyn() ); }
break;
case 13:
if (HX_FIELD_EQ(inName,"cacheAsBitmap") ) { if (inCallProp == ::hx::paccAlways) return ::hx::Val( get_cacheAsBitmap() ); }
if (HX_FIELD_EQ(inName,"__cacheBitmap") ) { return ::hx::Val( _hx___cacheBitmap ); }
if (HX_FIELD_EQ(inName,"__interactive") ) { return ::hx::Val( _hx___interactive ); }
if (HX_FIELD_EQ(inName,"__renderDirty") ) { return ::hx::Val( _hx___renderDirty ); }
if (HX_FIELD_EQ(inName,"__worldShader") ) { return ::hx::Val( _hx___worldShader ); }
if (HX_FIELD_EQ(inName,"dispatchEvent") ) { return ::hx::Val( dispatchEvent_dyn() ); }
if (HX_FIELD_EQ(inName,"globalToLocal") ) { return ::hx::Val( globalToLocal_dyn() ); }
if (HX_FIELD_EQ(inName,"hitTestObject") ) { return ::hx::Val( hitTestObject_dyn() ); }
if (HX_FIELD_EQ(inName,"localToGlobal") ) { return ::hx::Val( localToGlobal_dyn() ); }
if (HX_FIELD_EQ(inName,"__hitTestMask") ) { return ::hx::Val( _hx___hitTestMask_dyn() ); }
if (HX_FIELD_EQ(inName,"get_blendMode") ) { return ::hx::Val( get_blendMode_dyn() ); }
if (HX_FIELD_EQ(inName,"set_blendMode") ) { return ::hx::Val( set_blendMode_dyn() ); }
if (HX_FIELD_EQ(inName,"get_transform") ) { return ::hx::Val( get_transform_dyn() ); }
if (HX_FIELD_EQ(inName,"set_transform") ) { return ::hx::Val( set_transform_dyn() ); }
break;
case 14:
if (HX_FIELD_EQ(inName,"__drawableType") ) { return ::hx::Val( _hx___drawableType ); }
if (HX_FIELD_EQ(inName,"__renderParent") ) { return ::hx::Val( _hx___renderParent ); }
if (HX_FIELD_EQ(inName,"__rotationSine") ) { return ::hx::Val( _hx___rotationSine ); }
if (HX_FIELD_EQ(inName,"__worldVisible") ) { return ::hx::Val( _hx___worldVisible ); }
if (HX_FIELD_EQ(inName,"get_loaderInfo") ) { return ::hx::Val( get_loaderInfo_dyn() ); }
if (HX_FIELD_EQ(inName,"get_scale9Grid") ) { return ::hx::Val( get_scale9Grid_dyn() ); }
if (HX_FIELD_EQ(inName,"set_scale9Grid") ) { return ::hx::Val( set_scale9Grid_dyn() ); }
if (HX_FIELD_EQ(inName,"get_scrollRect") ) { return ::hx::Val( get_scrollRect_dyn() ); }
if (HX_FIELD_EQ(inName,"set_scrollRect") ) { return ::hx::Val( set_scrollRect_dyn() ); }
break;
case 15:
if (HX_FIELD_EQ(inName,"__cacheAsBitmap") ) { return ::hx::Val( _hx___cacheAsBitmap ); }
if (HX_FIELD_EQ(inName,"__dispatchEvent") ) { return ::hx::Val( _hx___dispatchEvent_dyn() ); }
if (HX_FIELD_EQ(inName,"__globalToLocal") ) { return ::hx::Val( _hx___globalToLocal_dyn() ); }
break;
case 16:
if (HX_FIELD_EQ(inName,"opaqueBackground") ) { return ::hx::Val( opaqueBackground ); }
if (HX_FIELD_EQ(inName,"__rotationCosine") ) { return ::hx::Val( _hx___rotationCosine ); }
if (HX_FIELD_EQ(inName,"__transformDirty") ) { return ::hx::Val( _hx___transformDirty ); }
if (HX_FIELD_EQ(inName,"__worldBlendMode") ) { return ::hx::Val( _hx___worldBlendMode ); }
if (HX_FIELD_EQ(inName,"__worldTransform") ) { return ::hx::Val( _hx___worldTransform ); }
if (HX_FIELD_EQ(inName,"addEventListener") ) { return ::hx::Val( addEventListener_dyn() ); }
if (HX_FIELD_EQ(inName,"__getInteractive") ) { return ::hx::Val( _hx___getInteractive_dyn() ); }
if (HX_FIELD_EQ(inName,"__getLocalBounds") ) { return ::hx::Val( _hx___getLocalBounds_dyn() ); }
if (HX_FIELD_EQ(inName,"__setRenderDirty") ) { return ::hx::Val( _hx___setRenderDirty_dyn() ); }
break;
case 17:
if (HX_FIELD_EQ(inName,"__cacheBitmapData") ) { return ::hx::Val( _hx___cacheBitmapData ); }
if (HX_FIELD_EQ(inName,"__objectTransform") ) { return ::hx::Val( _hx___objectTransform ); }
if (HX_FIELD_EQ(inName,"__renderTransform") ) { return ::hx::Val( _hx___renderTransform ); }
if (HX_FIELD_EQ(inName,"__worldScale9Grid") ) { return ::hx::Val( _hx___worldScale9Grid ); }
if (HX_FIELD_EQ(inName,"__getFilterBounds") ) { return ::hx::Val( _hx___getFilterBounds_dyn() ); }
if (HX_FIELD_EQ(inName,"__getRenderBounds") ) { return ::hx::Val( _hx___getRenderBounds_dyn() ); }
if (HX_FIELD_EQ(inName,"get_cacheAsBitmap") ) { return ::hx::Val( get_cacheAsBitmap_dyn() ); }
if (HX_FIELD_EQ(inName,"set_cacheAsBitmap") ) { return ::hx::Val( set_cacheAsBitmap_dyn() ); }
break;
case 18:
if (HX_FIELD_EQ(inName,"__cacheBitmapData2") ) { return ::hx::Val( _hx___cacheBitmapData2 ); }
if (HX_FIELD_EQ(inName,"__cacheBitmapData3") ) { return ::hx::Val( _hx___cacheBitmapData3 ); }
if (HX_FIELD_EQ(inName,"__worldClipChanged") ) { return ::hx::Val( _hx___worldClipChanged ); }
if (HX_FIELD_EQ(inName,"__dispatchChildren") ) { return ::hx::Val( _hx___dispatchChildren_dyn() ); }
if (HX_FIELD_EQ(inName,"__readGraphicsData") ) { return ::hx::Val( _hx___readGraphicsData_dyn() ); }
if (HX_FIELD_EQ(inName,"__updateTransforms") ) { return ::hx::Val( _hx___updateTransforms_dyn() ); }
break;
case 19:
if (HX_FIELD_EQ(inName,"cacheAsBitmapMatrix") ) { if (inCallProp == ::hx::paccAlways) return ::hx::Val( get_cacheAsBitmapMatrix() ); }
if (HX_FIELD_EQ(inName,"__cacheBitmapMatrix") ) { return ::hx::Val( _hx___cacheBitmapMatrix ); }
if (HX_FIELD_EQ(inName,"__customRenderClear") ) { return ::hx::Val( _hx___customRenderClear ); }
if (HX_FIELD_EQ(inName,"__customRenderEvent") ) { return ::hx::Val( _hx___customRenderEvent ); }
if (HX_FIELD_EQ(inName,"__worldAlphaChanged") ) { return ::hx::Val( _hx___worldAlphaChanged ); }
if (HX_FIELD_EQ(inName,"removeEventListener") ) { return ::hx::Val( removeEventListener_dyn() ); }
if (HX_FIELD_EQ(inName,"__getWorldTransform") ) { return ::hx::Val( _hx___getWorldTransform_dyn() ); }
if (HX_FIELD_EQ(inName,"__setStageReference") ) { return ::hx::Val( _hx___setStageReference_dyn() ); }
if (HX_FIELD_EQ(inName,"__setTransformDirty") ) { return ::hx::Val( _hx___setTransformDirty_dyn() ); }
if (HX_FIELD_EQ(inName,"__stopAllMovieClips") ) { return ::hx::Val( _hx___stopAllMovieClips_dyn() ); }
break;
case 20:
if (HX_FIELD_EQ(inName,"__getRenderTransform") ) { return ::hx::Val( _hx___getRenderTransform_dyn() ); }
break;
case 21:
if (HX_FIELD_EQ(inName,"__cacheAsBitmapMatrix") ) { return ::hx::Val( _hx___cacheAsBitmapMatrix ); }
if (HX_FIELD_EQ(inName,"__cacheBitmapRenderer") ) { return ::hx::Val( _hx___cacheBitmapRenderer ); }
if (HX_FIELD_EQ(inName,"__isCacheBitmapRender") ) { return ::hx::Val( _hx___isCacheBitmapRender ); }
if (HX_FIELD_EQ(inName,"__worldColorTransform") ) { return ::hx::Val( _hx___worldColorTransform ); }
if (HX_FIELD_EQ(inName,"__worldVisibleChanged") ) { return ::hx::Val( _hx___worldVisibleChanged ); }
if (HX_FIELD_EQ(inName,"__dispatchWithCapture") ) { return ::hx::Val( _hx___dispatchWithCapture_dyn() ); }
break;
case 22:
if (HX_FIELD_EQ(inName,"__renderTransformCache") ) { return ::hx::Val( _hx___renderTransformCache ); }
if (HX_FIELD_EQ(inName,"__setParentRenderDirty") ) { return ::hx::Val( _hx___setParentRenderDirty_dyn() ); }
break;
case 23:
if (HX_FIELD_EQ(inName,"__cacheBitmapBackground") ) { return ::hx::Val( _hx___cacheBitmapBackground ); }
if (HX_FIELD_EQ(inName,"__worldTransformInvalid") ) { return ::hx::Val( _hx___worldTransformInvalid ); }
if (HX_FIELD_EQ(inName,"get_cacheAsBitmapMatrix") ) { return ::hx::Val( get_cacheAsBitmapMatrix_dyn() ); }
if (HX_FIELD_EQ(inName,"set_cacheAsBitmapMatrix") ) { return ::hx::Val( set_cacheAsBitmapMatrix_dyn() ); }
break;
case 24:
if (HX_FIELD_EQ(inName,"__renderTransformChanged") ) { return ::hx::Val( _hx___renderTransformChanged ); }
break;
case 26:
if (HX_FIELD_EQ(inName,"__setWorldTransformInvalid") ) { return ::hx::Val( _hx___setWorldTransformInvalid_dyn() ); }
break;
case 27:
if (HX_FIELD_EQ(inName,"__cacheBitmapColorTransform") ) { return ::hx::Val( _hx___cacheBitmapColorTransform ); }
}
return super::__Field(inName,inCallProp);
}
bool DisplayObject_obj::__GetStatic(const ::String &inName, Dynamic &outValue, ::hx::PropertyAccess inCallProp)
{
switch(inName.length) {
case 11:
if (HX_FIELD_EQ(inName,"__initStage") ) { outValue = ( _hx___initStage ); return true; }
if (HX_FIELD_EQ(inName,"__tempStack") ) { outValue = ( _hx___tempStack ); return true; }
break;
case 15:
if (HX_FIELD_EQ(inName,"__instanceCount") ) { outValue = ( _hx___instanceCount ); return true; }
break;
case 17:
if (HX_FIELD_EQ(inName,"__broadcastEvents") ) { outValue = ( _hx___broadcastEvents ); return true; }
break;
case 28:
if (HX_FIELD_EQ(inName,"__calculateAbsoluteTransform") ) { outValue = _hx___calculateAbsoluteTransform_dyn(); return true; }
}
return false;
}
::hx::Val DisplayObject_obj::__SetField(const ::String &inName,const ::hx::Val &inValue,::hx::PropertyAccess inCallProp)
{
switch(inName.length) {
case 1:
if (HX_FIELD_EQ(inName,"x") ) { if (inCallProp == ::hx::paccAlways) return ::hx::Val( set_x(inValue.Cast< Float >()) ); }
if (HX_FIELD_EQ(inName,"y") ) { if (inCallProp == ::hx::paccAlways) return ::hx::Val( set_y(inValue.Cast< Float >()) ); }
break;
case 4:
if (HX_FIELD_EQ(inName,"mask") ) { if (inCallProp == ::hx::paccAlways) return ::hx::Val( set_mask(inValue.Cast< ::openfl::display::DisplayObject >()) ); }
if (HX_FIELD_EQ(inName,"name") ) { if (inCallProp == ::hx::paccAlways) return ::hx::Val( set_name(inValue.Cast< ::String >()) ); }
break;
case 5:
if (HX_FIELD_EQ(inName,"alpha") ) { if (inCallProp == ::hx::paccAlways) return ::hx::Val( set_alpha(inValue.Cast< Float >()) ); }
if (HX_FIELD_EQ(inName,"stage") ) { stage=inValue.Cast< ::openfl::display::Stage >(); return inValue; }
if (HX_FIELD_EQ(inName,"width") ) { if (inCallProp == ::hx::paccAlways) return ::hx::Val( set_width(inValue.Cast< Float >()) ); }
break;
case 6:
if (HX_FIELD_EQ(inName,"height") ) { if (inCallProp == ::hx::paccAlways) return ::hx::Val( set_height(inValue.Cast< Float >()) ); }
if (HX_FIELD_EQ(inName,"parent") ) { parent=inValue.Cast< ::openfl::display::DisplayObjectContainer >(); return inValue; }
if (HX_FIELD_EQ(inName,"scaleX") ) { if (inCallProp == ::hx::paccAlways) return ::hx::Val( set_scaleX(inValue.Cast< Float >()) ); }
if (HX_FIELD_EQ(inName,"scaleY") ) { if (inCallProp == ::hx::paccAlways) return ::hx::Val( set_scaleY(inValue.Cast< Float >()) ); }
if (HX_FIELD_EQ(inName,"shader") ) { if (inCallProp == ::hx::paccAlways) return ::hx::Val( set_shader(inValue.Cast< ::openfl::display::Shader >()) ); }
if (HX_FIELD_EQ(inName,"__mask") ) { _hx___mask=inValue.Cast< ::openfl::display::DisplayObject >(); return inValue; }
if (HX_FIELD_EQ(inName,"__name") ) { _hx___name=inValue.Cast< ::String >(); return inValue; }
break;
case 7:
if (HX_FIELD_EQ(inName,"filters") ) { if (inCallProp == ::hx::paccAlways) return ::hx::Val( set_filters(inValue.Cast< ::Array< ::Dynamic> >()) ); }
if (HX_FIELD_EQ(inName,"visible") ) { if (inCallProp == ::hx::paccAlways) return ::hx::Val( set_visible(inValue.Cast< bool >()) ); }
if (HX_FIELD_EQ(inName,"__alpha") ) { _hx___alpha=inValue.Cast< Float >(); return inValue; }
if (HX_FIELD_EQ(inName,"__cairo") ) { _hx___cairo=inValue.Cast< ::lime::graphics::cairo::Cairo >(); return inValue; }
break;
case 8:
if (HX_FIELD_EQ(inName,"rotation") ) { if (inCallProp == ::hx::paccAlways) return ::hx::Val( set_rotation(inValue.Cast< Float >()) ); }
if (HX_FIELD_EQ(inName,"__isMask") ) { _hx___isMask=inValue.Cast< bool >(); return inValue; }
if (HX_FIELD_EQ(inName,"__scaleX") ) { _hx___scaleX=inValue.Cast< Float >(); return inValue; }
if (HX_FIELD_EQ(inName,"__scaleY") ) { _hx___scaleY=inValue.Cast< Float >(); return inValue; }
if (HX_FIELD_EQ(inName,"__shader") ) { _hx___shader=inValue.Cast< ::openfl::display::Shader >(); return inValue; }
if (HX_FIELD_EQ(inName,"__worldZ") ) { _hx___worldZ=inValue.Cast< int >(); return inValue; }
break;
case 9:
if (HX_FIELD_EQ(inName,"blendMode") ) { if (inCallProp == ::hx::paccAlways) return ::hx::Val( set_blendMode(inValue.Cast< ::Dynamic >()) ); }
if (HX_FIELD_EQ(inName,"transform") ) { if (inCallProp == ::hx::paccAlways) return ::hx::Val( set_transform(inValue.Cast< ::openfl::geom::Transform >()) ); }
if (HX_FIELD_EQ(inName,"__filters") ) { _hx___filters=inValue.Cast< ::Array< ::Dynamic> >(); return inValue; }
if (HX_FIELD_EQ(inName,"__visible") ) { _hx___visible=inValue.Cast< bool >(); return inValue; }
break;
case 10:
if (HX_FIELD_EQ(inName,"scale9Grid") ) { if (inCallProp == ::hx::paccAlways) return ::hx::Val( set_scale9Grid(inValue.Cast< ::openfl::geom::Rectangle >()) ); }
if (HX_FIELD_EQ(inName,"scrollRect") ) { if (inCallProp == ::hx::paccAlways) return ::hx::Val( set_scrollRect(inValue.Cast< ::openfl::geom::Rectangle >()) ); }
if (HX_FIELD_EQ(inName,"__children") ) { _hx___children=inValue.Cast< ::Array< ::Dynamic> >(); return inValue; }
if (HX_FIELD_EQ(inName,"__graphics") ) { _hx___graphics=inValue.Cast< ::openfl::display::Graphics >(); return inValue; }
if (HX_FIELD_EQ(inName,"__rotation") ) { _hx___rotation=inValue.Cast< Float >(); return inValue; }
break;
case 11:
if (HX_FIELD_EQ(inName,"__blendMode") ) { _hx___blendMode=inValue.Cast< ::Dynamic >(); return inValue; }
if (HX_FIELD_EQ(inName,"__tempPoint") ) { _hx___tempPoint=inValue.Cast< ::openfl::geom::Point >(); return inValue; }
if (HX_FIELD_EQ(inName,"__transform") ) { _hx___transform=inValue.Cast< ::openfl::geom::Matrix >(); return inValue; }
if (HX_FIELD_EQ(inName,"__worldClip") ) { _hx___worldClip=inValue.Cast< ::openfl::geom::Rectangle >(); return inValue; }
break;
case 12:
if (HX_FIELD_EQ(inName,"__loaderInfo") ) { _hx___loaderInfo=inValue.Cast< ::openfl::display::LoaderInfo >(); return inValue; }
if (HX_FIELD_EQ(inName,"__maskTarget") ) { _hx___maskTarget=inValue.Cast< ::openfl::display::DisplayObject >(); return inValue; }
if (HX_FIELD_EQ(inName,"__renderable") ) { _hx___renderable=inValue.Cast< bool >(); return inValue; }
if (HX_FIELD_EQ(inName,"__scale9Grid") ) { _hx___scale9Grid=inValue.Cast< ::openfl::geom::Rectangle >(); return inValue; }
if (HX_FIELD_EQ(inName,"__scrollRect") ) { _hx___scrollRect=inValue.Cast< ::openfl::geom::Rectangle >(); return inValue; }
if (HX_FIELD_EQ(inName,"__worldAlpha") ) { _hx___worldAlpha=inValue.Cast< Float >(); return inValue; }
break;
case 13:
if (HX_FIELD_EQ(inName,"cacheAsBitmap") ) { if (inCallProp == ::hx::paccAlways) return ::hx::Val( set_cacheAsBitmap(inValue.Cast< bool >()) ); }
if (HX_FIELD_EQ(inName,"__cacheBitmap") ) { _hx___cacheBitmap=inValue.Cast< ::openfl::display::Bitmap >(); return inValue; }
if (HX_FIELD_EQ(inName,"__interactive") ) { _hx___interactive=inValue.Cast< bool >(); return inValue; }
if (HX_FIELD_EQ(inName,"__renderDirty") ) { _hx___renderDirty=inValue.Cast< bool >(); return inValue; }
if (HX_FIELD_EQ(inName,"__worldShader") ) { _hx___worldShader=inValue.Cast< ::openfl::display::Shader >(); return inValue; }
break;
case 14:
if (HX_FIELD_EQ(inName,"__drawableType") ) { _hx___drawableType=inValue.Cast< int >(); return inValue; }
if (HX_FIELD_EQ(inName,"__renderParent") ) { _hx___renderParent=inValue.Cast< ::openfl::display::DisplayObject >(); return inValue; }
if (HX_FIELD_EQ(inName,"__rotationSine") ) { _hx___rotationSine=inValue.Cast< Float >(); return inValue; }
if (HX_FIELD_EQ(inName,"__worldVisible") ) { _hx___worldVisible=inValue.Cast< bool >(); return inValue; }
break;
case 15:
if (HX_FIELD_EQ(inName,"__cacheAsBitmap") ) { _hx___cacheAsBitmap=inValue.Cast< bool >(); return inValue; }
break;
case 16:
if (HX_FIELD_EQ(inName,"opaqueBackground") ) { opaqueBackground=inValue.Cast< ::Dynamic >(); return inValue; }
if (HX_FIELD_EQ(inName,"__rotationCosine") ) { _hx___rotationCosine=inValue.Cast< Float >(); return inValue; }
if (HX_FIELD_EQ(inName,"__transformDirty") ) { _hx___transformDirty=inValue.Cast< bool >(); return inValue; }
if (HX_FIELD_EQ(inName,"__worldBlendMode") ) { _hx___worldBlendMode=inValue.Cast< ::Dynamic >(); return inValue; }
if (HX_FIELD_EQ(inName,"__worldTransform") ) { _hx___worldTransform=inValue.Cast< ::openfl::geom::Matrix >(); return inValue; }
break;
case 17:
if (HX_FIELD_EQ(inName,"__cacheBitmapData") ) { _hx___cacheBitmapData=inValue.Cast< ::openfl::display::BitmapData >(); return inValue; }
if (HX_FIELD_EQ(inName,"__objectTransform") ) { _hx___objectTransform=inValue.Cast< ::openfl::geom::Transform >(); return inValue; }
if (HX_FIELD_EQ(inName,"__renderTransform") ) { _hx___renderTransform=inValue.Cast< ::openfl::geom::Matrix >(); return inValue; }
if (HX_FIELD_EQ(inName,"__worldScale9Grid") ) { _hx___worldScale9Grid=inValue.Cast< ::openfl::geom::Rectangle >(); return inValue; }
break;
case 18:
if (HX_FIELD_EQ(inName,"__cacheBitmapData2") ) { _hx___cacheBitmapData2=inValue.Cast< ::openfl::display::BitmapData >(); return inValue; }
if (HX_FIELD_EQ(inName,"__cacheBitmapData3") ) { _hx___cacheBitmapData3=inValue.Cast< ::openfl::display::BitmapData >(); return inValue; }
if (HX_FIELD_EQ(inName,"__worldClipChanged") ) { _hx___worldClipChanged=inValue.Cast< bool >(); return inValue; }
break;
case 19:
if (HX_FIELD_EQ(inName,"cacheAsBitmapMatrix") ) { if (inCallProp == ::hx::paccAlways) return ::hx::Val( set_cacheAsBitmapMatrix(inValue.Cast< ::openfl::geom::Matrix >()) ); }
if (HX_FIELD_EQ(inName,"__cacheBitmapMatrix") ) { _hx___cacheBitmapMatrix=inValue.Cast< ::openfl::geom::Matrix >(); return inValue; }
if (HX_FIELD_EQ(inName,"__customRenderClear") ) { _hx___customRenderClear=inValue.Cast< bool >(); return inValue; }
if (HX_FIELD_EQ(inName,"__customRenderEvent") ) { _hx___customRenderEvent=inValue.Cast< ::openfl::events::RenderEvent >(); return inValue; }
if (HX_FIELD_EQ(inName,"__worldAlphaChanged") ) { _hx___worldAlphaChanged=inValue.Cast< bool >(); return inValue; }
break;
case 21:
if (HX_FIELD_EQ(inName,"__cacheAsBitmapMatrix") ) { _hx___cacheAsBitmapMatrix=inValue.Cast< ::openfl::geom::Matrix >(); return inValue; }
if (HX_FIELD_EQ(inName,"__cacheBitmapRenderer") ) { _hx___cacheBitmapRenderer=inValue.Cast< ::openfl::display::DisplayObjectRenderer >(); return inValue; }
if (HX_FIELD_EQ(inName,"__isCacheBitmapRender") ) { _hx___isCacheBitmapRender=inValue.Cast< bool >(); return inValue; }
if (HX_FIELD_EQ(inName,"__worldColorTransform") ) { _hx___worldColorTransform=inValue.Cast< ::openfl::geom::ColorTransform >(); return inValue; }
if (HX_FIELD_EQ(inName,"__worldVisibleChanged") ) { _hx___worldVisibleChanged=inValue.Cast< bool >(); return inValue; }
break;
case 22:
if (HX_FIELD_EQ(inName,"__renderTransformCache") ) { _hx___renderTransformCache=inValue.Cast< ::openfl::geom::Matrix >(); return inValue; }
break;
case 23:
if (HX_FIELD_EQ(inName,"__cacheBitmapBackground") ) { _hx___cacheBitmapBackground=inValue.Cast< ::Dynamic >(); return inValue; }
if (HX_FIELD_EQ(inName,"__worldTransformInvalid") ) { _hx___worldTransformInvalid=inValue.Cast< bool >(); return inValue; }
break;
case 24:
if (HX_FIELD_EQ(inName,"__renderTransformChanged") ) { _hx___renderTransformChanged=inValue.Cast< bool >(); return inValue; }
break;
case 27:
if (HX_FIELD_EQ(inName,"__cacheBitmapColorTransform") ) { _hx___cacheBitmapColorTransform=inValue.Cast< ::openfl::geom::ColorTransform >(); return inValue; }
}
return super::__SetField(inName,inValue,inCallProp);
}
bool DisplayObject_obj::__SetStatic(const ::String &inName,Dynamic &ioValue,::hx::PropertyAccess inCallProp)
{
switch(inName.length) {
case 11:
if (HX_FIELD_EQ(inName,"__initStage") ) { _hx___initStage=ioValue.Cast< ::openfl::display::Stage >(); return true; }
if (HX_FIELD_EQ(inName,"__tempStack") ) { _hx___tempStack=ioValue.Cast< ::lime::utils::ObjectPool >(); return true; }
break;
case 15:
if (HX_FIELD_EQ(inName,"__instanceCount") ) { _hx___instanceCount=ioValue.Cast< int >(); return true; }
break;
case 17:
if (HX_FIELD_EQ(inName,"__broadcastEvents") ) { _hx___broadcastEvents=ioValue.Cast< ::haxe::ds::StringMap >(); return true; }
}
return false;
}
void DisplayObject_obj::__GetFields(Array< ::String> &outFields)
{
outFields->push(HX_("alpha",5e,a7,96,21));
outFields->push(HX_("blendMode",54,e4,37,0c));
outFields->push(HX_("cacheAsBitmap",e3,82,0f,6a));
outFields->push(HX_("cacheAsBitmapMatrix",84,f9,81,95));
outFields->push(HX_("filters",bb,a1,46,09));
outFields->push(HX_("height",e7,07,4c,02));
outFields->push(HX_("loaderInfo",21,b2,e4,b6));
outFields->push(HX_("mask",ec,40,56,48));
outFields->push(HX_("mouseX",93,4a,0e,cc));
outFields->push(HX_("mouseY",94,4a,0e,cc));
outFields->push(HX_("name",4b,72,ff,48));
outFields->push(HX_("opaqueBackground",2f,b8,a7,1a));
outFields->push(HX_("parent",2a,05,7e,ed));
outFields->push(HX_("root",22,ee,ae,4b));
outFields->push(HX_("rotation",3e,3d,86,08));
outFields->push(HX_("scale9Grid",d5,50,22,8f));
outFields->push(HX_("scaleX",8e,ea,25,3c));
outFields->push(HX_("scaleY",8f,ea,25,3c));
outFields->push(HX_("scrollRect",d1,db,66,09));
outFields->push(HX_("shader",25,bf,20,1d));
outFields->push(HX_("stage",be,6a,0b,84));
outFields->push(HX_("transform",6c,2d,93,45));
outFields->push(HX_("visible",72,78,24,a3));
outFields->push(HX_("width",06,b6,62,ca));
outFields->push(HX_("x",78,00,00,00));
outFields->push(HX_("y",79,00,00,00));
outFields->push(HX_("__alpha",3e,00,f5,8b));
outFields->push(HX_("__blendMode",34,2d,64,3a));
outFields->push(HX_("__cacheAsBitmap",c3,bb,c1,f1));
outFields->push(HX_("__cacheAsBitmapMatrix",64,1a,76,03));
outFields->push(HX_("__cacheBitmap",b1,7c,25,58));
outFields->push(HX_("__cacheBitmapBackground",ff,3b,ef,ca));
outFields->push(HX_("__cacheBitmapColorTransform",1a,5c,d5,a9));
outFields->push(HX_("__cacheBitmapData",7b,ab,bc,95));
outFields->push(HX_("__cacheBitmapData2",57,60,59,6f));
outFields->push(HX_("__cacheBitmapData3",58,60,59,6f));
outFields->push(HX_("__cacheBitmapMatrix",d2,41,1e,98));
outFields->push(HX_("__cacheBitmapRenderer",14,97,78,d9));
outFields->push(HX_("__cairo",68,89,77,ab));
outFields->push(HX_("__children",5f,8c,a2,13));
outFields->push(HX_("__customRenderClear",06,03,07,b9));
outFields->push(HX_("__customRenderEvent",93,59,70,e6));
outFields->push(HX_("__drawableType",98,b4,3c,42));
outFields->push(HX_("__filters",9b,f2,94,8a));
outFields->push(HX_("__graphics",eb,6b,a0,b5));
outFields->push(HX_("__interactive",c2,7e,d1,84));
outFields->push(HX_("__isCacheBitmapRender",9d,cb,4a,93));
outFields->push(HX_("__isMask",16,71,ec,0d));
outFields->push(HX_("__loaderInfo",41,2d,78,ef));
outFields->push(HX_("__mask",0c,a4,4e,f7));
outFields->push(HX_("__maskTarget",7d,9c,64,d4));
outFields->push(HX_("__name",6b,d5,f7,f7));
outFields->push(HX_("__objectTransform",8d,6f,30,54));
outFields->push(HX_("__renderable",10,b7,2c,2b));
outFields->push(HX_("__renderDirty",bc,bd,f9,ed));
outFields->push(HX_("__renderParent",40,8c,94,7d));
outFields->push(HX_("__renderTransform",16,b8,95,b1));
outFields->push(HX_("__renderTransformCache",4c,42,cb,bc));
outFields->push(HX_("__renderTransformChanged",7e,ef,84,a1));
outFields->push(HX_("__rotation",5e,b0,be,ab));
outFields->push(HX_("__rotationCosine",f7,71,7b,14));
outFields->push(HX_("__rotationSine",cb,f9,ad,3f));
outFields->push(HX_("__scale9Grid",f5,cb,b5,c7));
outFields->push(HX_("__scaleX",ae,55,55,e4));
outFields->push(HX_("__scaleY",af,55,55,e4));
outFields->push(HX_("__scrollRect",f1,56,fa,41));
outFields->push(HX_("__shader",45,2a,50,c5));
outFields->push(HX_("__tempPoint",7c,01,d0,2a));
outFields->push(HX_("__transform",4c,76,bf,73));
outFields->push(HX_("__transformDirty",26,f6,91,84));
outFields->push(HX_("__visible",52,c9,72,24));
outFields->push(HX_("__worldAlpha",cc,d2,d6,c5));
outFields->push(HX_("__worldAlphaChanged",88,37,d8,d0));
outFields->push(HX_("__worldBlendMode",c2,5e,7d,61));
outFields->push(HX_("__worldClip",22,0b,0b,7d));
outFields->push(HX_("__worldClipChanged",f2,55,0d,68));
outFields->push(HX_("__worldColorTransform",5b,ce,21,a3));
outFields->push(HX_("__worldShader",f7,93,06,31));
outFields->push(HX_("__worldScale9Grid",a7,f6,a7,d6));
outFields->push(HX_("__worldTransform",da,a7,d8,9a));
outFields->push(HX_("__worldVisible",60,db,58,f8));
outFields->push(HX_("__worldVisibleChanged",74,29,51,77));
outFields->push(HX_("__worldTransformInvalid",3d,6a,28,96));
outFields->push(HX_("__worldZ",e8,5c,ce,71));
super::__GetFields(outFields);
};
#ifdef HXCPP_SCRIPTABLE
static ::hx::StorageInfo DisplayObject_obj_sMemberStorageInfo[] = {
{::hx::fsObject /* ::Dynamic */ ,(int)offsetof(DisplayObject_obj,opaqueBackground),HX_("opaqueBackground",2f,b8,a7,1a)},
{::hx::fsObject /* ::openfl::display::DisplayObjectContainer */ ,(int)offsetof(DisplayObject_obj,parent),HX_("parent",2a,05,7e,ed)},
{::hx::fsObject /* ::openfl::display::Stage */ ,(int)offsetof(DisplayObject_obj,stage),HX_("stage",be,6a,0b,84)},
{::hx::fsFloat,(int)offsetof(DisplayObject_obj,_hx___alpha),HX_("__alpha",3e,00,f5,8b)},
{::hx::fsObject /* ::Dynamic */ ,(int)offsetof(DisplayObject_obj,_hx___blendMode),HX_("__blendMode",34,2d,64,3a)},
{::hx::fsBool,(int)offsetof(DisplayObject_obj,_hx___cacheAsBitmap),HX_("__cacheAsBitmap",c3,bb,c1,f1)},
{::hx::fsObject /* ::openfl::geom::Matrix */ ,(int)offsetof(DisplayObject_obj,_hx___cacheAsBitmapMatrix),HX_("__cacheAsBitmapMatrix",64,1a,76,03)},
{::hx::fsObject /* ::openfl::display::Bitmap */ ,(int)offsetof(DisplayObject_obj,_hx___cacheBitmap),HX_("__cacheBitmap",b1,7c,25,58)},
{::hx::fsObject /* ::Dynamic */ ,(int)offsetof(DisplayObject_obj,_hx___cacheBitmapBackground),HX_("__cacheBitmapBackground",ff,3b,ef,ca)},
{::hx::fsObject /* ::openfl::geom::ColorTransform */ ,(int)offsetof(DisplayObject_obj,_hx___cacheBitmapColorTransform),HX_("__cacheBitmapColorTransform",1a,5c,d5,a9)},
{::hx::fsObject /* ::openfl::display::BitmapData */ ,(int)offsetof(DisplayObject_obj,_hx___cacheBitmapData),HX_("__cacheBitmapData",7b,ab,bc,95)},
{::hx::fsObject /* ::openfl::display::BitmapData */ ,(int)offsetof(DisplayObject_obj,_hx___cacheBitmapData2),HX_("__cacheBitmapData2",57,60,59,6f)},
{::hx::fsObject /* ::openfl::display::BitmapData */ ,(int)offsetof(DisplayObject_obj,_hx___cacheBitmapData3),HX_("__cacheBitmapData3",58,60,59,6f)},
{::hx::fsObject /* ::openfl::geom::Matrix */ ,(int)offsetof(DisplayObject_obj,_hx___cacheBitmapMatrix),HX_("__cacheBitmapMatrix",d2,41,1e,98)},
{::hx::fsObject /* ::openfl::display::DisplayObjectRenderer */ ,(int)offsetof(DisplayObject_obj,_hx___cacheBitmapRenderer),HX_("__cacheBitmapRenderer",14,97,78,d9)},
{::hx::fsObject /* ::lime::graphics::cairo::Cairo */ ,(int)offsetof(DisplayObject_obj,_hx___cairo),HX_("__cairo",68,89,77,ab)},
{::hx::fsObject /* ::Array< ::Dynamic> */ ,(int)offsetof(DisplayObject_obj,_hx___children),HX_("__children",5f,8c,a2,13)},
{::hx::fsBool,(int)offsetof(DisplayObject_obj,_hx___customRenderClear),HX_("__customRenderClear",06,03,07,b9)},
{::hx::fsObject /* ::openfl::events::RenderEvent */ ,(int)offsetof(DisplayObject_obj,_hx___customRenderEvent),HX_("__customRenderEvent",93,59,70,e6)},
{::hx::fsInt,(int)offsetof(DisplayObject_obj,_hx___drawableType),HX_("__drawableType",98,b4,3c,42)},
{::hx::fsObject /* ::Array< ::Dynamic> */ ,(int)offsetof(DisplayObject_obj,_hx___filters),HX_("__filters",9b,f2,94,8a)},
{::hx::fsObject /* ::openfl::display::Graphics */ ,(int)offsetof(DisplayObject_obj,_hx___graphics),HX_("__graphics",eb,6b,a0,b5)},
{::hx::fsBool,(int)offsetof(DisplayObject_obj,_hx___interactive),HX_("__interactive",c2,7e,d1,84)},
{::hx::fsBool,(int)offsetof(DisplayObject_obj,_hx___isCacheBitmapRender),HX_("__isCacheBitmapRender",9d,cb,4a,93)},
{::hx::fsBool,(int)offsetof(DisplayObject_obj,_hx___isMask),HX_("__isMask",16,71,ec,0d)},
{::hx::fsObject /* ::openfl::display::LoaderInfo */ ,(int)offsetof(DisplayObject_obj,_hx___loaderInfo),HX_("__loaderInfo",41,2d,78,ef)},
{::hx::fsObject /* ::openfl::display::DisplayObject */ ,(int)offsetof(DisplayObject_obj,_hx___mask),HX_("__mask",0c,a4,4e,f7)},
{::hx::fsObject /* ::openfl::display::DisplayObject */ ,(int)offsetof(DisplayObject_obj,_hx___maskTarget),HX_("__maskTarget",7d,9c,64,d4)},
{::hx::fsString,(int)offsetof(DisplayObject_obj,_hx___name),HX_("__name",6b,d5,f7,f7)},
{::hx::fsObject /* ::openfl::geom::Transform */ ,(int)offsetof(DisplayObject_obj,_hx___objectTransform),HX_("__objectTransform",8d,6f,30,54)},
{::hx::fsBool,(int)offsetof(DisplayObject_obj,_hx___renderable),HX_("__renderable",10,b7,2c,2b)},
{::hx::fsBool,(int)offsetof(DisplayObject_obj,_hx___renderDirty),HX_("__renderDirty",bc,bd,f9,ed)},
{::hx::fsObject /* ::openfl::display::DisplayObject */ ,(int)offsetof(DisplayObject_obj,_hx___renderParent),HX_("__renderParent",40,8c,94,7d)},
{::hx::fsObject /* ::openfl::geom::Matrix */ ,(int)offsetof(DisplayObject_obj,_hx___renderTransform),HX_("__renderTransform",16,b8,95,b1)},
{::hx::fsObject /* ::openfl::geom::Matrix */ ,(int)offsetof(DisplayObject_obj,_hx___renderTransformCache),HX_("__renderTransformCache",4c,42,cb,bc)},
{::hx::fsBool,(int)offsetof(DisplayObject_obj,_hx___renderTransformChanged),HX_("__renderTransformChanged",7e,ef,84,a1)},
{::hx::fsFloat,(int)offsetof(DisplayObject_obj,_hx___rotation),HX_("__rotation",5e,b0,be,ab)},
{::hx::fsFloat,(int)offsetof(DisplayObject_obj,_hx___rotationCosine),HX_("__rotationCosine",f7,71,7b,14)},
{::hx::fsFloat,(int)offsetof(DisplayObject_obj,_hx___rotationSine),HX_("__rotationSine",cb,f9,ad,3f)},
{::hx::fsObject /* ::openfl::geom::Rectangle */ ,(int)offsetof(DisplayObject_obj,_hx___scale9Grid),HX_("__scale9Grid",f5,cb,b5,c7)},
{::hx::fsFloat,(int)offsetof(DisplayObject_obj,_hx___scaleX),HX_("__scaleX",ae,55,55,e4)},
{::hx::fsFloat,(int)offsetof(DisplayObject_obj,_hx___scaleY),HX_("__scaleY",af,55,55,e4)},
{::hx::fsObject /* ::openfl::geom::Rectangle */ ,(int)offsetof(DisplayObject_obj,_hx___scrollRect),HX_("__scrollRect",f1,56,fa,41)},
{::hx::fsObject /* ::openfl::display::Shader */ ,(int)offsetof(DisplayObject_obj,_hx___shader),HX_("__shader",45,2a,50,c5)},
{::hx::fsObject /* ::openfl::geom::Point */ ,(int)offsetof(DisplayObject_obj,_hx___tempPoint),HX_("__tempPoint",7c,01,d0,2a)},
{::hx::fsObject /* ::openfl::geom::Matrix */ ,(int)offsetof(DisplayObject_obj,_hx___transform),HX_("__transform",4c,76,bf,73)},
{::hx::fsBool,(int)offsetof(DisplayObject_obj,_hx___transformDirty),HX_("__transformDirty",26,f6,91,84)},
{::hx::fsBool,(int)offsetof(DisplayObject_obj,_hx___visible),HX_("__visible",52,c9,72,24)},
{::hx::fsFloat,(int)offsetof(DisplayObject_obj,_hx___worldAlpha),HX_("__worldAlpha",cc,d2,d6,c5)},
{::hx::fsBool,(int)offsetof(DisplayObject_obj,_hx___worldAlphaChanged),HX_("__worldAlphaChanged",88,37,d8,d0)},
{::hx::fsObject /* ::Dynamic */ ,(int)offsetof(DisplayObject_obj,_hx___worldBlendMode),HX_("__worldBlendMode",c2,5e,7d,61)},
{::hx::fsObject /* ::openfl::geom::Rectangle */ ,(int)offsetof(DisplayObject_obj,_hx___worldClip),HX_("__worldClip",22,0b,0b,7d)},
{::hx::fsBool,(int)offsetof(DisplayObject_obj,_hx___worldClipChanged),HX_("__worldClipChanged",f2,55,0d,68)},
{::hx::fsObject /* ::openfl::geom::ColorTransform */ ,(int)offsetof(DisplayObject_obj,_hx___worldColorTransform),HX_("__worldColorTransform",5b,ce,21,a3)},
{::hx::fsObject /* ::openfl::display::Shader */ ,(int)offsetof(DisplayObject_obj,_hx___worldShader),HX_("__worldShader",f7,93,06,31)},
{::hx::fsObject /* ::openfl::geom::Rectangle */ ,(int)offsetof(DisplayObject_obj,_hx___worldScale9Grid),HX_("__worldScale9Grid",a7,f6,a7,d6)},
{::hx::fsObject /* ::openfl::geom::Matrix */ ,(int)offsetof(DisplayObject_obj,_hx___worldTransform),HX_("__worldTransform",da,a7,d8,9a)},
{::hx::fsBool,(int)offsetof(DisplayObject_obj,_hx___worldVisible),HX_("__worldVisible",60,db,58,f8)},
{::hx::fsBool,(int)offsetof(DisplayObject_obj,_hx___worldVisibleChanged),HX_("__worldVisibleChanged",74,29,51,77)},
{::hx::fsBool,(int)offsetof(DisplayObject_obj,_hx___worldTransformInvalid),HX_("__worldTransformInvalid",3d,6a,28,96)},
{::hx::fsInt,(int)offsetof(DisplayObject_obj,_hx___worldZ),HX_("__worldZ",e8,5c,ce,71)},
{ ::hx::fsUnknown, 0, null()}
};
static ::hx::StaticInfo DisplayObject_obj_sStaticStorageInfo[] = {
{::hx::fsObject /* ::haxe::ds::StringMap */ ,(void *) &DisplayObject_obj::_hx___broadcastEvents,HX_("__broadcastEvents",da,4d,64,5a)},
{::hx::fsObject /* ::openfl::display::Stage */ ,(void *) &DisplayObject_obj::_hx___initStage,HX_("__initStage",6e,ce,c9,cd)},
{::hx::fsInt,(void *) &DisplayObject_obj::_hx___instanceCount,HX_("__instanceCount",da,31,1e,3f)},
{::hx::fsBool,(void *) &DisplayObject_obj::_hx___supportDOM,HX_("__supportDOM",d3,00,fe,8b)},
{::hx::fsObject /* ::lime::utils::ObjectPool */ ,(void *) &DisplayObject_obj::_hx___tempStack,HX_("__tempStack",74,b4,4b,e8)},
{ ::hx::fsUnknown, 0, null()}
};
#endif
static ::String DisplayObject_obj_sMemberFields[] = {
HX_("opaqueBackground",2f,b8,a7,1a),
HX_("parent",2a,05,7e,ed),
HX_("stage",be,6a,0b,84),
HX_("__alpha",3e,00,f5,8b),
HX_("__blendMode",34,2d,64,3a),
HX_("__cacheAsBitmap",c3,bb,c1,f1),
HX_("__cacheAsBitmapMatrix",64,1a,76,03),
HX_("__cacheBitmap",b1,7c,25,58),
HX_("__cacheBitmapBackground",ff,3b,ef,ca),
HX_("__cacheBitmapColorTransform",1a,5c,d5,a9),
HX_("__cacheBitmapData",7b,ab,bc,95),
HX_("__cacheBitmapData2",57,60,59,6f),
HX_("__cacheBitmapData3",58,60,59,6f),
HX_("__cacheBitmapMatrix",d2,41,1e,98),
HX_("__cacheBitmapRenderer",14,97,78,d9),
HX_("__cairo",68,89,77,ab),
HX_("__children",5f,8c,a2,13),
HX_("__customRenderClear",06,03,07,b9),
HX_("__customRenderEvent",93,59,70,e6),
HX_("__drawableType",98,b4,3c,42),
HX_("__filters",9b,f2,94,8a),
HX_("__graphics",eb,6b,a0,b5),
HX_("__interactive",c2,7e,d1,84),
HX_("__isCacheBitmapRender",9d,cb,4a,93),
HX_("__isMask",16,71,ec,0d),
HX_("__loaderInfo",41,2d,78,ef),
HX_("__mask",0c,a4,4e,f7),
HX_("__maskTarget",7d,9c,64,d4),
HX_("__name",6b,d5,f7,f7),
HX_("__objectTransform",8d,6f,30,54),
HX_("__renderable",10,b7,2c,2b),
HX_("__renderDirty",bc,bd,f9,ed),
HX_("__renderParent",40,8c,94,7d),
HX_("__renderTransform",16,b8,95,b1),
HX_("__renderTransformCache",4c,42,cb,bc),
HX_("__renderTransformChanged",7e,ef,84,a1),
HX_("__rotation",5e,b0,be,ab),
HX_("__rotationCosine",f7,71,7b,14),
HX_("__rotationSine",cb,f9,ad,3f),
HX_("__scale9Grid",f5,cb,b5,c7),
HX_("__scaleX",ae,55,55,e4),
HX_("__scaleY",af,55,55,e4),
HX_("__scrollRect",f1,56,fa,41),
HX_("__shader",45,2a,50,c5),
HX_("__tempPoint",7c,01,d0,2a),
HX_("__transform",4c,76,bf,73),
HX_("__transformDirty",26,f6,91,84),
HX_("__visible",52,c9,72,24),
HX_("__worldAlpha",cc,d2,d6,c5),
HX_("__worldAlphaChanged",88,37,d8,d0),
HX_("__worldBlendMode",c2,5e,7d,61),
HX_("__worldClip",22,0b,0b,7d),
HX_("__worldClipChanged",f2,55,0d,68),
HX_("__worldColorTransform",5b,ce,21,a3),
HX_("__worldShader",f7,93,06,31),
HX_("__worldScale9Grid",a7,f6,a7,d6),
HX_("__worldTransform",da,a7,d8,9a),
HX_("__worldVisible",60,db,58,f8),
HX_("__worldVisibleChanged",74,29,51,77),
HX_("__worldTransformInvalid",3d,6a,28,96),
HX_("__worldZ",e8,5c,ce,71),
HX_("addEventListener",cd,0b,64,f1),
HX_("dispatchEvent",00,c7,64,c6),
HX_("getBounds",ab,0f,74,e2),
HX_("getRect",da,fc,29,1e),
HX_("globalToLocal",cd,4e,ae,6b),
HX_("hitTestObject",e4,54,64,d7),
HX_("hitTestPoint",cb,a9,21,e4),
HX_("invalidate",7b,19,2a,87),
HX_("localToGlobal",c9,41,eb,47),
HX_("removeEventListener",ca,87,75,55),
HX_("__cleanup",04,5d,90,2c),
HX_("__dispatch",da,41,9c,c1),
HX_("__dispatchChildren",39,81,f4,f4),
HX_("__dispatchEvent",e0,ff,16,4e),
HX_("__dispatchWithCapture",66,3f,63,34),
HX_("__enterFrame",15,7f,e3,3a),
HX_("__getBounds",8b,58,a0,10),
HX_("__getCursor",ec,60,6b,e9),
HX_("__getFilterBounds",e3,3a,ba,18),
HX_("__getInteractive",0c,1c,37,f8),
HX_("__getLocalBounds",6a,04,36,df),
HX_("__getRenderBounds",01,11,b8,7b),
HX_("__getRenderTransform",60,c2,34,c0),
HX_("__getWorldTransform",d0,f4,fc,8b),
HX_("__globalToLocal",ad,87,60,f3),
HX_("__hitTest",25,b1,cd,63),
HX_("__hitTestMask",b1,14,fd,3b),
HX_("__readGraphicsData",2b,10,91,f2),
HX_("__setParentRenderDirty",f0,bc,57,f3),
HX_("__setRenderDirty",7a,43,7f,81),
HX_("__setStageReference",4f,e5,e5,f4),
HX_("__setTransformDirty",28,1b,24,99),
HX_("__setWorldTransformInvalid",7b,c9,b9,d4),
HX_("__stopAllMovieClips",d2,89,e8,53),
HX_("__update",29,f1,34,2f),
HX_("__updateTransforms",10,f4,b0,50),
HX_("get_alpha",b5,03,40,65),
HX_("set_alpha",c1,ef,90,48),
HX_("get_blendMode",2b,b8,9b,cd),
HX_("set_blendMode",37,9a,a1,12),
HX_("get_cacheAsBitmap",3a,8e,7f,70),
HX_("set_cacheAsBitmap",46,66,ed,93),
HX_("get_cacheAsBitmapMatrix",1b,a0,d7,9d),
HX_("set_cacheAsBitmapMatrix",27,09,39,a0),
HX_("get_filters",d2,01,41,8f),
HX_("set_filters",de,08,ae,99),
HX_("get_height",b0,77,d3,f2),
HX_("set_height",24,16,51,f6),
HX_("get_loaderInfo",6a,3a,da,2c),
HX_("get_mask",75,fc,10,c8),
HX_("set_mask",e9,55,6e,76),
HX_("get_mouseX",5c,ba,95,bc),
HX_("get_mouseY",5d,ba,95,bc),
HX_("get_name",d4,2d,ba,c8),
HX_("set_name",48,87,17,77),
HX_("get_root",ab,a9,69,cb),
HX_("get_rotation",47,f1,9f,bd),
HX_("set_rotation",bb,14,99,d2),
HX_("get_scale9Grid",1e,d9,17,05),
HX_("set_scale9Grid",92,c1,37,25),
HX_("get_scaleX",57,5a,ad,2c),
HX_("set_scaleX",cb,f8,2a,30),
HX_("get_scaleY",58,5a,ad,2c),
HX_("set_scaleY",cc,f8,2a,30),
HX_("get_scrollRect",1a,64,5c,7f),
HX_("set_scrollRect",8e,4c,7c,9f),
HX_("get_shader",ee,2e,a8,0d),
HX_("set_shader",62,cd,25,11),
HX_("get_transform",43,01,f7,06),
HX_("set_transform",4f,e3,fc,4b),
HX_("get_visible",89,d8,1e,29),
HX_("set_visible",95,df,8b,33),
HX_("get_width",5d,12,0c,0e),
HX_("set_width",69,fe,5c,f1),
HX_("get_x",4f,a5,60,91),
HX_("set_x",5b,9b,2f,7a),
HX_("get_y",50,a5,60,91),
HX_("set_y",5c,9b,2f,7a),
::String(null()) };
static void DisplayObject_obj_sMarkStatics(HX_MARK_PARAMS) {
HX_MARK_MEMBER_NAME(DisplayObject_obj::_hx___broadcastEvents,"__broadcastEvents");
HX_MARK_MEMBER_NAME(DisplayObject_obj::_hx___initStage,"__initStage");
HX_MARK_MEMBER_NAME(DisplayObject_obj::_hx___instanceCount,"__instanceCount");
HX_MARK_MEMBER_NAME(DisplayObject_obj::_hx___supportDOM,"__supportDOM");
HX_MARK_MEMBER_NAME(DisplayObject_obj::_hx___tempStack,"__tempStack");
};
#ifdef HXCPP_VISIT_ALLOCS
static void DisplayObject_obj_sVisitStatics(HX_VISIT_PARAMS) {
HX_VISIT_MEMBER_NAME(DisplayObject_obj::_hx___broadcastEvents,"__broadcastEvents");
HX_VISIT_MEMBER_NAME(DisplayObject_obj::_hx___initStage,"__initStage");
HX_VISIT_MEMBER_NAME(DisplayObject_obj::_hx___instanceCount,"__instanceCount");
HX_VISIT_MEMBER_NAME(DisplayObject_obj::_hx___supportDOM,"__supportDOM");
HX_VISIT_MEMBER_NAME(DisplayObject_obj::_hx___tempStack,"__tempStack");
};
#endif
::hx::Class DisplayObject_obj::__mClass;
static ::String DisplayObject_obj_sStaticFields[] = {
HX_("__broadcastEvents",da,4d,64,5a),
HX_("__initStage",6e,ce,c9,cd),
HX_("__instanceCount",da,31,1e,3f),
HX_("__supportDOM",d3,00,fe,8b),
HX_("__tempStack",74,b4,4b,e8),
HX_("__calculateAbsoluteTransform",cf,aa,ec,8d),
::String(null())
};
void DisplayObject_obj::__register()
{
DisplayObject_obj _hx_dummy;
DisplayObject_obj::_hx_vtable = *(void **)&_hx_dummy;
::hx::Static(__mClass) = new ::hx::Class_obj();
__mClass->mName = HX_("openfl.display.DisplayObject",f7,4b,6f,ea);
__mClass->mSuper = &super::__SGetClass();
__mClass->mConstructEmpty = &__CreateEmpty;
__mClass->mConstructArgs = &__Create;
__mClass->mGetStaticField = &DisplayObject_obj::__GetStatic;
__mClass->mSetStaticField = &DisplayObject_obj::__SetStatic;
__mClass->mMarkFunc = DisplayObject_obj_sMarkStatics;
__mClass->mStatics = ::hx::Class_obj::dupFunctions(DisplayObject_obj_sStaticFields);
__mClass->mMembers = ::hx::Class_obj::dupFunctions(DisplayObject_obj_sMemberFields);
__mClass->mCanCast = ::hx::TCanCast< DisplayObject_obj >;
#ifdef HXCPP_VISIT_ALLOCS
__mClass->mVisitFunc = DisplayObject_obj_sVisitStatics;
#endif
#ifdef HXCPP_SCRIPTABLE
__mClass->mMemberStorageInfo = DisplayObject_obj_sMemberStorageInfo;
#endif
#ifdef HXCPP_SCRIPTABLE
__mClass->mStaticStorageInfo = DisplayObject_obj_sStaticStorageInfo;
#endif
::hx::_hx_RegisterClass(__mClass->mName, __mClass);
}
void DisplayObject_obj::__boot()
{
{
HX_STACKFRAME(&_hx_pos_26400284d5456c16_182_boot)
HXDLIN( 182) __mClass->__meta__ = ::Dynamic(::hx::Anon_obj::Create(1)
->setFixed(0,HX_("fields",79,8e,8e,80), ::Dynamic(::hx::Anon_obj::Create(3)
->setFixed(0,HX_("__cairo",68,89,77,ab), ::Dynamic(::hx::Anon_obj::Create(1)
->setFixed(0,HX_("SuppressWarnings",0c,d3,d2,00),::cpp::VirtualArray_obj::__new(1)->init(0,HX_("checkstyle:Dynamic",ce,ea,47,3c)))))
->setFixed(1,HX_("addEventListener",cd,0b,64,f1), ::Dynamic(::hx::Anon_obj::Create(1)
->setFixed(0,HX_("SuppressWarnings",0c,d3,d2,00),::cpp::VirtualArray_obj::__new(1)->init(0,HX_("checkstyle:Dynamic",ce,ea,47,3c)))))
->setFixed(2,HX_("removeEventListener",ca,87,75,55), ::Dynamic(::hx::Anon_obj::Create(1)
->setFixed(0,HX_("SuppressWarnings",0c,d3,d2,00),::cpp::VirtualArray_obj::__new(1)->init(0,HX_("checkstyle:Dynamic",ce,ea,47,3c))))))));
}
{
HX_GC_STACKFRAME(&_hx_pos_26400284d5456c16_184_boot)
HXDLIN( 184) _hx___broadcastEvents = ::haxe::ds::StringMap_obj::__alloc( HX_CTX );
}
{
HX_STACKFRAME(&_hx_pos_26400284d5456c16_186_boot)
HXDLIN( 186) _hx___instanceCount = 0;
}
{
HX_STACKFRAME(&_hx_pos_26400284d5456c16_189_boot)
HXDLIN( 189) _hx___supportDOM = false;
}
{
HX_BEGIN_LOCAL_FUNC_S0(::hx::LocalFunc,_hx_Closure_0) HXARGC(0)
::openfl::_Vector::ObjectVector _hx_run(){
HX_GC_STACKFRAME(&_hx_pos_26400284d5456c16_191_boot)
HXLINE( 192) int length = null();
HXDLIN( 192) bool fixed = null();
HXDLIN( 192) ::Array< ::Dynamic> array = null();
HXDLIN( 192) return ::openfl::_Vector::ObjectVector_obj::__alloc( HX_CTX ,length,fixed,array,true);
}
HX_END_LOCAL_FUNC0(return)
HX_BEGIN_LOCAL_FUNC_S0(::hx::LocalFunc,_hx_Closure_1) HXARGC(1)
void _hx_run( ::openfl::_Vector::ObjectVector stack){
HX_STACKFRAME(&_hx_pos_26400284d5456c16_192_boot)
HXLINE( 192) stack->set_length(0);
}
HX_END_LOCAL_FUNC1((void))
HX_GC_STACKFRAME(&_hx_pos_26400284d5456c16_191_boot)
HXDLIN( 191) _hx___tempStack = ::lime::utils::ObjectPool_obj::__alloc( HX_CTX , ::Dynamic(new _hx_Closure_0()), ::Dynamic(new _hx_Closure_1()),null());
}
}
} // end namespace openfl
} // end namespace display
| 53.006738 | 317 | 0.71483 | [
"render",
"object",
"transform",
"3d"
] |
29236e9be8d939f3e98b6a6a36a5855b3af8c02c | 897 | cpp | C++ | 2nd/091_decode_ways.cpp | buptlxb/leetcode | b641419de040801c4f54618d7ee26edcf10ee53c | [
"BSD-3-Clause"
] | null | null | null | 2nd/091_decode_ways.cpp | buptlxb/leetcode | b641419de040801c4f54618d7ee26edcf10ee53c | [
"BSD-3-Clause"
] | null | null | null | 2nd/091_decode_ways.cpp | buptlxb/leetcode | b641419de040801c4f54618d7ee26edcf10ee53c | [
"BSD-3-Clause"
] | null | null | null | #include <iostream>
#include <vector>
#include <cassert>
using namespace std;
class Solution {
public:
typedef vector<int>::size_type sz_t;
int numDecodings(string s) {
if (s.size() == 0 || s[0] == '0')
return 0;
int a, b, c;
a = b = c = 1;
for (sz_t i = 1, iend = s.size(); i < iend; ++i) {
if (s[i] == '0') {
if (s[i-1] == '1' || s[i-1] == '2')
c = a;
else
return 0;
} else {
if (s[i-1] == '0' || s[i-1] > '2')
c = b;
else if (s[i-1] == '2' && s[i] > '6')
c = b;
else c = b + a;
}
a = b;
b = c;
}
return b;
}
};
int main(void)
{
Solution s;
assert(s.numDecodings("12") == 2);
return 0;
}
| 21.878049 | 58 | 0.342252 | [
"vector"
] |
29326a62ac836850475f0985bb3bbec802daefd2 | 4,363 | hpp | C++ | third-party/casadi/casadi/core/linsol_internal.hpp | dbdxnuliba/mit-biomimetics_Cheetah | f3b0c0f6a3835d33b7f2f345f00640b3fc256388 | [
"MIT"
] | 8 | 2020-02-18T09:07:48.000Z | 2021-12-25T05:40:02.000Z | third-party/casadi/casadi/core/linsol_internal.hpp | geekfeiw/Cheetah-Software | f3b0c0f6a3835d33b7f2f345f00640b3fc256388 | [
"MIT"
] | null | null | null | third-party/casadi/casadi/core/linsol_internal.hpp | geekfeiw/Cheetah-Software | f3b0c0f6a3835d33b7f2f345f00640b3fc256388 | [
"MIT"
] | 13 | 2019-08-25T12:32:06.000Z | 2022-03-31T02:38:12.000Z | /*
* This file is part of CasADi.
*
* CasADi -- A symbolic framework for dynamic optimization.
* Copyright (C) 2010-2014 Joel Andersson, Joris Gillis, Moritz Diehl,
* K.U. Leuven. All rights reserved.
* Copyright (C) 2011-2014 Greg Horn
*
* CasADi 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.
*
* CasADi 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 CasADi; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
#ifndef CASADI_LINSOL_INTERNAL_HPP
#define CASADI_LINSOL_INTERNAL_HPP
#include "linsol.hpp"
#include "function_internal.hpp"
#include "plugin_interface.hpp"
/// \cond INTERNAL
namespace casadi {
struct CASADI_EXPORT LinsolMemory {
// Current state of factorization
bool is_sfact, is_nfact;
// Constructor
LinsolMemory() : is_sfact(false), is_nfact(false) {}
};
/** Internal class
@copydoc Linsol_doc
*/
class CASADI_EXPORT LinsolInternal
: public ProtoFunction, public PluginInterface<LinsolInternal> {
public:
/// Constructor
LinsolInternal(const std::string& name, const Sparsity& sp);
/// Destructor
~LinsolInternal() override;
/** \brief Display object */
void disp(std::ostream& stream, bool more) const override;
/** \brief Print more */
virtual void disp_more(std::ostream& stream) const {}
/// Initialize
void init(const Dict& opts) override;
/** \brief Create memory block */
void* alloc_mem() const override { return new LinsolMemory();}
/** \brief Initalize memory block */
int init_mem(void* mem) const override;
/** \brief Free memory block */
void free_mem(void *mem) const override { delete static_cast<LinsolMemory*>(mem);}
/// Evaluate SX, possibly transposed
virtual void linsol_eval_sx(const SXElem** arg, SXElem** res,
casadi_int* iw, SXElem* w, void* mem,
bool tr, casadi_int nrhs) const;
#if 0
// (Re)factorize the system
casadi_int factorize(void* mem, const double* A) const;
// Needs symbolic factorization
virtual bool needs_sfact(void* mem, const double* A) const;
// Needs numeric factorization
virtual bool needs_nfact(void* mem, const double* A) const;
#endif
// Symbolic factorization
virtual int sfact(void* mem, const double* A) const { return 0;}
/// Numeric factorization
virtual int nfact(void* mem, const double* A) const;
// Solve numerically
virtual int solve(void* mem, const double* A, double* x, casadi_int nrhs, bool tr) const;
/// Number of negative eigenvalues
virtual casadi_int neig(void* mem, const double* A) const;
/// Matrix rank
virtual casadi_int rank(void* mem, const double* A) const;
/// Generate C code
virtual void generate(CodeGenerator& g, const std::string& A, const std::string& x,
casadi_int nrhs, bool tr) const;
// Creator function for internal class
typedef LinsolInternal* (*Creator)(const std::string& name, const Sparsity& sp);
// No static functions exposed
struct Exposed{ };
/// Collection of solvers
static std::map<std::string, Plugin> solvers_;
/// Infix
static const std::string infix_;
// Get name of the plugin
const char* plugin_name() const override = 0;
/// Get sparsity pattern
casadi_int nrow() const { return sp_.size1();}
casadi_int ncol() const { return sp_.size2();}
const casadi_int* colind() const { return sp_.colind();}
const casadi_int* row() const { return sp_.row();}
casadi_int nnz() const { return sp_.nnz();}
// Sparsity pattern of the linear system
Sparsity sp_;
};
} // namespace casadi
/// \endcond
#endif // CASADI_LINSOL_INTERNAL_HPP
| 31.164286 | 93 | 0.667431 | [
"object"
] |
293317f5c009cded85417a192c899bc9f3cd414b | 139,695 | cpp | C++ | Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/opengl/GLLogWrapper.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/opengl/GLLogWrapper.cpp | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | null | null | null | Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/opengl/GLLogWrapper.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/opengl/GLLogWrapper.h"
#include "Elastos.CoreLibrary.IO.h"
#include <elastos/core/StringUtils.h>
#include <elastos/core/Math.h>
#include <elastos/utility/logging/Slogger.h>
using Elastos::Core::StringUtils;
using Elastos::IO::IFlushable;
using Elastos::IO::ByteOrder;
using Elastos::IO::IByteBufferHelper;
using Elastos::IO::CByteBufferHelper;
using Elastos::IO::IByteOrderHelper;
using Elastos::IO::CByteOrderHelper;
using Elastos::IO::IByteBuffer;
using Elastos::IO::ICharBuffer;
using Elastos::IO::IInt16Buffer;
using Elastos::IO::IInt32Buffer;
using Elastos::IO::IInt64Buffer;
using Elastos::IO::IDoubleBuffer;
namespace Elastos {
namespace Droid {
namespace Opengl {
GLLogWrapper::PointerInfo::PointerInfo(
/* [in] */ GLLogWrapper* host)
: mSize(0)
, mType(0)
, mStride(0)
, mHost(host)
{}
GLLogWrapper::PointerInfo::PointerInfo(
/* [in] */ Int32 size,
/* [in] */ Int32 type,
/* [in] */ Int32 stride,
/* [in] */ IBuffer* pointer,
/* [in] */ GLLogWrapper* host)
{
mSize = size;
mType = type;
mStride = stride;
mPointer = pointer;
mHost = host;
}
Int32 GLLogWrapper::PointerInfo::Sizeof(
/* [in] */ Int32 type)
{
switch (type) {
case IGL10::_GL_UNSIGNED_BYTE:
return 1;
case IGL10::_GL_BYTE:
return 1;
case IGL10::_GL_SHORT:
return 2;
case IGL10::_GL_FIXED:
return 4;
case IGL10::_GL_FLOAT:
return 4;
default:
return 0;
}
}
Int32 GLLogWrapper::PointerInfo::GetStride()
{
return mStride > 0 ? mStride : Sizeof(mType) * mSize;
}
ECode GLLogWrapper::PointerInfo::BindByteBuffer()
{
if (mPointer == NULL) {
mTempByteBuffer = NULL;
} else {
mHost->ToByteBuffer(-1, mPointer, (IByteBuffer**)&mTempByteBuffer);
}
return NOERROR;
}
ECode GLLogWrapper::PointerInfo::UnbindByteBuffer()
{
mTempByteBuffer = NULL;
return NOERROR;
}
GLLogWrapper::GLLogWrapper(
/* [in] */ IGL* gl,
/* [in] */ IWriter* log,
/* [in] */ Boolean logArgumentNames)
: GLWrapperBase(gl)
{
mLog = log;
mLogArgumentNames = logArgumentNames;
}
ECode GLLogWrapper::CheckError()
{
Int32 glError;
if ((mgl->GlGetError(&glError), glError) != 0) {
String errorMessage = String("glError") + StringUtils::ToString(glError);
LogLine(errorMessage);
}
return NOERROR;
}
ECode GLLogWrapper::LogLine(
/* [in] */ const String& message)
{
return Log(message + "\n");
}
ECode GLLogWrapper::Log(
/* [in] */ const String& message)
{
mLog->Write(message);
return NOERROR;
}
ECode GLLogWrapper::Begin(
/* [in] */ const String& name)
{
Log(name + "(");
mArgCount = 0;
return NOERROR;
}
ECode GLLogWrapper::Arg(
/* [in] */ const String& name,
/* [in] */ const String& value)
{
if (mArgCount++ > 0) {
Log(String(", "));
}
if (mLogArgumentNames) {
Log(name + "=");
}
Log(value);
return NOERROR;
}
ECode GLLogWrapper::End()
{
Log(String(");\n"));
Flush();
return NOERROR;
}
ECode GLLogWrapper::Flush()
{
// try {
if(FAILED(IFlushable::Probe(mLog)->Flush())) {
mLog = NULL;
}
// } catch (IOException e) {
// mLog = null;
// }
return NOERROR;
}
ECode GLLogWrapper::Arg(
/* [in] */ const String& name,
/* [in] */ Boolean value)
{
return Arg(name, StringUtils::BooleanToString(value));
}
ECode GLLogWrapper::Arg(
/* [in] */ const String& name,
/* [in] */ Int32 value)
{
return Arg(name, StringUtils::ToString(value));
}
ECode GLLogWrapper::Arg(
/* [in] */ const String& name,
/* [in] */ Float value)
{
return Arg(name, StringUtils::ToString(value));
}
ECode GLLogWrapper::Returns(
/* [in] */ const String& result)
{
Log(String(") Returns ") + result + ");\n");
Flush();
return NOERROR;
}
ECode GLLogWrapper::Returns(
/* [in] */ Int32 result)
{
Returns(StringUtils::ToString(result));
return NOERROR;
}
ECode GLLogWrapper::Arg(
/* [in] */ const String& name,
/* [in] */ Int32 n,
/* [in] */ ArrayOf<Int32>* arr,
/* [in] */ Int32 offset)
{
return Arg(name, ToString(n, FORMAT_INT, arr, offset));
}
ECode GLLogWrapper::Arg(
/* [in] */ const String& name,
/* [in] */ Int32 n,
/* [in] */ ArrayOf<Int16>* arr,
/* [in] */ Int32 offset)
{
return Arg(name, ToString(n, arr, offset));
}
ECode GLLogWrapper::Arg(
/* [in] */ const String& name,
/* [in] */ Int32 n,
/* [in] */ ArrayOf<Float>* arr,
/* [in] */ Int32 offset)
{
return Arg(name, ToString(n, arr, offset));
}
ECode GLLogWrapper::FormattedAppend(
/* [in] */ StringBuilder& buf,
/* [in] */ Int32 value,
/* [in] */ Int32 format)
{
switch (format) {
case FORMAT_INT:
buf += value;
break;
case FORMAT_FLOAT:
buf += Elastos::Core::Math::FloatToInt32Bits(value);
break;
case FORMAT_FIXED:
buf += value / 65536.0f;
break;
}
return NOERROR;
}
String GLLogWrapper::ToString(
/* [in] */ Int32 n,
/* [in] */ Int32 format,
/* [in] */ ArrayOf<Int32>* arr,
/* [in] */ Int32 offset)
{
StringBuilder buf;
buf += "{\n";
Int32 arrLen = arr->GetLength();
for (Int32 i = 0; i < n; i++) {
Int32 index = offset + i;
buf += " [";
buf += index;
buf += "] = ";
if (index < 0 || index >= arrLen) {
buf += "out of bounds";
} else {
FormattedAppend(buf, (*arr)[index], format);
}
buf += '\n';
}
buf += "}";
return buf.ToString();
}
String GLLogWrapper::ToString(
/* [in] */ Int32 n,
/* [in] */ ArrayOf<Int16>* arr,
/* [in] */ Int32 offset)
{
StringBuilder buf;
buf += "{\n";
Int32 arrLen = arr->GetLength();
for (Int32 i = 0; i < n; i++) {
Int32 index = offset + i;
buf += " [";
buf += index;
buf += "] = ";
if (index < 0 || index >= arrLen) {
buf += "out of bounds";
} else {
buf += (*arr)[index];
}
buf += '\n';
}
buf += "}";
return buf.ToString();
}
String GLLogWrapper::ToString(
/* [in] */ Int32 n,
/* [in] */ ArrayOf<Float>* arr,
/* [in] */ Int32 offset)
{
StringBuilder buf;
buf += "{\n";
Int32 arrLen = arr->GetLength();
for (Int32 i = 0; i < n; i++) {
Int32 index = offset + i;
buf += " [";
buf += index;
buf += "] = ";
if (index < 0 || index >= arrLen) {
buf += "out of bounds";
} else {
buf += (*arr)[index];
}
buf += '\n';
}
buf += "}";
return buf.ToString();
}
String GLLogWrapper::ToString(
/* [in] */ Int32 n,
/* [in] */ IFloatBuffer* buf)
{
StringBuilder builder;
builder += "{\n";
for (Int32 i = 0; i < n; i++) {
builder += " [";
builder += i;
builder += "] = ";
Float f;
buf->Get(i, &f);
builder += f;
builder += '\n';
}
builder += "}";
return builder.ToString();
}
String GLLogWrapper::ToString(
/* [in] */ Int32 n,
/* [in] */ Int32 format,
/* [in] */ IInt32Buffer* buf)
{
StringBuilder builder;
builder += "{\n";
for (Int32 i = 0; i < n; i++) {
builder += " [";
builder += i;
builder += "] = ";
Int32 f;
buf->Get(i, &f);
builder += FormattedAppend(builder, f, format);
builder += '\n';
}
builder += "}";
return builder.ToString();
}
String GLLogWrapper::ToString(
/* [in] */ Int32 n,
/* [in] */ IInt16Buffer* buf)
{
StringBuilder builder;
builder += "{\n";
for (Int32 i = 0; i < n; i++) {
builder += " [";
builder += i;
builder += "] = ";
Int16 f;
buf->Get(i, &f);
builder += f;
builder += '\n';
}
builder += "}";
return builder.ToString();
}
ECode GLLogWrapper::Arg(
/* [in] */ const String& name,
/* [in] */ Int32 n,
/* [in] */ IFloatBuffer* buf)
{
return Arg(name, ToString(n, buf));
}
ECode GLLogWrapper::Arg(
/* [in] */ const String& name,
/* [in] */ Int32 n,
/* [in] */ IInt32Buffer* buf)
{
return Arg(name, ToString(n, FORMAT_INT, buf));
}
ECode GLLogWrapper::Arg(
/* [in] */ const String& name,
/* [in] */ Int32 n,
/* [in] */ IInt16Buffer* buf)
{
return Arg(name, ToString(n, buf));
}
ECode GLLogWrapper::ArgPointer(
/* [in] */ Int32 size,
/* [in] */ Int32 type,
/* [in] */ Int32 stride,
/* [in] */ IBuffer* pointer)
{
Arg(String("size"), size);
Arg(String("type"), GetPointerTypeName(type));
Arg(String("stride"), stride);
Arg(String("pointer"), ParamsToString(pointer));
return NOERROR;
}
String GLLogWrapper::GetHex(
/* [in] */ Int32 value)
{
return String("0x") + StringUtils::ToString(value, 16);
}
String GLLogWrapper::GetErrorString(
/* [in] */ Int32 error)
{
switch (error) {
case IGL10::_GL_NO_ERROR:
return String("GL_NO_ERROR");
case IGL10::_GL_INVALID_ENUM:
return String("GL_INVALID_ENUM");
case IGL10::_GL_INVALID_VALUE:
return String("GL_INVALID_VALUE");
case IGL10::_GL_INVALID_OPERATION:
return String("GL_INVALID_OPERATION");
case IGL10::_GL_STACK_OVERFLOW:
return String("GL_STACK_OVERFLOW");
case IGL10::_GL_STACK_UNDERFLOW:
return String("GL_STACK_UNDERFLOW");
case IGL10::_GL_OUT_OF_MEMORY:
return String("GL_OUT_OF_MEMORY");
default:
return GetHex(error);
}
}
String GLLogWrapper::GetClearBufferMask(
/* [in] */ Int32 mask)
{
StringBuilder b;
if ((mask & IGL10::_GL_DEPTH_BUFFER_BIT) != 0) {
b += "GL_DEPTH_BUFFER_BIT";
mask &= ~IGL10::_GL_DEPTH_BUFFER_BIT;
}
if ((mask & IGL10::_GL_STENCIL_BUFFER_BIT) != 0) {
Int32 len;
b.GetLength(&len);
if (len > 0) {
b += " | ";
}
b += "GL_STENCIL_BUFFER_BIT";
mask &= ~IGL10::_GL_STENCIL_BUFFER_BIT;
}
if ((mask & IGL10::_GL_COLOR_BUFFER_BIT) != 0) {
Int32 len;
b.GetLength(&len);
if (len > 0) {
b += " | ";
}
b += "GL_COLOR_BUFFER_BIT";
mask &= ~IGL10::_GL_COLOR_BUFFER_BIT;
}
if (mask != 0) {
Int32 len;
b.GetLength(&len);
if (len > 0) {
b += " | ";
}
b += GetHex(mask);
}
return b.ToString();
}
String GLLogWrapper::GetFactor(
/* [in] */ Int32 factor)
{
switch(factor) {
case IGL10::_GL_ZERO:
return String("GL_ZERO");
case IGL10::_GL_ONE:
return String("GL_ONE");
case IGL10::_GL_SRC_COLOR:
return String("GL_SRC_COLOR");
case IGL10::_GL_ONE_MINUS_SRC_COLOR:
return String("GL_ONE_MINUS_SRC_COLOR");
case IGL10::_GL_DST_COLOR:
return String("GL_DST_COLOR");
case IGL10::_GL_ONE_MINUS_DST_COLOR:
return String("GL_ONE_MINUS_DST_COLOR");
case IGL10::_GL_SRC_ALPHA:
return String("GL_SRC_ALPHA");
case IGL10::_GL_ONE_MINUS_SRC_ALPHA:
return String("GL_ONE_MINUS_SRC_ALPHA");
case IGL10::_GL_DST_ALPHA:
return String("GL_DST_ALPHA");
case IGL10::_GL_ONE_MINUS_DST_ALPHA:
return String("GL_ONE_MINUS_DST_ALPHA");
case IGL10::_GL_SRC_ALPHA_SATURATE:
return String("GL_SRC_ALPHA_SATURATE");
default:
return GetHex(factor);
}
}
String GLLogWrapper::GetShadeModel(
/* [in] */ Int32 model)
{
switch(model) {
case IGL10::_GL_FLAT:
return String("GL_FLAT");
case IGL10::_GL_SMOOTH:
return String("GL_SMOOTH");
default:
return GetHex(model);
}
}
String GLLogWrapper::GetTextureTarget(
/* [in] */ Int32 target)
{
switch (target) {
case IGL10::_GL_TEXTURE_2D:
return String("GL_TEXTURE_2D");
default:
return GetHex(target);
}
}
String GLLogWrapper::GetTextureEnvTarget(
/* [in] */ Int32 target)
{
switch (target) {
case IGL10::_GL_TEXTURE_ENV:
return String("GL_TEXTURE_ENV");
default:
return GetHex(target);
}
}
String GLLogWrapper::GetTextureEnvPName(
/* [in] */ Int32 pname)
{
switch (pname) {
case IGL10::_GL_TEXTURE_ENV_MODE:
return String("GL_TEXTURE_ENV_MODE");
case IGL10::_GL_TEXTURE_ENV_COLOR:
return String("GL_TEXTURE_ENV_COLOR");
default:
return GetHex(pname);
}
}
Int32 GLLogWrapper::GetTextureEnvParamCount(
/* [in] */ Int32 pname)
{
switch (pname) {
case IGL10::_GL_TEXTURE_ENV_MODE:
return 1;
case IGL10::_GL_TEXTURE_ENV_COLOR:
return 4;
default:
return 0;
}
}
String GLLogWrapper::GetTextureEnvParamName(
/* [in] */ Float param)
{
Int32 iparam = (Int32) param;
if (param == (Float) iparam) {
switch (iparam) {
case IGL10::_GL_REPLACE:
return String("GL_REPLACE");
case IGL10::_GL_MODULATE:
return String("GL_MODULATE");
case IGL10::_GL_DECAL:
return String("GL_DECAL");
case IGL10::_GL_BLEND:
return String("GL_BLEND");
case IGL10::_GL_ADD:
return String("GL_ADD");
case IGL11::_GL_COMBINE:
return String("GL_COMBINE");
default:
return GetHex(iparam);
}
}
return StringUtils::ToString(param);;
}
String GLLogWrapper::GetMatrixMode(
/* [in] */ Int32 matrixMode)
{
switch (matrixMode) {
case IGL10::_GL_MODELVIEW:
return String("GL_MODELVIEW");
case IGL10::_GL_PROJECTION:
return String("GL_PROJECTION");
case IGL10::_GL_TEXTURE:
return String("GL_TEXTURE");
default:
return GetHex(matrixMode);
}
}
String GLLogWrapper::GetClientState(
/* [in] */ Int32 clientState)
{
switch (clientState) {
case IGL10::_GL_COLOR_ARRAY:
return String("GL_COLOR_ARRAY");
case IGL10::_GL_VERTEX_ARRAY:
return String("GL_VERTEX_ARRAY");
case IGL10::_GL_NORMAL_ARRAY:
return String("GL_NORMAL_ARRAY");
case IGL10::_GL_TEXTURE_COORD_ARRAY:
return String("GL_TEXTURE_COORD_ARRAY");
default:
return GetHex(clientState);
}
}
String GLLogWrapper::GetCap(
/* [in] */ Int32 cap)
{
switch (cap) {
case IGL10::_GL_FOG:
return String("GL_FOG");
case IGL10::_GL_LIGHTING:
return String("GL_LIGHTING");
case IGL10::_GL_TEXTURE_2D:
return String("GL_TEXTURE_2D");
case IGL10::_GL_CULL_FACE:
return String("GL_CULL_FACE");
case IGL10::_GL_ALPHA_TEST:
return String("GL_ALPHA_TEST");
case IGL10::_GL_BLEND:
return String("GL_BLEND");
case IGL10::_GL_COLOR_LOGIC_OP:
return String("GL_COLOR_LOGIC_OP");
case IGL10::_GL_DITHER:
return String("GL_DITHER");
case IGL10::_GL_STENCIL_TEST:
return String("GL_STENCIL_TEST");
case IGL10::_GL_DEPTH_TEST:
return String("GL_DEPTH_TEST");
case IGL10::_GL_LIGHT0:
return String("GL_LIGHT0");
case IGL10::_GL_LIGHT1:
return String("GL_LIGHT1");
case IGL10::_GL_LIGHT2:
return String("GL_LIGHT2");
case IGL10::_GL_LIGHT3:
return String("GL_LIGHT3");
case IGL10::_GL_LIGHT4:
return String("GL_LIGHT4");
case IGL10::_GL_LIGHT5:
return String("GL_LIGHT5");
case IGL10::_GL_LIGHT6:
return String("GL_LIGHT6");
case IGL10::_GL_LIGHT7:
return String("GL_LIGHT7");
case IGL10::_GL_POINT_SMOOTH:
return String("GL_POINT_SMOOTH");
case IGL10::_GL_LINE_SMOOTH:
return String("GL_LINE_SMOOTH");
case IGL10::_GL_COLOR_MATERIAL:
return String("GL_COLOR_MATERIAL");
case IGL10::_GL_NORMALIZE:
return String("GL_NORMALIZE");
case IGL10::_GL_RESCALE_NORMAL:
return String("GL_RESCALE_NORMAL");
case IGL10::_GL_VERTEX_ARRAY:
return String("GL_VERTEX_ARRAY");
case IGL10::_GL_NORMAL_ARRAY:
return String("GL_NORMAL_ARRAY");
case IGL10::_GL_COLOR_ARRAY:
return String("GL_COLOR_ARRAY");
case IGL10::_GL_TEXTURE_COORD_ARRAY:
return String("GL_TEXTURE_COORD_ARRAY");
case IGL10::_GL_MULTISAMPLE:
return String("GL_MULTISAMPLE");
case IGL10::_GL_SAMPLE_ALPHA_TO_COVERAGE:
return String("GL_SAMPLE_ALPHA_TO_COVERAGE");
case IGL10::_GL_SAMPLE_ALPHA_TO_ONE:
return String("GL_SAMPLE_ALPHA_TO_ONE");
case IGL10::_GL_SAMPLE_COVERAGE:
return String("GL_SAMPLE_COVERAGE");
case IGL10::_GL_SCISSOR_TEST:
return String("GL_SCISSOR_TEST");
default:
return GetHex(cap);
}
}
String GLLogWrapper::GetTexturePName(
/* [in] */ Int32 pname)
{
switch (pname) {
case IGL10::_GL_TEXTURE_MAG_FILTER:
return String("GL_TEXTURE_MAG_FILTER");
case IGL10::_GL_TEXTURE_MIN_FILTER:
return String("GL_TEXTURE_MIN_FILTER");
case IGL10::_GL_TEXTURE_WRAP_S:
return String("GL_TEXTURE_WRAP_S");
case IGL10::_GL_TEXTURE_WRAP_T:
return String("GL_TEXTURE_WRAP_T");
case IGL11::_GL_GENERATE_MIPMAP:
return String("GL_GENERATE_MIPMAP");
case IGL11Ext::_GL_TEXTURE_CROP_RECT_OES:
return String("GL_TEXTURE_CROP_RECT_OES");
default:
return GetHex(pname);
}
}
String GLLogWrapper::GetTextureParamName(
/* [in] */ Float param)
{
Int32 iparam = (Int32) param;
if (param == (Float) iparam) {
switch (iparam) {
case IGL10::_GL_CLAMP_TO_EDGE:
return String("GL_CLAMP_TO_EDGE");
case IGL10::_GL_REPEAT:
return String("GL_REPEAT");
case IGL10::_GL_NEAREST:
return String("GL_NEAREST");
case IGL10::_GL_LINEAR:
return String("GL_LINEAR");
case IGL10::_GL_NEAREST_MIPMAP_NEAREST:
return String("GL_NEAREST_MIPMAP_NEAREST");
case IGL10::_GL_LINEAR_MIPMAP_NEAREST:
return String("GL_LINEAR_MIPMAP_NEAREST");
case IGL10::_GL_NEAREST_MIPMAP_LINEAR:
return String("GL_NEAREST_MIPMAP_LINEAR");
case IGL10::_GL_LINEAR_MIPMAP_LINEAR:
return String("GL_LINEAR_MIPMAP_LINEAR");
default:
return GetHex(iparam);
}
}
return StringUtils::ToString(param);
}
String GLLogWrapper::GetFogPName(
/* [in] */ Int32 pname)
{
switch (pname) {
case IGL10::_GL_FOG_DENSITY:
return String("GL_FOG_DENSITY");
case IGL10::_GL_FOG_START:
return String("GL_FOG_START");
case IGL10::_GL_FOG_END:
return String("GL_FOG_END");
case IGL10::_GL_FOG_MODE:
return String("GL_FOG_MODE");
case IGL10::_GL_FOG_COLOR:
return String("GL_FOG_COLOR");
default:
return GetHex(pname);
}
}
Int32 GLLogWrapper::GetFogParamCount(
/* [in] */ Int32 pname)
{
switch (pname) {
case IGL10::_GL_FOG_DENSITY:
return 1;
case IGL10::_GL_FOG_START:
return 1;
case IGL10::_GL_FOG_END:
return 1;
case IGL10::_GL_FOG_MODE:
return 1;
case IGL10::_GL_FOG_COLOR:
return 4;
default:
return 0;
}
}
String GLLogWrapper::GetBeginMode(
/* [in] */ Int32 mode)
{
switch (mode) {
case IGL10::_GL_POINTS:
return String("GL_POINTS");
case IGL10::_GL_LINES:
return String("GL_LINES");
case IGL10::_GL_LINE_LOOP:
return String("GL_LINE_LOOP");
case IGL10::_GL_LINE_STRIP:
return String("GL_LINE_STRIP");
case IGL10::_GL_TRIANGLES:
return String("GL_TRIANGLES");
case IGL10::_GL_TRIANGLE_STRIP:
return String("GL_TRIANGLE_STRIP");
case IGL10::_GL_TRIANGLE_FAN:
return String("GL_TRIANGLE_FAN");
default:
return GetHex(mode);
}
}
String GLLogWrapper::GetIndexType(
/* [in] */ Int32 type)
{
switch (type) {
case IGL10::_GL_UNSIGNED_SHORT:
return String("GL_UNSIGNED_SHORT");
case IGL10::_GL_UNSIGNED_BYTE:
return String("GL_UNSIGNED_BYTE");
default:
return GetHex(type);
}
}
String GLLogWrapper::GetIntegerStateName(
/* [in] */ Int32 pname)
{
switch (pname) {
case IGL10::_GL_ALPHA_BITS:
return String("GL_ALPHA_BITS");
case IGL10::_GL_ALIASED_LINE_WIDTH_RANGE:
return String("GL_ALIASED_LINE_WIDTH_RANGE");
case IGL10::_GL_ALIASED_POINT_SIZE_RANGE:
return String("GL_ALIASED_POINT_SIZE_RANGE");
case IGL10::_GL_BLUE_BITS:
return String("GL_BLUE_BITS");
case IGL10::_GL_COMPRESSED_TEXTURE_FORMATS:
return String("GL_COMPRESSED_TEXTURE_FORMATS");
case IGL10::_GL_DEPTH_BITS:
return String("GL_DEPTH_BITS");
case IGL10::_GL_GREEN_BITS:
return String("GL_GREEN_BITS");
case IGL10::_GL_MAX_ELEMENTS_INDICES:
return String("GL_MAX_ELEMENTS_INDICES");
case IGL10::_GL_MAX_ELEMENTS_VERTICES:
return String("GL_MAX_ELEMENTS_VERTICES");
case IGL10::_GL_MAX_LIGHTS:
return String("GL_MAX_LIGHTS");
case IGL10::_GL_MAX_TEXTURE_SIZE:
return String("GL_MAX_TEXTURE_SIZE");
case IGL10::_GL_MAX_VIEWPORT_DIMS:
return String("GL_MAX_VIEWPORT_DIMS");
case IGL10::_GL_MAX_MODELVIEW_STACK_DEPTH:
return String("GL_MAX_MODELVIEW_STACK_DEPTH");
case IGL10::_GL_MAX_PROJECTION_STACK_DEPTH:
return String("GL_MAX_PROJECTION_STACK_DEPTH");
case IGL10::_GL_MAX_TEXTURE_STACK_DEPTH:
return String("GL_MAX_TEXTURE_STACK_DEPTH");
case IGL10::_GL_MAX_TEXTURE_UNITS:
return String("GL_MAX_TEXTURE_UNITS");
case IGL10::_GL_NUM_COMPRESSED_TEXTURE_FORMATS:
return String("GL_NUM_COMPRESSED_TEXTURE_FORMATS");
case IGL10::_GL_RED_BITS:
return String("GL_RED_BITS");
case IGL10::_GL_SMOOTH_LINE_WIDTH_RANGE:
return String("GL_SMOOTH_LINE_WIDTH_RANGE");
case IGL10::_GL_SMOOTH_POINT_SIZE_RANGE:
return String("GL_SMOOTH_POINT_SIZE_RANGE");
case IGL10::_GL_STENCIL_BITS:
return String("GL_STENCIL_BITS");
case IGL10::_GL_SUBPIXEL_BITS:
return String("GL_SUBPIXEL_BITS");
case IGL11::_GL_MODELVIEW_MATRIX_FLOAT_AS_INT_BITS_OES:
return String("GL_MODELVIEW_MATRIX_FLOAT_AS_INT_BITS_OES");
case IGL11::_GL_PROJECTION_MATRIX_FLOAT_AS_INT_BITS_OES:
return String("GL_PROJECTION_MATRIX_FLOAT_AS_INT_BITS_OES");
case IGL11::_GL_TEXTURE_MATRIX_FLOAT_AS_INT_BITS_OES:
return String("GL_TEXTURE_MATRIX_FLOAT_AS_INT_BITS_OES");
default:
return GetHex(pname);
}
}
Int32 GLLogWrapper::GetIntegerStateSize(
/* [in] */ Int32 pname)
{
switch (pname) {
case IGL10::_GL_ALPHA_BITS:
return 1;
case IGL10::_GL_ALIASED_LINE_WIDTH_RANGE:
return 2;
case IGL10::_GL_ALIASED_POINT_SIZE_RANGE:
return 2;
case IGL10::_GL_BLUE_BITS:
return 1;
case IGL10::_GL_COMPRESSED_TEXTURE_FORMATS:
// Have to ask the implementation for the size
{
AutoPtr<ArrayOf<Int32> > buffer = ArrayOf<Int32>::Alloc(1);
IGL::Probe(mgl)->GlGetIntegerv(IGL10::_GL_NUM_COMPRESSED_TEXTURE_FORMATS, buffer, 0);
return (*buffer)[0];
}
case IGL10::_GL_DEPTH_BITS:
return 1;
case IGL10::_GL_GREEN_BITS:
return 1;
case IGL10::_GL_MAX_ELEMENTS_INDICES:
return 1;
case IGL10::_GL_MAX_ELEMENTS_VERTICES:
return 1;
case IGL10::_GL_MAX_LIGHTS:
return 1;
case IGL10::_GL_MAX_TEXTURE_SIZE:
return 1;
case IGL10::_GL_MAX_VIEWPORT_DIMS:
return 2;
case IGL10::_GL_MAX_MODELVIEW_STACK_DEPTH:
return 1;
case IGL10::_GL_MAX_PROJECTION_STACK_DEPTH:
return 1;
case IGL10::_GL_MAX_TEXTURE_STACK_DEPTH:
return 1;
case IGL10::_GL_MAX_TEXTURE_UNITS:
return 1;
case IGL10::_GL_NUM_COMPRESSED_TEXTURE_FORMATS:
return 1;
case IGL10::_GL_RED_BITS:
return 1;
case IGL10::_GL_SMOOTH_LINE_WIDTH_RANGE:
return 2;
case IGL10::_GL_SMOOTH_POINT_SIZE_RANGE:
return 2;
case IGL10::_GL_STENCIL_BITS:
return 1;
case IGL10::_GL_SUBPIXEL_BITS:
return 1;
case IGL11::_GL_MODELVIEW_MATRIX_FLOAT_AS_INT_BITS_OES:
case IGL11::_GL_PROJECTION_MATRIX_FLOAT_AS_INT_BITS_OES:
case IGL11::_GL_TEXTURE_MATRIX_FLOAT_AS_INT_BITS_OES:
return 16;
default:
return 0;
}
}
Int32 GLLogWrapper::GetIntegerStateFormat(
/* [in] */ Int32 pname)
{
switch (pname) {
case IGL11::_GL_MODELVIEW_MATRIX_FLOAT_AS_INT_BITS_OES:
case IGL11::_GL_PROJECTION_MATRIX_FLOAT_AS_INT_BITS_OES:
case IGL11::_GL_TEXTURE_MATRIX_FLOAT_AS_INT_BITS_OES:
return FORMAT_FLOAT;
default:
return FORMAT_INT;
}
}
String GLLogWrapper::GetHintTarget(
/* [in] */ Int32 target)
{
switch (target) {
case IGL10::_GL_FOG_HINT:
return String("GL_FOG_HINT");
case IGL10::_GL_LINE_SMOOTH_HINT:
return String("GL_LINE_SMOOTH_HINT");
case IGL10::_GL_PERSPECTIVE_CORRECTION_HINT:
return String("GL_PERSPECTIVE_CORRECTION_HINT");
case IGL10::_GL_POINT_SMOOTH_HINT:
return String("GL_POINT_SMOOTH_HINT");
case IGL10::_GL_POLYGON_SMOOTH_HINT:
return String("GL_POLYGON_SMOOTH_HINT");
case IGL11::_GL_GENERATE_MIPMAP_HINT:
return String("GL_GENERATE_MIPMAP_HINT");
default:
return GetHex(target);
}
}
String GLLogWrapper::GetHintMode(
/* [in] */ Int32 mode)
{
switch (mode) {
case IGL10::_GL_FASTEST:
return String("GL_FASTEST");
case IGL10::_GL_NICEST:
return String("GL_NICEST");
case IGL10::_GL_DONT_CARE:
return String("GL_DONT_CARE");
default:
return GetHex(mode);
}
}
String GLLogWrapper::GetFaceName(
/* [in] */ Int32 face)
{
switch (face) {
case IGL10::_GL_FRONT_AND_BACK:
return String("GL_FRONT_AND_BACK");
default:
return GetHex(face);
}
}
String GLLogWrapper::GetMaterialPName(
/* [in] */ Int32 pname)
{
switch (pname) {
case IGL10::_GL_AMBIENT:
return String("GL_AMBIENT");
case IGL10::_GL_DIFFUSE:
return String("GL_DIFFUSE");
case IGL10::_GL_SPECULAR:
return String("GL_SPECULAR");
case IGL10::_GL_EMISSION:
return String("GL_EMISSION");
case IGL10::_GL_SHININESS:
return String("GL_SHININESS");
case IGL10::_GL_AMBIENT_AND_DIFFUSE:
return String("GL_AMBIENT_AND_DIFFUSE");
default:
return GetHex(pname);
}
}
Int32 GLLogWrapper::GetMaterialParamCount(
/* [in] */ Int32 pname)
{
switch (pname) {
case IGL10::_GL_AMBIENT:
return 4;
case IGL10::_GL_DIFFUSE:
return 4;
case IGL10::_GL_SPECULAR:
return 4;
case IGL10::_GL_EMISSION:
return 4;
case IGL10::_GL_SHININESS:
return 1;
case IGL10::_GL_AMBIENT_AND_DIFFUSE:
return 4;
default:
return 0;
}
}
String GLLogWrapper::GetLightName(
/* [in] */ Int32 light)
{
if (light >= IGL10::_GL_LIGHT0 && light <= IGL10::_GL_LIGHT7) {
return String("GL_LIGHT") + StringUtils::ToString(light);
}
return GetHex(light);
}
String GLLogWrapper::GetLightPName(
/* [in] */ Int32 pname)
{
switch (pname) {
case IGL10::_GL_AMBIENT:
return String("GL_AMBIENT");
case IGL10::_GL_DIFFUSE:
return String("GL_DIFFUSE");
case IGL10::_GL_SPECULAR:
return String("GL_SPECULAR");
case IGL10::_GL_POSITION:
return String("GL_POSITION");
case IGL10::_GL_SPOT_DIRECTION:
return String("GL_SPOT_DIRECTION");
case IGL10::_GL_SPOT_EXPONENT:
return String("GL_SPOT_EXPONENT");
case IGL10::_GL_SPOT_CUTOFF:
return String("GL_SPOT_CUTOFF");
case IGL10::_GL_CONSTANT_ATTENUATION:
return String("GL_CONSTANT_ATTENUATION");
case IGL10::_GL_LINEAR_ATTENUATION:
return String("GL_LINEAR_ATTENUATION");
case IGL10::_GL_QUADRATIC_ATTENUATION:
return String("GL_QUADRATIC_ATTENUATION");
default:
return GetHex(pname);
}
}
Int32 GLLogWrapper::GetLightParamCount(
/* [in] */ Int32 pname)
{
switch (pname) {
case IGL10::_GL_AMBIENT:
return 4;
case IGL10::_GL_DIFFUSE:
return 4;
case IGL10::_GL_SPECULAR:
return 4;
case IGL10::_GL_POSITION:
return 4;
case IGL10::_GL_SPOT_DIRECTION:
return 3;
case IGL10::_GL_SPOT_EXPONENT:
return 1;
case IGL10::_GL_SPOT_CUTOFF:
return 1;
case IGL10::_GL_CONSTANT_ATTENUATION:
return 1;
case IGL10::_GL_LINEAR_ATTENUATION:
return 1;
case IGL10::_GL_QUADRATIC_ATTENUATION:
return 1;
default:
return 0;
}
}
String GLLogWrapper::GetLightModelPName(
/* [in] */ Int32 pname)
{
switch (pname) {
case IGL10::_GL_LIGHT_MODEL_AMBIENT:
return String("GL_LIGHT_MODEL_AMBIENT");
case IGL10::_GL_LIGHT_MODEL_TWO_SIDE:
return String("GL_LIGHT_MODEL_TWO_SIDE");
default:
return GetHex(pname);
}
}
Int32 GLLogWrapper::GetLightModelParamCount(
/* [in] */ Int32 pname)
{
switch (pname) {
case IGL10::_GL_LIGHT_MODEL_AMBIENT:
return 4;
case IGL10::_GL_LIGHT_MODEL_TWO_SIDE:
return 1;
default:
return 0;
}
}
String GLLogWrapper::GetPointerTypeName(
/* [in] */ Int32 type)
{
switch (type) {
case IGL10::_GL_BYTE:
return String("GL_BYTE");
case IGL10::_GL_UNSIGNED_BYTE:
return String("GL_UNSIGNED_BYTE");
case IGL10::_GL_SHORT:
return String("GL_SHORT");
case IGL10::_GL_FIXED:
return String("GL_FIXED");
case IGL10::_GL_FLOAT:
return String("GL_FLOAT");
default:
return GetHex(type);
}
}
ECode GLLogWrapper::ToByteBuffer(
/* [in] */ Int32 count,
/* [in] */ IBuffer* input,
/* [in] */ IByteBuffer** rBuf)
{
AutoPtr<IByteBuffer> result;
Int32 byteCount = count;
Boolean convertWholeBuffer = (count < 0);
AutoPtr<IByteBufferHelper> byteHelper;
CByteBufferHelper::AcquireSingleton((IByteBufferHelper**)&byteHelper);
if (IByteBuffer::Probe(input)) {
AutoPtr<IByteBuffer> input2 = IByteBuffer::Probe(input);
Int32 position;
input->GetPosition(&position);
if (convertWholeBuffer) {
Int32 limit;
input->GetLimit(&limit);
byteCount = limit - position;
}
byteHelper->Allocate(byteCount, (IByteBuffer**)&result);
ByteOrder order;
input2->GetOrder(&order);
result->SetOrder(order);
for (Int32 i = 0; i < byteCount; i++) {
Byte v;
input2->Get(&v);
result->Put(v);
}
input->SetPosition(position);
} else if (ICharBuffer::Probe(input)) {
AutoPtr<ICharBuffer> input2 = ICharBuffer::Probe(input);
Int32 position;
input->GetPosition(&position);
if (convertWholeBuffer) {
Int32 limit;
input->GetLimit(&limit);
byteCount = (limit - position) * 4;
}
byteHelper->Allocate(byteCount, (IByteBuffer**)&result);
ByteOrder order;
input2->GetOrder(&order);
result->SetOrder(order);
AutoPtr<ICharBuffer> result2;
result->AsCharBuffer((ICharBuffer**)&result2);
for (Int32 i = 0; i < byteCount / 4; i++) {
Char32 v;
input2->Get(&v);
result2->Put(v);
}
input->SetPosition(position);
} else if (IInt16Buffer::Probe(input)) {
AutoPtr<IInt16Buffer> input2 = IInt16Buffer::Probe(input);
Int32 position;
input->GetPosition(&position);
if (convertWholeBuffer) {
Int32 limit;
input->GetLimit(&limit);
byteCount = (limit - position) * 2;
}
byteHelper->Allocate(byteCount, (IByteBuffer**)&result);
ByteOrder order;
input2->GetOrder(&order);
result->SetOrder(order);
AutoPtr<IInt16Buffer> result2;
result->AsInt16Buffer((IInt16Buffer**)&result2);
for (Int32 i = 0; i < byteCount / 2; i++) {
Int16 v;
input2->Get(&v);
result2->Put(v);
}
input->SetPosition(position);
} else if (IInt32Buffer::Probe(input)) {
AutoPtr<IInt32Buffer> input2 = IInt32Buffer::Probe(input);
Int32 position;
input->GetPosition(&position);
if (convertWholeBuffer) {
Int32 limit;
input->GetLimit(&limit);
byteCount = (limit - position) * 4;
}
byteHelper->Allocate(byteCount, (IByteBuffer**)&result);
ByteOrder order;
input2->GetOrder(&order);
result->SetOrder(order);
AutoPtr<IInt32Buffer> result2;
result->AsInt32Buffer((IInt32Buffer**)&result2);
for (Int32 i = 0; i < byteCount / 4; i++) {
Int32 v;
input2->Get(&v);
result2->Put(v);
}
input->SetPosition(position);
} else if (IFloatBuffer::Probe(input)) {
AutoPtr<IFloatBuffer> input2 = IFloatBuffer::Probe(input);
Int32 position;
input->GetPosition(&position);
if (convertWholeBuffer) {
Int32 limit;
input->GetLimit(&limit);
byteCount = (limit - position) * 4;
}
byteHelper->Allocate(byteCount, (IByteBuffer**)&result);
ByteOrder order;
input2->GetOrder(&order);
result->SetOrder(order);
AutoPtr<IFloatBuffer> result2;
result->AsFloatBuffer((IFloatBuffer**)&result2);
for (Int32 i = 0; i < byteCount / 4; i++) {
Float v;
input2->Get(&v);
result2->Put(v);
}
input->SetPosition(position);
} else if (IDoubleBuffer::Probe(input)) {
AutoPtr<IDoubleBuffer> input2 = IDoubleBuffer::Probe(input);
Int32 position;
input->GetPosition(&position);
if (convertWholeBuffer) {
Int32 limit;
input->GetLimit(&limit);
byteCount = (limit - position) * 8;
}
byteHelper->Allocate(byteCount, (IByteBuffer**)&result);
ByteOrder order;
input2->GetOrder(&order);
result->SetOrder(order);
AutoPtr<IDoubleBuffer> result2;
result->AsDoubleBuffer((IDoubleBuffer**)&result2);
for (Int32 i = 0; i < byteCount / 8; i++) {
Double v;
input2->Get(&v);
result2->Put(v);
}
input->SetPosition(position);
} else if (IInt64Buffer::Probe(input)) {
AutoPtr<IInt64Buffer> input2 = IInt64Buffer::Probe(input);
Int32 position;
input->GetPosition(&position);
if (convertWholeBuffer) {
Int32 limit;
input->GetLimit(&limit);
byteCount = (limit - position) * 8;
}
byteHelper->Allocate(byteCount, (IByteBuffer**)&result);
ByteOrder order;
input2->GetOrder(&order);
result->SetOrder(order);
AutoPtr<IInt64Buffer> result2;
result->AsInt64Buffer((IInt64Buffer**)&result2);
for (Int32 i = 0; i < byteCount / 8; i++) {
Int64 v;
input2->Get(&v);
result2->Put(v);
}
input->SetPosition(position);
} else {
SLOGGERE("GLLogWrapper", "Unimplemented Buffer subclass.")
return E_RUNTIME_EXCEPTION;
}
IBuffer::Probe(result)->Rewind();
// The OpenGL API will interpret the result in hardware byte order,
// so we better do that as well:
AutoPtr<IByteOrderHelper> orderHelper;
CByteOrderHelper::AcquireSingleton((IByteOrderHelper**)&orderHelper);
ByteOrder nativeOrder;
orderHelper->GetNativeOrder(&nativeOrder);
result->SetOrder(nativeOrder);
*rBuf = result;
REFCOUNT_ADD(*rBuf)
return NOERROR;
}
AutoPtr<ArrayOf<Char32> > GLLogWrapper::ToCharIndices(
/* [in] */ Int32 count,
/* [in] */ Int32 type,
/* [in] */ IBuffer* indices)
{
AutoPtr<ArrayOf<Char32> > result = ArrayOf<Char32>::Alloc(count);
switch (type) {
case IGL10::_GL_UNSIGNED_BYTE: {
AutoPtr<IByteBuffer> byteBuffer;
ToByteBuffer(count, indices, (IByteBuffer**)&byteBuffer);
AutoPtr<ArrayOf<Byte> > array;
byteBuffer->GetArray((ArrayOf<Byte>**)&array);
Int32 offset;
IBuffer::Probe(byteBuffer)->GetArrayOffset(&offset);
for (Int32 i = 0; i < count; i++) {
(*result)[i] = (Char32) (0xff & (*array)[offset + i]);
}
}
break;
case IGL10::_GL_UNSIGNED_SHORT: {
AutoPtr<ICharBuffer> charBuffer;
if (ICharBuffer::Probe(indices) != NULL) {
charBuffer = ICharBuffer::Probe(indices);
} else {
AutoPtr<IByteBuffer> byteBuffer;
ToByteBuffer(count * 2, indices, (IByteBuffer**)&byteBuffer);
byteBuffer->AsCharBuffer((ICharBuffer**)&charBuffer);
}
Int32 oldPosition;
IBuffer::Probe(charBuffer)->GetPosition(&oldPosition);
IBuffer::Probe(charBuffer)->SetPosition(0);
charBuffer->Get(result);
IBuffer::Probe(charBuffer)->SetPosition(oldPosition);
}
break;
default:
// Don't throw an exception, because we don't want logging to
// change the behavior.
break;
}
return result;
}
ECode GLLogWrapper::DoArrayElement(
/* [in] */ StringBuilder& builder,
/* [in] */ Boolean enabled,
/* [in] */ const String& name,
/* [in] */ PointerInfo* pointer,
/* [in] */ Int32 index)
{
if (!enabled) {
return NOERROR;
}
builder += " ";
builder += name + ":{";
if (pointer == NULL || pointer->mTempByteBuffer == NULL ) {
builder += "undefined }";
return NOERROR;
}
if (pointer->mStride < 0) {
builder += "invalid stride";
return NOERROR;
}
Int32 stride = pointer->GetStride();
AutoPtr<IByteBuffer> byteBuffer = pointer->mTempByteBuffer;
Int32 size = pointer->mSize;
Int32 type = pointer->mType;
Int32 sizeofType = pointer->Sizeof(type);
Int32 byteOffset = stride * index;
for (Int32 i = 0; i < size; i++) {
if (i > 0) {
builder += ", ";
}
switch (type) {
case IGL10::_GL_BYTE: {
Byte d;
byteBuffer->Get(byteOffset, &d);
builder += d;
}
break;
case IGL10::_GL_UNSIGNED_BYTE: {
Byte d;
byteBuffer->Get(byteOffset, &d);
builder += (0xff & d);
}
break;
case IGL10::_GL_SHORT: {
AutoPtr<IInt16Buffer> shortBuffer;
byteBuffer->AsInt16Buffer((IInt16Buffer**)&shortBuffer);
Int16 d;
shortBuffer->Get(byteOffset / 2, &d);
builder += d;
}
break;
case IGL10::_GL_FIXED: {
AutoPtr<IInt32Buffer> intBuffer;
byteBuffer->AsInt32Buffer((IInt32Buffer**)&intBuffer);
Int32 d;
intBuffer->Get(byteOffset / 4, &d);
builder += d;
}
break;
case IGL10::_GL_FLOAT: {
AutoPtr<IFloatBuffer> floatBuffer;
byteBuffer->AsFloatBuffer((IFloatBuffer**)&floatBuffer);
Float d;
floatBuffer->Get(byteOffset / 4, &d);
builder += d;
}
break;
default:
builder += "?";
break;
}
byteOffset += sizeofType;
}
builder += "}";
return NOERROR;
}
ECode GLLogWrapper::DoElement(
/* [in] */ StringBuilder& builder,
/* [in] */ Int32 ordinal,
/* [in] */ Int32 vertexIndex)
{
builder += " [";
builder += ordinal;
builder += " : ";
builder += vertexIndex;
builder += "] =";
DoArrayElement(builder, mVertexArrayEnabled, String("v"), mVertexPointer,
vertexIndex);
DoArrayElement(builder, mNormalArrayEnabled, String("n"), mNormalPointer,
vertexIndex);
DoArrayElement(builder, mColorArrayEnabled, String("c"), mColorPointer,
vertexIndex);
DoArrayElement(builder, mTextureCoordArrayEnabled, String("t"),
mTexCoordPointer, vertexIndex);
builder += "\n";
// Vertex
// Normal
// Color
// TexCoord
return NOERROR;
}
ECode GLLogWrapper::BindArrays()
{
if (mColorArrayEnabled)
mColorPointer->BindByteBuffer();
if (mNormalArrayEnabled)
mNormalPointer->BindByteBuffer();
if (mTextureCoordArrayEnabled)
mTexCoordPointer->BindByteBuffer();
if (mVertexArrayEnabled)
mVertexPointer->BindByteBuffer();
return NOERROR;
}
ECode GLLogWrapper::UnbindArrays()
{
if (mColorArrayEnabled)
mColorPointer->UnbindByteBuffer();
if (mNormalArrayEnabled)
mNormalPointer->UnbindByteBuffer();
if (mTextureCoordArrayEnabled)
mTexCoordPointer->UnbindByteBuffer();
if (mVertexArrayEnabled)
mVertexPointer->UnbindByteBuffer();
return NOERROR;
}
ECode GLLogWrapper::StartLogIndices()
{
mStringBuilder += "\n";
BindArrays();
return NOERROR;
}
ECode GLLogWrapper::EndLogIndices()
{
Log(mStringBuilder.ToString());
UnbindArrays();
return NOERROR;
}
ECode GLLogWrapper::GlActiveTexture(
/* [in] */ Int32 texture)
{
Begin(String("glActiveTexture"));
Arg(String("texture"), texture);
End();
ECode ec = mgl->GlActiveTexture(texture);
CheckError();
return ec;
}
ECode GLLogWrapper::GlAlphaFunc(
/* [in] */ Int32 func,
/* [in] */ Float ref)
{
Begin(String("glAlphaFunc"));
Arg(String("func"), func);
Arg(String("ref"), ref);
End();
ECode ec = mgl->GlAlphaFunc(func, ref);
CheckError();
return ec;
}
ECode GLLogWrapper::GlAlphaFuncx(
/* [in] */ Int32 func,
/* [in] */ Int32 ref)
{
Begin(String("glAlphaFuncx"));
Arg(String("func"), func);
Arg(String("ref"), ref);
End();
ECode ec = mgl->GlAlphaFuncx(func, ref);
CheckError();
return ec;
}
ECode GLLogWrapper::GlBlendFunc(
/* [in] */ Int32 sfactor,
/* [in] */ Int32 dfactor)
{
Begin(String("GlBlendFunc"));
Arg(String("sfactor"), GetFactor(sfactor));
Arg(String("dfactor"), GetFactor(dfactor));
End();
ECode ec = mgl->GlBlendFunc(sfactor, dfactor);
CheckError();
return ec;
}
ECode GLLogWrapper::GlClear(
/* [in] */ Int32 mask)
{
Begin(String("glClear"));
Arg(String("mask"), GetClearBufferMask(mask));
End();
ECode ec = mgl->GlClear(mask);
CheckError();
return ec;
}
ECode GLLogWrapper::GlClearColor(
/* [in] */ Float red,
/* [in] */ Float green,
/* [in] */ Float blue,
/* [in] */ Float alpha)
{
Begin(String("glClearColor"));
Arg(String("red"), red);
Arg(String("green"), green);
Arg(String("blue"), blue);
Arg(String("alpha"), alpha);
End();
ECode ec = mgl->GlClearColor(red, green, blue, alpha);
CheckError();
return ec;
}
ECode GLLogWrapper::GlClearColorx(
/* [in] */ Int32 red,
/* [in] */ Int32 green,
/* [in] */ Int32 blue,
/* [in] */ Int32 alpha)
{
Begin(String("glClearColor"));
Arg(String("red"), red);
Arg(String("green"), green);
Arg(String("blue"), blue);
Arg(String("alpha"), alpha);
End();
ECode ec = mgl->GlClearColorx(red, green, blue, alpha);
CheckError();
return ec;
}
ECode GLLogWrapper::GlClearDepthf(
/* [in] */ Float depth)
{
Begin(String("glClearDepthf"));
Arg(String("depth"), depth);
End();
ECode ec = mgl->GlClearDepthf(depth);
CheckError();
return ec;
}
ECode GLLogWrapper::GlClearDepthx(
/* [in] */ Int32 depth)
{
Begin(String("glClearDepthx"));
Arg(String("depth"), depth);
End();
ECode ec = mgl->GlClearDepthx(depth);
CheckError();
return ec;
}
ECode GLLogWrapper::GlClearStencil(
/* [in] */ Int32 s)
{
Begin(String("glClearStencil"));
Arg(String("s"), s);
End();
ECode ec = mgl->GlClearStencil(s);
CheckError();
return ec;
}
ECode GLLogWrapper::GlClientActiveTexture(
/* [in] */ Int32 texture)
{
Begin(String("glClientActiveTexture"));
Arg(String("texture"), texture);
End();
ECode ec = mgl->GlClientActiveTexture(texture);
CheckError();
return ec;
}
ECode GLLogWrapper::GlColor4f(
/* [in] */ Float red,
/* [in] */ Float green,
/* [in] */ Float blue,
/* [in] */ Float alpha)
{
Begin(String("glColor4f"));
Arg(String("red"), red);
Arg(String("green"), green);
Arg(String("blue"), blue);
Arg(String("alpha"), alpha);
End();
ECode ec = mgl->GlColor4f(red, green, blue, alpha);
CheckError();
return ec;
}
ECode GLLogWrapper::GlColor4x(
/* [in] */ Int32 red,
/* [in] */ Int32 green,
/* [in] */ Int32 blue,
/* [in] */ Int32 alpha)
{
Begin(String("glColor4x"));
Arg(String("red"), red);
Arg(String("green"), green);
Arg(String("blue"), blue);
Arg(String("alpha"), alpha);
End();
ECode ec = mgl->GlColor4x(red, green, blue, alpha);
CheckError();
return ec;
}
ECode GLLogWrapper::GlColorMask(
/* [in] */ Boolean red,
/* [in] */ Boolean green,
/* [in] */ Boolean blue,
/* [in] */ Boolean alpha)
{
Begin(String("glColorMask"));
Arg(String("red"), red);
Arg(String("green"), green);
Arg(String("blue"), blue);
Arg(String("alpha"), alpha);
End();
ECode ec = mgl->GlColorMask(red, green, blue, alpha);
CheckError();
return ec;
}
ECode GLLogWrapper::GlColorPointer(
/* [in] */ Int32 size,
/* [in] */ Int32 type,
/* [in] */ Int32 stride,
/* [in] */ IBuffer* pointer)
{
Begin(String("glColorPointer"));
ArgPointer(size, type, stride, pointer);
End();
mColorPointer = new PointerInfo(size, type, stride, pointer, this);
ECode ec = mgl->GlColorPointer(size, type, stride, pointer);
CheckError();
return ec;
}
ECode GLLogWrapper::GlCompressedTexSubImage2D(
/* [in] */ Int32 target,
/* [in] */ Int32 level,
/* [in] */ Int32 xoffset,
/* [in] */ Int32 yoffset,
/* [in] */ Int32 width,
/* [in] */ Int32 height,
/* [in] */ Int32 format,
/* [in] */ Int32 imageSize,
/* [in] */ IBuffer* data)
{
Begin(String("glCompressedTexSubImage2D"));
Arg(String("target"), GetTextureTarget(target));
Arg(String("level"), level);
Arg(String("xoffset"), xoffset);
Arg(String("yoffset"), yoffset);
Arg(String("width"), width);
Arg(String("height"), height);
Arg(String("format"), format);
Arg(String("imageSize"), imageSize);
Arg(String("data"), ParamsToString(data));
End();
ECode ec = mgl->GlCompressedTexSubImage2D(target, level, xoffset, yoffset, width,
height, format, imageSize, data);
CheckError();
return ec;
}
ECode GLLogWrapper::GlCopyTexSubImage2D(
/* [in] */ Int32 target,
/* [in] */ Int32 level,
/* [in] */ Int32 xoffset,
/* [in] */ Int32 yoffset,
/* [in] */ Int32 x,
/* [in] */ Int32 y,
/* [in] */ Int32 width,
/* [in] */ Int32 height)
{
Begin(String("glCopyTexSubImage2D"));
Arg(String("target"), GetTextureTarget(target));
Arg(String("level"), level);
Arg(String("xoffset"), xoffset);
Arg(String("yoffset"), yoffset);
Arg(String("x"), x);
Arg(String("y"), y);
Arg(String("width"), width);
Arg(String("height"), height);
End();
ECode ec = mgl->GlCopyTexSubImage2D(target, level, xoffset, yoffset, x, y, width,
height);
CheckError();
return ec;
}
ECode GLLogWrapper::GlCullFace(
/* [in] */ Int32 mode)
{
Begin(String("glCullFace"));
Arg(String("mode"), mode);
End();
ECode ec = mgl->GlCullFace(mode);
CheckError();
return ec;
}
ECode GLLogWrapper::GlDeleteTextures(
/* [in] */ Int32 n,
/* [in] */ ArrayOf<Int32>* textures,
/* [in] */ Int32 offset)
{
Begin(String("glDeleteTextures"));
Arg(String("n"), n);
Arg(String("textures"), n, textures, offset);
Arg(String("offset"), offset);
End();
ECode ec = mgl->GlDeleteTextures(n, textures, offset);
CheckError();
return ec;
}
ECode GLLogWrapper::GlDeleteTextures(
/* [in] */ Int32 n,
/* [in] */ IInt32Buffer* textures)
{
Begin(String("GlDeleteTexturesEx"));
Arg(String("n"), n);
Arg(String("textures"), n, textures);
End();
ECode ec = mgl->GlDeleteTextures(n, textures);
CheckError();
return ec;
}
ECode GLLogWrapper::GlDepthFunc(
/* [in] */ Int32 func)
{
Begin(String("glDepthFunc"));
Arg(String("func"), func);
End();
ECode ec = mgl->GlDepthFunc(func);
CheckError();
return ec;
}
ECode GLLogWrapper::GlDepthMask(
/* [in] */ Boolean flag)
{
Begin(String("glDepthMask"));
Arg(String("flag"), flag);
End();
ECode ec = mgl->GlDepthMask(flag);
CheckError();
return ec;
}
ECode GLLogWrapper::GlDepthRangef(
/* [in] */ Float near,
/* [in] */ Float far)
{
Begin(String("glDepthRangef"));
Arg(String("near"), near);
Arg(String("far"), far);
End();
ECode ec = mgl->GlDepthRangef(near, far);
CheckError();
return ec;
}
ECode GLLogWrapper::GlDepthRangex(
/* [in] */ Int32 near,
/* [in] */ Int32 far)
{
Begin(String("glDepthRangex"));
Arg(String("near"), near);
Arg(String("far"), far);
End();
ECode ec = mgl->GlDepthRangex(near, far);
CheckError();
return ec;
}
ECode GLLogWrapper::GlDisable(
/* [in] */ Int32 cap)
{
Begin(String("glDisable"));
Arg(String("cap"), GetCap(cap));
End();
ECode ec = mgl->GlDisable(cap);
CheckError();
return ec;
}
ECode GLLogWrapper::GlDisableClientState(
/* [in] */ Int32 array)
{
Begin(String("glDisableClientState"));
Arg(String("array"), GetClientState(array));
End();
switch (array) {
case IGL10::_GL_COLOR_ARRAY:
mColorArrayEnabled = FALSE;
break;
case IGL10::_GL_NORMAL_ARRAY:
mNormalArrayEnabled = FALSE;
break;
case IGL10::_GL_TEXTURE_COORD_ARRAY:
mTextureCoordArrayEnabled = FALSE;
break;
case IGL10::_GL_VERTEX_ARRAY:
mVertexArrayEnabled = FALSE;
break;
}
ECode ec = mgl->GlDisableClientState(array);
CheckError();
return ec;
}
ECode GLLogWrapper::GlDrawArrays(
/* [in] */ Int32 mode,
/* [in] */ Int32 first,
/* [in] */ Int32 count)
{
Begin(String("glDrawArrays"));
Arg(String("mode"), mode);
Arg(String("first"), first);
Arg(String("count"), count);
StartLogIndices();
for (int i = 0; i < count; i++) {
DoElement(mStringBuilder, i, first + i);
}
EndLogIndices();
End();
ECode ec = mgl->GlDrawArrays(mode, first, count);
CheckError();
return ec;
}
ECode GLLogWrapper::GlDrawElements(
/* [in] */ Int32 mode,
/* [in] */ Int32 count,
/* [in] */ Int32 type,
/* [in] */ IBuffer* indices)
{
Begin(String("glDrawElements"));
Arg(String("mode"), GetBeginMode(mode));
Arg(String("count"), count);
Arg(String("type"), GetIndexType(type));
AutoPtr<ArrayOf<Char32> > indexArray = ToCharIndices(count, type, indices);
Int32 indexArrayLength = indexArray->GetLength();
StartLogIndices();
for (int i = 0; i < indexArrayLength; i++) {
DoElement(mStringBuilder, i, (*indexArray)[i]);
}
EndLogIndices();
End();
ECode ec = mgl->GlDrawElements(mode, count, type, indices);
CheckError();
return ec;
}
ECode GLLogWrapper::GlFinish()
{
Begin(String("glFinish"));
End();
ECode ec = mgl->GlFinish();
CheckError();
return ec;
}
ECode GLLogWrapper::GlFlush()
{
Begin(String("glFlush"));
End();
ECode ec = mgl->GlFlush();
CheckError();
return ec;
}
ECode GLLogWrapper::GlFogf(
/* [in] */ Int32 pname,
/* [in] */ Float param)
{
Begin(String("glFogf"));
Arg(String("pname"), pname);
Arg(String("param"), param);
End();
ECode ec = mgl->GlFogf(pname, param);
CheckError();
return ec;
}
ECode GLLogWrapper::GlFogfv(
/* [in] */ Int32 pname,
/* [in] */ ArrayOf<Float>* params,
/* [in] */ Int32 offset)
{
Begin(String("glFogfv"));
Arg(String("pname"), GetFogPName(pname));
Arg(String("params"), GetFogParamCount(pname), params, offset);
Arg(String("offset"), offset);
End();
ECode ec = mgl->GlFogfv(pname, params, offset);
CheckError();
return ec;
}
ECode GLLogWrapper::GlFogfv(
/* [in] */ Int32 pname,
/* [in] */ IFloatBuffer* params)
{
Begin(String("GlFogfvEx"));
Arg(String("pname"), GetFogPName(pname));
Arg(String("params"), GetFogParamCount(pname), params);
End();
ECode ec = mgl->GlFogfv(pname, params);
CheckError();
return ec;
}
ECode GLLogWrapper::GlFogx(
/* [in] */ Int32 pname,
/* [in] */ Int32 param)
{
Begin(String("glFogx"));
Arg(String("pname"), GetFogPName(pname));
Arg(String("param"), param);
End();
ECode ec = mgl->GlFogx(pname, param);
CheckError();
return ec;
}
ECode GLLogWrapper::GlFogxv(
/* [in] */ Int32 pname,
/* [in] */ ArrayOf<Int32>* params,
/* [in] */ Int32 offset)
{
Begin(String("glFogxv"));
Arg(String("pname"), GetFogPName(pname));
Arg(String("params"), GetFogParamCount(pname), params, offset);
Arg(String("offset"), offset);
End();
ECode ec = mgl->GlFogxv(pname, params, offset);
CheckError();
return ec;
}
ECode GLLogWrapper::GlFogxv(
/* [in] */ Int32 pname,
/* [in] */ IInt32Buffer* params)
{
Begin(String("GlFogxvEx"));
Arg(String("pname"), GetFogPName(pname));
Arg(String("params"), GetFogParamCount(pname), params);
End();
ECode ec = mgl->GlFogxv(pname, params);
CheckError();
return ec;
}
ECode GLLogWrapper::GlFrontFace(
/* [in] */ Int32 mode)
{
Begin(String("glFrontFace"));
Arg(String("mode"), mode);
End();
ECode ec = mgl->GlFrontFace(mode);
CheckError();
return ec;
}
ECode GLLogWrapper::GlFrustumf(
/* [in] */ Float left,
/* [in] */ Float right,
/* [in] */ Float bottom,
/* [in] */ Float top,
/* [in] */ Float near,
/* [in] */ Float far)
{
Begin(String("glFrustumf"));
Arg(String("left"), left);
Arg(String("right"), right);
Arg(String("bottom"), bottom);
Arg(String("top"), top);
Arg(String("near"), near);
Arg(String("far"), far);
End();
ECode ec = mgl->GlFrustumf(left, right, bottom, top, near, far);
CheckError();
return ec;
}
ECode GLLogWrapper::GlFrustumx(
/* [in] */ Int32 left,
/* [in] */ Int32 right,
/* [in] */ Int32 bottom,
/* [in] */ Int32 top,
/* [in] */ Int32 near,
/* [in] */ Int32 far)
{
Begin(String("glFrustumx"));
Arg(String("left"), left);
Arg(String("right"), right);
Arg(String("bottom"), bottom);
Arg(String("top"), top);
Arg(String("near"), near);
Arg(String("far"), far);
End();
ECode ec = mgl->GlFrustumx(left, right, bottom, top, near, far);
CheckError();
return ec;
}
ECode GLLogWrapper::GlGenTextures(
/* [in] */ Int32 n,
/* [in] */ ArrayOf<Int32>* textures,
/* [in] */ Int32 offset)
{
Begin(String("glGenTextures"));
Arg(String("n"), n);
Arg(String("textures"), TranArrayToString(textures));
Arg(String("offset"), offset);
ECode ec = mgl->GlGenTextures(n, textures, offset);
Returns(ToString(n, FORMAT_INT, textures, offset));
CheckError();
return ec;
}
ECode GLLogWrapper::GlGenTextures(
/* [in] */ Int32 n,
/* [in] */ IInt32Buffer* textures)
{
Begin(String("GlGenTexturesEx"));
Arg(String("n"), n);
Arg(String("textures"), ParamsToString(textures));
ECode ec = mgl->GlGenTextures(n, textures);
Returns(ToString(n, FORMAT_INT, textures));
CheckError();
return ec;
}
ECode GLLogWrapper::GlGetError(
/* [out] */ Int32* error)
{
VALIDATE_NOT_NULL(error)
Begin(String("glGetError"));
ECode ec = mgl->GlGetError(error);
Returns(*error);
return ec;
}
ECode GLLogWrapper::GlGetString(
/* [in] */ Int32 name,
/* [out] */ String* str)
{
VALIDATE_NOT_NULL(str)
Begin(String("glGetString"));
Arg(String("name"), name);
ECode ec = mgl->GlGetString(name, str);
Returns(*str);
CheckError();
return ec;
}
ECode GLLogWrapper::GlHint(
/* [in] */ Int32 target,
/* [in] */ Int32 mode)
{
Begin(String("glHint"));
Arg(String("target"), GetHintTarget(target));
Arg(String("mode"), GetHintMode(mode));
End();
ECode ec = mgl->GlHint(target, mode);
CheckError();
return ec;
}
ECode GLLogWrapper::GlLightModelf(
/* [in] */ Int32 pname,
/* [in] */ Float param)
{
Begin(String("glLightModelf"));
Arg(String("pname"), GetLightModelPName(pname));
Arg(String("param"), param);
End();
ECode ec = mgl->GlLightModelf(pname, param);
CheckError();
return ec;
}
ECode GLLogWrapper::GlLightModelfv(
/* [in] */ Int32 pname,
/* [in] */ ArrayOf<Float>* params,
/* [in] */ Int32 offset)
{
Begin(String("glLightModelfv"));
Arg(String("pname"), GetLightModelPName(pname));
Arg(String("params"), GetLightModelParamCount(pname), params, offset);
Arg(String("offset"), offset);
End();
ECode ec = mgl->GlLightModelfv(pname, params, offset);
CheckError();
return ec;
}
ECode GLLogWrapper::GlLightModelfv(
/* [in] */ Int32 pname,
/* [in] */ IFloatBuffer* params)
{
Begin(String("GlLightModelfvEx"));
Arg(String("pname"), GetLightModelPName(pname));
Arg(String("params"), GetLightModelParamCount(pname), params);
End();
ECode ec = mgl->GlLightModelfv(pname, params);
CheckError();
return ec;
}
ECode GLLogWrapper::GlLightModelx(
/* [in] */ Int32 pname,
/* [in] */ Int32 param)
{
Begin(String("glLightModelx"));
Arg(String("pname"), GetLightModelPName(pname));
Arg(String("param"), param);
End();
ECode ec = mgl->GlLightModelx(pname, param);
CheckError();
return ec;
}
ECode GLLogWrapper::GlLightModelxv(
/* [in] */ Int32 pname,
/* [in] */ ArrayOf<Int32>* params,
/* [in] */ Int32 offset)
{
Begin(String("glLightModelxv"));
Arg(String("pname"), GetLightModelPName(pname));
Arg(String("params"), GetLightModelParamCount(pname), params, offset);
Arg(String("offset"), offset);
End();
ECode ec = mgl->GlLightModelxv(pname, params, offset);
CheckError();
return ec;
}
ECode GLLogWrapper::GlLightModelxv(
/* [in] */ Int32 pname,
/* [in] */ IInt32Buffer* params)
{
Begin(String("GlLightModelxvEx"));
Arg(String("pname"), GetLightModelPName(pname));
Arg(String("params"), GetLightModelParamCount(pname), params);
End();
ECode ec = mgl->GlLightModelxv(pname, params);
CheckError();
return ec;
}
ECode GLLogWrapper::GlLightf(
/* [in] */ Int32 light,
/* [in] */ Int32 pname,
/* [in] */ Float param)
{
Begin(String("glLightf"));
Arg(String("light"), GetLightName(light));
Arg(String("pname"), GetLightPName(pname));
Arg(String("param"), param);
End();
ECode ec = mgl->GlLightf(light, pname, param);
CheckError();
return ec;
}
ECode GLLogWrapper::GlLightfv(
/* [in] */ Int32 light,
/* [in] */ Int32 pname,
/* [in] */ ArrayOf<Float>* params,
/* [in] */ Int32 offset)
{
Begin(String("glLightfv"));
Arg(String("light"), GetLightName(light));
Arg(String("pname"), GetLightPName(pname));
Arg(String("params"), GetLightParamCount(pname), params, offset);
Arg(String("offset"), offset);
End();
ECode ec = mgl->GlLightfv(light, pname, params, offset);
CheckError();
return ec;
}
ECode GLLogWrapper::GlLightfv(
/* [in] */ Int32 light,
/* [in] */ Int32 pname,
/* [in] */ IFloatBuffer* params)
{
Begin(String("GlLightfvEx"));
Arg(String("light"), GetLightName(light));
Arg(String("pname"), GetLightPName(pname));
Arg(String("params"), GetLightParamCount(pname), params);
End();
ECode ec = mgl->GlLightfv(light, pname, params);
CheckError();
return ec;
}
ECode GLLogWrapper::GlLightx(
/* [in] */ Int32 light,
/* [in] */ Int32 pname,
/* [in] */ Int32 param)
{
Begin(String("glLightx"));
Arg(String("light"), GetLightName(light));
Arg(String("pname"), GetLightPName(pname));
Arg(String("param"), param);
End();
ECode ec = mgl->GlLightx(light, pname, param);
CheckError();
return ec;
}
ECode GLLogWrapper::GlLightxv(
/* [in] */ Int32 light,
/* [in] */ Int32 pname,
/* [in] */ ArrayOf<Int32>* params,
/* [in] */ Int32 offset)
{
Begin(String("glLightxv"));
Arg(String("light"), GetLightName(light));
Arg(String("pname"), GetLightPName(pname));
Arg(String("params"), GetLightParamCount(pname), params, offset);
Arg(String("offset"), offset);
End();
ECode ec = mgl->GlLightxv(light, pname, params, offset);
CheckError();
return ec;
}
ECode GLLogWrapper::GlLightxv(
/* [in] */ Int32 light,
/* [in] */ Int32 pname,
/* [in] */ IInt32Buffer* params)
{
Begin(String("GlLightxvEx"));
Arg(String("light"), GetLightName(light));
Arg(String("pname"), GetLightPName(pname));
Arg(String("params"), GetLightParamCount(pname), params);
End();
ECode ec = mgl->GlLightxv(light, pname, params);
CheckError();
return ec;
}
ECode GLLogWrapper::GlLineWidth(
/* [in] */ Float width)
{
Begin(String("glLineWidth"));
Arg(String("width"), width);
End();
ECode ec = mgl->GlLineWidth(width);
CheckError();
return ec;
}
ECode GLLogWrapper::GlLineWidthx(
/* [in] */ Int32 width)
{
Begin(String("glLineWidthx"));
Arg(String("width"), width);
End();
ECode ec = mgl->GlLineWidthx(width);
CheckError();
return ec;
}
ECode GLLogWrapper::GlLoadIdentity()
{
Begin(String("glLoadIdentity"));
End();
ECode ec = mgl->GlLoadIdentity();
CheckError();
return ec;
}
ECode GLLogWrapper::GlLoadMatrixf(
/* [in] */ ArrayOf<Float>* m,
/* [in] */ Int32 offset)
{
Begin(String("glLoadMatrixf"));
Arg(String("m"), 16, m, offset);
Arg(String("offset"), offset);
End();
ECode ec = mgl->GlLoadMatrixf(m, offset);
CheckError();
return ec;
}
ECode GLLogWrapper::GlLoadMatrixf(
/* [in] */ IFloatBuffer* m)
{
Begin(String("GlLoadMatrixfEx"));
Arg(String("m"), 16, m);
End();
ECode ec = mgl->GlLoadMatrixf(m);
CheckError();
return ec;
}
ECode GLLogWrapper::GlLoadMatrixx(
/* [in] */ ArrayOf<Int32>* m,
/* [in] */ Int32 offset)
{
Begin(String("glLoadMatrixx"));
Arg(String("m"), 16, m, offset);
Arg(String("offset"), offset);
End();
ECode ec = mgl->GlLoadMatrixx(m, offset);
CheckError();
return ec;
}
ECode GLLogWrapper::GlLoadMatrixx(
/* [in] */ IInt32Buffer* m)
{
Begin(String("GlLoadMatrixxEx"));
Arg(String("m"), 16, m);
End();
ECode ec = mgl->GlLoadMatrixx(m);
CheckError();
return ec;
}
ECode GLLogWrapper::GlLogicOp(
/* [in] */ Int32 opcode)
{
Begin(String("glLogicOp"));
Arg(String("opcode"), opcode);
End();
ECode ec = mgl->GlLogicOp(opcode);
CheckError();
return ec;
}
ECode GLLogWrapper::GlMaterialf(
/* [in] */ Int32 face,
/* [in] */ Int32 pname,
/* [in] */ Float param)
{
Begin(String("glMaterialf"));
Arg(String("face"), GetFaceName(face));
Arg(String("pname"), GetMaterialPName(pname));
Arg(String("param"), param);
End();
ECode ec = mgl->GlMaterialf(face, pname, param);
CheckError();
return ec;
}
ECode GLLogWrapper::GlMaterialfv(
/* [in] */ Int32 face,
/* [in] */ Int32 pname,
/* [in] */ ArrayOf<Float>* params,
/* [in] */ Int32 offset)
{
Begin(String("glMaterialfv"));
Arg(String("face"), GetFaceName(face));
Arg(String("pname"), GetMaterialPName(pname));
Arg(String("params"), GetMaterialParamCount(pname), params, offset);
Arg(String("offset"), offset);
End();
ECode ec = mgl->GlMaterialfv(face, pname, params, offset);
CheckError();
return ec;
}
ECode GLLogWrapper::GlMaterialfv(
/* [in] */ Int32 face,
/* [in] */ Int32 pname,
/* [in] */ IFloatBuffer* params)
{
Begin(String("GlMaterialfvEx"));
Arg(String("face"), GetFaceName(face));
Arg(String("pname"), GetMaterialPName(pname));
Arg(String("params"), GetMaterialParamCount(pname), params);
End();
ECode ec = mgl->GlMaterialfv(face, pname, params);
CheckError();
return ec;
}
ECode GLLogWrapper::GlMaterialx(
/* [in] */ Int32 face,
/* [in] */ Int32 pname,
/* [in] */ Int32 param)
{
Begin(String("glMaterialx"));
Arg(String("face"), GetFaceName(face));
Arg(String("pname"), GetMaterialPName(pname));
Arg(String("param"), param);
End();
ECode ec = mgl->GlMaterialx(face, pname, param);
CheckError();
return ec;
}
ECode GLLogWrapper::GlMaterialxv(
/* [in] */ Int32 face,
/* [in] */ Int32 pname,
/* [in] */ ArrayOf<Int32>* params,
/* [in] */ Int32 offset)
{
Begin(String("glMaterialxv"));
Arg(String("face"), GetFaceName(face));
Arg(String("pname"), GetMaterialPName(pname));
Arg(String("params"), GetMaterialParamCount(pname), params, offset);
Arg(String("offset"), offset);
End();
ECode ec = mgl->GlMaterialxv(face, pname, params, offset);
CheckError();
return ec;
}
ECode GLLogWrapper::GlMaterialxv(
/* [in] */ Int32 face,
/* [in] */ Int32 pname,
/* [in] */ IInt32Buffer* params)
{
Begin(String("GlMaterialxvEx"));
Arg(String("face"), GetFaceName(face));
Arg(String("pname"), GetMaterialPName(pname));
Arg(String("params"), GetMaterialParamCount(pname), params);
End();
ECode ec = mgl->GlMaterialxv(face, pname, params);
CheckError();
return ec;
}
ECode GLLogWrapper::GlMatrixMode(
/* [in] */ Int32 mode)
{
Begin(String("glMatrixMode"));
Arg(String("mode"), GetMatrixMode(mode));
End();
ECode ec = mgl->GlMatrixMode(mode);
CheckError();
return ec;
}
ECode GLLogWrapper::GlMultMatrixf(
/* [in] */ ArrayOf<Float>* m,
/* [in] */ Int32 offset)
{
Begin(String("glMultMatrixf"));
Arg(String("m"), 16, m, offset);
Arg(String("offset"), offset);
End();
ECode ec = mgl->GlMultMatrixf(m, offset);
CheckError();
return ec;
}
ECode GLLogWrapper::GlMultMatrixf(
/* [in] */ IFloatBuffer* m)
{
Begin(String("GlMultMatrixfEx"));
Arg(String("m"), 16, m);
End();
ECode ec = mgl->GlMultMatrixf(m);
CheckError();
return ec;
}
ECode GLLogWrapper::GlMultMatrixx(
/* [in] */ ArrayOf<Int32>* m,
/* [in] */ Int32 offset)
{
Begin(String("glMultMatrixx"));
Arg(String("m"), 16, m, offset);
Arg(String("offset"), offset);
End();
ECode ec = mgl->GlMultMatrixx(m, offset);
CheckError();
return ec;
}
ECode GLLogWrapper::GlMultMatrixx(
/* [in] */ IInt32Buffer* m)
{
Begin(String("GlMultMatrixxEx"));
Arg(String("m"), 16, m);
End();
ECode ec = mgl->GlMultMatrixx(m);
CheckError();
return ec;
}
ECode GLLogWrapper::GlMultiTexCoord4f(
/* [in] */ Int32 target,
/* [in] */ Float s,
/* [in] */ Float t,
/* [in] */ Float r,
/* [in] */ Float q)
{
Begin(String("glMultiTexCoord4f"));
Arg(String("target"), target);
Arg(String("s"), s);
Arg(String("t"), t);
Arg(String("r"), r);
Arg(String("q"), q);
End();
ECode ec = mgl->GlMultiTexCoord4f(target, s, t, r, q);
CheckError();
return ec;
}
ECode GLLogWrapper::GlMultiTexCoord4x(
/* [in] */ Int32 target,
/* [in] */ Int32 s,
/* [in] */ Int32 t,
/* [in] */ Int32 r,
/* [in] */ Int32 q)
{
Begin(String("glMultiTexCoord4x"));
Arg(String("target"), target);
Arg(String("s"), s);
Arg(String("t"), t);
Arg(String("r"), r);
Arg(String("q"), q);
End();
ECode ec = mgl->GlMultiTexCoord4x(target, s, t, r, q);
CheckError();
return ec;
}
ECode GLLogWrapper::GlNormal3f(
/* [in] */ Float nx,
/* [in] */ Float ny,
/* [in] */ Float nz)
{
Begin(String("glNormal3f"));
Arg(String("nx"), nx);
Arg(String("ny"), ny);
Arg(String("nz"), nz);
End();
ECode ec = mgl->GlNormal3f(nx, ny, nz);
CheckError();
return ec;
}
ECode GLLogWrapper::GlNormal3x(
/* [in] */ Int32 nx,
/* [in] */ Int32 ny,
/* [in] */ Int32 nz)
{
Begin(String("glNormal3x"));
Arg(String("nx"), nx);
Arg(String("ny"), ny);
Arg(String("nz"), nz);
End();
ECode ec = mgl->GlNormal3x(nx, ny, nz);
CheckError();
return ec;
}
ECode GLLogWrapper::GlNormalPointer(
/* [in] */ Int32 type,
/* [in] */ Int32 stride,
/* [in] */ IBuffer* pointer)
{
Begin(String("glNormalPointer"));
Arg(String("type"), type);
Arg(String("stride"), stride);
Arg(String("pointer"), ParamsToString(pointer));
End();
mNormalPointer = new PointerInfo(3, type, stride, pointer, this);
ECode ec = mgl->GlNormalPointer(type, stride, pointer);
CheckError();
return ec;
}
ECode GLLogWrapper::GlOrthof(
/* [in] */ Float left,
/* [in] */ Float right,
/* [in] */ Float bottom,
/* [in] */ Float top,
/* [in] */ Float near,
/* [in] */ Float far)
{
Begin(String("glOrthof"));
Arg(String("left"), left);
Arg(String("right"), right);
Arg(String("bottom"), bottom);
Arg(String("top"), top);
Arg(String("near"), near);
Arg(String("far"), far);
End();
ECode ec = mgl->GlOrthof(left, right, bottom, top, near, far);
CheckError();
return ec;
}
ECode GLLogWrapper::GlOrthox(
/* [in] */ Int32 left,
/* [in] */ Int32 right,
/* [in] */ Int32 bottom,
/* [in] */ Int32 top,
/* [in] */ Int32 near,
/* [in] */ Int32 far)
{
Begin(String("glOrthox"));
Arg(String("left"), left);
Arg(String("right"), right);
Arg(String("bottom"), bottom);
Arg(String("top"), top);
Arg(String("near"), near);
Arg(String("far"), far);
End();
ECode ec = mgl->GlOrthox(left, right, bottom, top, near, far);
CheckError();
return ec;
}
ECode GLLogWrapper::GlPixelStorei(
/* [in] */ Int32 pname,
/* [in] */ Int32 param)
{
Begin(String("glPixelStorei"));
Arg(String("pname"), pname);
Arg(String("param"), param);
End();
ECode ec = mgl->GlPixelStorei(pname, param);
CheckError();
return ec;
}
ECode GLLogWrapper::GlPointSize(
/* [in] */ Float size)
{
Begin(String("glPointSize"));
Arg(String("size"), size);
End();
ECode ec = mgl->GlPointSize(size);
CheckError();
return ec;
}
ECode GLLogWrapper::GlPointSizex(
/* [in] */ Int32 size)
{
Begin(String("glPointSizex"));
Arg(String("size"), size);
End();
ECode ec = mgl->GlPointSizex(size);
CheckError();
return ec;
}
ECode GLLogWrapper::GlPolygonOffset(
/* [in] */ Float factor,
/* [in] */ Float units)
{
Begin(String("glPolygonOffset"));
Arg(String("factor"), factor);
Arg(String("units"), units);
End();
ECode ec = mgl->GlPolygonOffset(factor, units);
CheckError();
return ec;
}
ECode GLLogWrapper::GlPolygonOffsetx(
/* [in] */ Int32 factor,
/* [in] */ Int32 units)
{
Begin(String("glPolygonOffsetx"));
Arg(String("factor"), factor);
Arg(String("units"), units);
End();
ECode ec = mgl->GlPolygonOffsetx(factor, units);
CheckError();
return ec;
}
ECode GLLogWrapper::GlPopMatrix()
{
Begin(String("glPopMatrix"));
End();
ECode ec = mgl->GlPopMatrix();
CheckError();
return ec;
}
ECode GLLogWrapper::GlPushMatrix()
{
Begin(String("glPushMatrix"));
End();
ECode ec = mgl->GlPushMatrix();
CheckError();
return ec;
}
ECode GLLogWrapper::GlReadPixels(
/* [in] */ Int32 x,
/* [in] */ Int32 y,
/* [in] */ Int32 width,
/* [in] */ Int32 height,
/* [in] */ Int32 format,
/* [in] */ Int32 type,
/* [in] */ IBuffer* pixels)
{
Begin(String("glReadPixels"));
Arg(String("x"), x);
Arg(String("y"), y);
Arg(String("width"), width);
Arg(String("height"), height);
Arg(String("format"), format);
Arg(String("type"), type);
Arg(String("pixels"), ParamsToString(pixels));
End();
ECode ec = mgl->GlReadPixels(x, y, width, height, format, type, pixels);
CheckError();
return ec;
}
ECode GLLogWrapper::GlRotatef(
/* [in] */ Float angle,
/* [in] */ Float x,
/* [in] */ Float y,
/* [in] */ Float z)
{
Begin(String("glRotatef"));
Arg(String("angle"), angle);
Arg(String("x"), x);
Arg(String("y"), y);
Arg(String("z"), z);
End();
ECode ec = mgl->GlRotatef(angle, x, y, z);
CheckError();
return ec;
}
ECode GLLogWrapper::GlRotatex(
/* [in] */ Int32 angle,
/* [in] */ Int32 x,
/* [in] */ Int32 y,
/* [in] */ Int32 z)
{
Begin(String("glRotatex"));
Arg(String("angle"), angle);
Arg(String("x"), x);
Arg(String("y"), y);
Arg(String("z"), z);
End();
ECode ec = mgl->GlRotatex(angle, x, y, z);
CheckError();
return ec;
}
ECode GLLogWrapper::GlSampleCoverage(
/* [in] */ Float value,
/* [in] */ Boolean invert)
{
Begin(String("glSampleCoveragex"));
Arg(String("value"), value);
Arg(String("invert"), invert);
End();
ECode ec = mgl->GlSampleCoverage(value, invert);
CheckError();
return ec;
}
ECode GLLogWrapper::GlSampleCoveragex(
/* [in] */ Int32 value,
/* [in] */ Boolean invert)
{
Begin(String("glSampleCoveragex"));
Arg(String("value"), value);
Arg(String("invert"), invert);
End();
ECode ec = mgl->GlSampleCoveragex(value, invert);
CheckError();
return ec;
}
ECode GLLogWrapper::GlScalef(
/* [in] */ Float x,
/* [in] */ Float y,
/* [in] */ Float z)
{
Begin(String("glScalef"));
Arg(String("x"), x);
Arg(String("y"), y);
Arg(String("z"), z);
End();
ECode ec = mgl->GlScalef(x, y, z);
CheckError();
return ec;
}
ECode GLLogWrapper::GlScalex(
/* [in] */ Int32 x,
/* [in] */ Int32 y,
/* [in] */ Int32 z)
{
Begin(String("glScalex"));
Arg(String("x"), x);
Arg(String("y"), y);
Arg(String("z"), z);
End();
ECode ec = mgl->GlScalex(x, y, z);
CheckError();
return ec;
}
ECode GLLogWrapper::GlScissor(
/* [in] */ Int32 x,
/* [in] */ Int32 y,
/* [in] */ Int32 width,
/* [in] */ Int32 height)
{
Begin(String("glScissor"));
Arg(String("x"), x);
Arg(String("y"), y);
Arg(String("width"), width);
Arg(String("height"), height);
End();
ECode ec = mgl->GlScissor(x, y, width, height);
CheckError();
return ec;
}
ECode GLLogWrapper::GlShadeModel(
/* [in] */ Int32 mode)
{
Begin(String("glShadeModel"));
Arg(String("mode"), GetShadeModel(mode));
End();
ECode ec = mgl->GlShadeModel(mode);
CheckError();
return ec;
}
ECode GLLogWrapper::GlStencilFunc(
/* [in] */ Int32 func,
/* [in] */ Int32 ref,
/* [in] */ Int32 mask)
{
Begin(String("glStencilFunc"));
Arg(String("func"), func);
Arg(String("ref"), ref);
Arg(String("mask"), mask);
End();
ECode ec = mgl->GlStencilFunc(func, ref, mask);
CheckError();
return ec;
}
ECode GLLogWrapper::GlStencilMask(
/* [in] */ Int32 mask)
{
Begin(String("glStencilMask"));
Arg(String("mask"), mask);
End();
ECode ec = mgl->GlStencilMask(mask);
CheckError();
return ec;
}
ECode GLLogWrapper::GlTexCoordPointer(
/* [in] */ Int32 size,
/* [in] */ Int32 type,
/* [in] */ Int32 stride,
/* [in] */ IBuffer* pointer)
{
Begin(String("glTexCoordPointer"));
ArgPointer(size, type, stride, pointer);
End();
mTexCoordPointer = new PointerInfo(size, type, stride, pointer, this);
ECode ec = mgl->GlTexCoordPointer(size, type, stride, pointer);
CheckError();
return ec;
}
ECode GLLogWrapper::GlTexImage2D(
/* [in] */ Int32 target,
/* [in] */ Int32 level,
/* [in] */ Int32 internalformat,
/* [in] */ Int32 width,
/* [in] */ Int32 height,
/* [in] */ Int32 border,
/* [in] */ Int32 format,
/* [in] */ Int32 type,
/* [in] */ IBuffer* pixels)
{
Begin(String("glTexImage2D"));
Arg(String("target"), target);
Arg(String("level"), level);
Arg(String("internalformat"), internalformat);
Arg(String("width"), width);
Arg(String("height"), height);
Arg(String("border"), border);
Arg(String("format"), format);
Arg(String("type"), type);
Arg(String("pixels"), ParamsToString(pixels));
End();
ECode ec = mgl->GlTexImage2D(target, level, internalformat, width, height, border,
format, type, pixels);
CheckError();
return ec;
}
ECode GLLogWrapper::GlTexParameterx(
/* [in] */ Int32 target,
/* [in] */ Int32 pname,
/* [in] */ Int32 param)
{
Begin(String("glTexParameterx"));
Arg(String("target"), GetTextureTarget(target));
Arg(String("pname"), GetTexturePName(pname));
Arg(String("param"), param);
End();
ECode ec = mgl->GlTexParameterx(target, pname, param);
CheckError();
return ec;
}
ECode GLLogWrapper::GlTexSubImage2D(
/* [in] */ Int32 target,
/* [in] */ Int32 level,
/* [in] */ Int32 xoffset,
/* [in] */ Int32 yoffset,
/* [in] */ Int32 width,
/* [in] */ Int32 height,
/* [in] */ Int32 format,
/* [in] */ Int32 type,
/* [in] */ IBuffer* pixels)
{
Begin(String("glTexSubImage2D"));
Arg(String("target"), GetTextureTarget(target));
Arg(String("level"), level);
Arg(String("xoffset"), xoffset);
Arg(String("yoffset"), yoffset);
Arg(String("width"), width);
Arg(String("height"), height);
Arg(String("format"), format);
Arg(String("type"), type);
Arg(String("pixels"), ParamsToString(pixels));
End();
ECode ec = mgl->GlTexSubImage2D(target, level, xoffset, yoffset, width, height,
format, type, pixels);
CheckError();
return ec;
}
ECode GLLogWrapper::GlTranslatef(
/* [in] */ Float x,
/* [in] */ Float y,
/* [in] */ Float z)
{
Begin(String("glTranslatef"));
Arg(String("x"), x);
Arg(String("y"), y);
Arg(String("z"), z);
End();
ECode ec = mgl->GlTranslatef(x, y, z);
CheckError();
return ec;
}
ECode GLLogWrapper::GlTranslatex(
/* [in] */ Int32 x,
/* [in] */ Int32 y,
/* [in] */ Int32 z)
{
Begin(String("glTranslatex"));
Arg(String("x"), x);
Arg(String("y"), y);
Arg(String("z"), z);
End();
ECode ec = mgl->GlTranslatex(x, y, z);
CheckError();
return ec;
}
ECode GLLogWrapper::GlVertexPointer(
/* [in] */ Int32 size,
/* [in] */ Int32 type,
/* [in] */ Int32 stride,
/* [in] */ IBuffer* pointer)
{
Begin(String("glVertexPointer"));
ArgPointer(size, type, stride, pointer);
End();
mVertexPointer = new PointerInfo(size, type, stride, pointer, this);
ECode ec = mgl->GlVertexPointer(size, type, stride, pointer);
CheckError();
return ec;
}
ECode GLLogWrapper::GlViewport(
/* [in] */ Int32 x,
/* [in] */ Int32 y,
/* [in] */ Int32 width,
/* [in] */ Int32 height)
{
Begin(String("glViewport"));
Arg(String("x"), x);
Arg(String("y"), y);
Arg(String("width"), width);
Arg(String("height"), height);
End();
ECode ec = mgl->GlViewport(x, y, width, height);
CheckError();
return ec;
}
ECode GLLogWrapper::GlEnable(
/* [in] */ Int32 cap)
{
Begin(String("glEnable"));
Arg(String("cap"), GetCap(cap));
End();
ECode ec = IGL::Probe(mgl)->GlEnable(cap);
CheckError();
return ec;
}
ECode GLLogWrapper::GlEnableClientState(
/* [in] */ Int32 array)
{
Begin(String("glEnableClientState"));
Arg(String("array"), GetClientState(array));
End();
switch (array) {
case IGL10::_GL_COLOR_ARRAY:
mColorArrayEnabled = true;
break;
case IGL10::_GL_NORMAL_ARRAY:
mNormalArrayEnabled = true;
break;
case IGL10::_GL_TEXTURE_COORD_ARRAY:
mTextureCoordArrayEnabled = true;
break;
case IGL10::_GL_VERTEX_ARRAY:
mVertexArrayEnabled = true;
break;
}
ECode ec = IGL::Probe(mgl)->GlEnableClientState(array);
CheckError();
return ec;
}
ECode GLLogWrapper::GlTexParameterf(
/* [in] */ Int32 target,
/* [in] */ Int32 pname,
/* [in] */ Float param)
{
Begin(String("glTexParameterf"));
Arg(String("target"), GetTextureTarget(target));
Arg(String("pname"), GetTexturePName(pname));
Arg(String("param"), GetTextureParamName(param));
End();
ECode ec = IGL::Probe(mgl)->GlTexParameterf(target, pname, param);
CheckError();
return ec;
}
ECode GLLogWrapper::GlTexParameterfv(
/* [in] */ Int32 target,
/* [in] */ Int32 pname,
/* [in] */ ArrayOf<Float>* params,
/* [in] */ Int32 offset)
{
Begin(String("glTexParameterfv"));
Arg(String("target"), target);
Arg(String("pname"), pname);
Arg(String("params"), TranArrayToString(params));
Arg(String("offset"), offset);
End();
ECode ec = IGL::Probe(mgl11)->GlTexParameterfv( target, pname, params, offset);
CheckError();
return ec;
}
ECode GLLogWrapper::GlTexParameterfv(
/* [in] */ Int32 target,
/* [in] */ Int32 pname,
/* [in] */ IFloatBuffer* params)
{
Begin(String("GlTexParameterfv"));
Arg(String("target"), target);
Arg(String("pname"), pname);
String str;
IObject::Probe(params)->ToString(&str);
Arg(String("params"), str);
End();
ECode ec = IGL::Probe(mgl11)->GlTexParameterfv(target, pname, params);
CheckError();
return ec;
}
ECode GLLogWrapper::GlBindTexture(
/* [in] */ Int32 target,
/* [in] */ Int32 texture)
{
Begin(String("glBindTexture"));
Arg(String("target"), GetTextureTarget(target));
Arg(String("texture"), texture);
End();
ECode ec = IGL::Probe(mgl)->GlBindTexture(target, texture);
CheckError();
return ec;
}
ECode GLLogWrapper::GlCompressedTexImage2D(
/* [in] */ Int32 target,
/* [in] */ Int32 level,
/* [in] */ Int32 internalformat,
/* [in] */ Int32 width,
/* [in] */ Int32 height,
/* [in] */ Int32 border,
/* [in] */ Int32 imageSize,
/* [in] */ IBuffer* data)
{
Begin(String("glCompressedTexImage2D"));
Arg(String("target"), GetTextureTarget(target));
Arg(String("level"), level);
Arg(String("internalformat"), internalformat);
Arg(String("width"), width);
Arg(String("height"), height);
Arg(String("border"), border);
Arg(String("imageSize"), imageSize);
Arg(String("data"), ParamsToString(data));
End();
ECode ec = IGL::Probe(mgl)->GlCompressedTexImage2D(target, level, internalformat, width,
height, border, imageSize, data);
CheckError();
return ec;
}
ECode GLLogWrapper::GlCopyTexImage2D(
/* [in] */ Int32 target,
/* [in] */ Int32 level,
/* [in] */ Int32 internalformat,
/* [in] */ Int32 x,
/* [in] */ Int32 y,
/* [in] */ Int32 width,
/* [in] */ Int32 height,
/* [in] */ Int32 border)
{
Begin(String("glCopyTexImage2D"));
Arg(String("target"), GetTextureTarget(target));
Arg(String("level"), level);
Arg(String("internalformat"), internalformat);
Arg(String("x"), x);
Arg(String("y"), y);
Arg(String("width"), width);
Arg(String("height"), height);
Arg(String("border"), border);
End();
ECode ec = IGL::Probe(mgl)->GlCopyTexImage2D(target, level, internalformat, x, y, width,
height, border);
CheckError();
return ec;
}
ECode GLLogWrapper::GlGetIntegerv(
/* [in] */ Int32 pname,
/* [in] */ ArrayOf<Int32>* params,
/* [in] */ Int32 offset)
{
Begin(String("glGetIntegerv"));
Arg(String("pname"), GetIntegerStateName(pname));
Arg(String("params"), ParamsToString(params));
Arg(String("offset"), offset);
ECode ec = IGL::Probe(mgl)->GlGetIntegerv(pname, params, offset);
Returns(ToString(GetIntegerStateSize(pname),
GetIntegerStateFormat(pname), params, offset));
CheckError();
return ec;
}
ECode GLLogWrapper::GlGetIntegerv(
/* [in] */ Int32 pname,
/* [in] */ IInt32Buffer* params)
{
Begin(String("GlGetIntegervEx"));
Arg(String("pname"), GetIntegerStateName(pname));
Arg(String("params"), ParamsToString(params));
ECode ec = IGL::Probe(mgl)->GlGetIntegerv(pname, params);
Returns(ToString(GetIntegerStateSize(pname),
GetIntegerStateFormat(pname), params));
CheckError();
return ec;
}
ECode GLLogWrapper::GlStencilOp(
/* [in] */ Int32 fail,
/* [in] */ Int32 zfail,
/* [in] */ Int32 zpass)
{
Begin(String("glStencilOp"));
Arg(String("fail"), fail);
Arg(String("zfail"), zfail);
Arg(String("zpass"), zpass);
End();
ECode ec = IGL::Probe(mgl)->GlStencilOp(fail, zfail, zpass);
CheckError();
return ec;
}
ECode GLLogWrapper::GlTexEnvf(
/* [in] */ Int32 target,
/* [in] */ Int32 pname,
/* [in] */ Float param)
{
Begin(String("glTexEnvf"));
Arg(String("target"), GetTextureEnvTarget(target));
Arg(String("pname"), GetTextureEnvPName(pname));
Arg(String("param"), GetTextureEnvParamName(param));
End();
ECode ec = IGL::Probe(mgl)->GlTexEnvf(target, pname, param);
CheckError();
return ec;
}
ECode GLLogWrapper::GlTexEnvfv(
/* [in] */ Int32 target,
/* [in] */ Int32 pname,
/* [in] */ ArrayOf<Float>* params,
/* [in] */ Int32 offset)
{
Begin(String("glTexEnvfv"));
Arg(String("target"), GetTextureEnvTarget(target));
Arg(String("pname"), GetTextureEnvPName(pname));
Arg(String("params"), GetTextureEnvParamCount(pname), params, offset);
Arg(String("offset"), offset);
End();
ECode ec = IGL::Probe(mgl)->GlTexEnvfv(target, pname, params, offset);
CheckError();
return ec;
}
ECode GLLogWrapper::GlTexEnvfv(
/* [in] */ Int32 target,
/* [in] */ Int32 pname,
/* [in] */ IFloatBuffer* params)
{
Begin(String("GlTexEnvfvEx"));
Arg(String("target"), GetTextureEnvTarget(target));
Arg(String("pname"), GetTextureEnvPName(pname));
Arg(String("params"), GetTextureEnvParamCount(pname), params);
End();
ECode ec = IGL::Probe(mgl)->GlTexEnvfv(target, pname, params);
CheckError();
return ec;
}
ECode GLLogWrapper::GlTexEnvx(
/* [in] */ Int32 target,
/* [in] */ Int32 pname,
/* [in] */ Int32 param)
{
Begin(String("glTexEnvx"));
Arg(String("target"), GetTextureEnvTarget(target));
Arg(String("pname"), GetTextureEnvPName(pname));
Arg(String("param"), param);
End();
ECode ec = IGL::Probe(mgl)->GlTexEnvx(target, pname, param);
CheckError();
return ec;
}
ECode GLLogWrapper::GlTexEnvxv(
/* [in] */ Int32 target,
/* [in] */ Int32 pname,
/* [in] */ ArrayOf<Int32>* params,
/* [in] */ Int32 offset)
{
Begin(String("glTexEnvxv"));
Arg(String("target"), GetTextureEnvTarget(target));
Arg(String("pname"), GetTextureEnvPName(pname));
Arg(String("params"), GetTextureEnvParamCount(pname), params, offset);
Arg(String("offset"), offset);
End();
ECode ec = IGL::Probe(mgl)->GlTexEnvxv(target, pname, params, offset);
CheckError();
return ec;
}
ECode GLLogWrapper::GlTexEnvxv(
/* [in] */ Int32 target,
/* [in] */ Int32 pname,
/* [in] */ IInt32Buffer* params)
{
Begin(String("GlTexEnvxvEx"));
Arg(String("target"), GetTextureEnvTarget(target));
Arg(String("pname"), GetTextureEnvPName(pname));
Arg(String("params"), GetTextureEnvParamCount(pname), params);
End();
ECode ec = IGL::Probe(mgl)->GlTexEnvxv(target, pname, params);
CheckError();
return ec;
}
ECode GLLogWrapper::GlQueryMatrixxOES(
/* [in] */ ArrayOf<Int32>* mantissa,
/* [in] */ Int32 mantissaOffset,
/* [in] */ ArrayOf<Int32>* exponent,
/* [in] */ Int32 exponentOffset,
/* [out] */ Int32* matrixxOES)
{
VALIDATE_NOT_NULL(matrixxOES)
Begin(String("glQueryMatrixxOES"));
Arg(String("mantissa"), ParamsToString(mantissa));
Arg(String("exponent"), ParamsToString(exponent));
End();
ECode ec = mgl10Ext->GlQueryMatrixxOES(mantissa, mantissaOffset,
exponent, exponentOffset, matrixxOES);
Returns(ToString(16, FORMAT_FIXED, mantissa, mantissaOffset));
Returns(ToString(16, FORMAT_INT, exponent, exponentOffset));
CheckError();
return ec;
}
ECode GLLogWrapper::GlQueryMatrixxOES(
/* [in] */ IInt32Buffer* mantissa,
/* [in] */ IInt32Buffer* exponent,
/* [out] */ Int32* matrixxOES)
{
VALIDATE_NOT_NULL(matrixxOES)
Begin(String("GlQueryMatrixxOESEx"));
Arg(String("mantissa"), ParamsToString(mantissa));
Arg(String("exponent"), ParamsToString(exponent));
End();
ECode ec = mgl10Ext->GlQueryMatrixxOES(mantissa, exponent, matrixxOES);
Returns(ToString(16, FORMAT_FIXED, mantissa));
Returns(ToString(16, FORMAT_INT, exponent));
CheckError();
return ec;
}
ECode GLLogWrapper::GlGetPointerv(
/* [in] */ Int32 pname,
/* [in] */ ArrayOf<IBuffer*>* params)
{
Begin(String("glGetPointerv"));
Arg(String("pname"), pname);
Arg(String("params"), ParamsToString(params));
End();
ECode ec = mgl11->GlGetPointerv(pname, params);
CheckError();
return ec;
}
ECode GLLogWrapper::GlBindBuffer(
/* [in] */ Int32 target,
/* [in] */ Int32 buffer)
{
Begin(String("glBindBuffer"));
Arg(String("target"), target);
Arg(String("buffer"), buffer);
End();
ECode ec = mgl11->GlBindBuffer(target, buffer);
CheckError();
return ec;
}
ECode GLLogWrapper::GlBufferData(
/* [in] */ Int32 target,
/* [in] */ Int32 size,
/* [in] */ IBuffer* data,
/* [in] */ Int32 usage)
{
Begin(String("glBufferData"));
Arg(String("target"), target);
Arg(String("size"), size);
Arg(String("data"), ParamsToString(data));
Arg(String("usage"), usage);
End();
ECode ec = mgl11->GlBufferData(target, size, data, usage);
CheckError();
return ec;
}
ECode GLLogWrapper::GlBufferSubData(
/* [in] */ Int32 target,
/* [in] */ Int32 offset,
/* [in] */ Int32 size,
/* [in] */ IBuffer* data)
{
Begin(String("glBufferSubData"));
Arg(String("target"), target);
Arg(String("offset"), offset);
Arg(String("size"), size);
Arg(String("data"), ParamsToString(data));
End();
ECode ec = mgl11->GlBufferSubData(target, offset, size, data);
CheckError();
return ec;
}
ECode GLLogWrapper::GlClipPlanef(
/* [in] */ Int32 plane,
/* [in] */ ArrayOf<Float>* equation,
/* [in] */ Int32 offset)
{
Begin(String("glClipPlanef"));
Arg(String("plane"), plane);
Arg(String("equation"), 4, equation, offset);
Arg(String("offset"), offset);
End();
ECode ec = mgl11->GlClipPlanef(plane, equation, offset);
CheckError();
return ec;
}
ECode GLLogWrapper::GlClipPlanef(
/* [in] */ Int32 plane,
/* [in] */ IFloatBuffer* equation)
{
Begin(String("GlClipPlanefEx"));
Arg(String("plane"), plane);
Arg(String("equation"), 4, equation);
End();
ECode ec = mgl11->GlClipPlanef(plane, equation);
CheckError();
return ec;
}
ECode GLLogWrapper::GlClipPlanex(
/* [in] */ Int32 plane,
/* [in] */ ArrayOf<Int32>* equation,
/* [in] */ Int32 offset)
{
Begin(String("glClipPlanex"));
Arg(String("plane"), plane);
Arg(String("equation"), 4, equation, offset);
Arg(String("offset"), offset);
End();
ECode ec = mgl11->GlClipPlanex(plane, equation, offset);
CheckError();
return ec;
}
ECode GLLogWrapper::GlClipPlanex(
/* [in] */ Int32 plane,
/* [in] */ IInt32Buffer* equation)
{
Begin(String("GlClipPlanexEx"));
Arg(String("plane"), plane);
Arg(String("equation"), 4, equation);
End();
ECode ec = mgl11->GlClipPlanex(plane, equation);
CheckError();
return ec;
}
ECode GLLogWrapper::GlColor4ub(
/* [in] */ Byte red,
/* [in] */ Byte green,
/* [in] */ Byte blue,
/* [in] */ Byte alpha)
{
Begin(String("glColor4ub"));
Arg(String("red"), red);
Arg(String("green"), green);
Arg(String("blue"), blue);
Arg(String("alpha"), alpha);
End();
ECode ec = mgl11->GlColor4ub(red, green, blue, alpha);
CheckError();
return ec;
}
ECode GLLogWrapper::GlColorPointer(
/* [in] */ Int32 size,
/* [in] */ Int32 type,
/* [in] */ Int32 stride,
/* [in] */ Int32 offset)
{
Begin(String("GlColorPointerEx"));
Arg(String("size"), size);
Arg(String("type"), type);
Arg(String("stride"), stride);
Arg(String("offset"), offset);
End();
ECode ec = mgl11->GlColorPointer(size, type, stride, offset);
CheckError();
return ec;
}
ECode GLLogWrapper::GlDeleteBuffers(
/* [in] */ Int32 n,
/* [in] */ ArrayOf<Int32>* buffers,
/* [in] */ Int32 offset)
{
Begin(String("glDeleteBuffers"));
Arg(String("n"), n);
Arg(String("buffers"), ParamsToString(buffers));
Arg(String("offset"), offset);
End();
ECode ec = mgl11->GlDeleteBuffers(n, buffers, offset);
CheckError();
return ec;
}
ECode GLLogWrapper::GlDeleteBuffers(
/* [in] */ Int32 n,
/* [in] */ IInt32Buffer* buffers)
{
Begin(String("GlDeleteBuffersEx"));
Arg(String("n"), n);
Arg(String("buffers"), ParamsToString(buffers));
End();
ECode ec = mgl11->GlDeleteBuffers(n, buffers);
CheckError();
return ec;
}
ECode GLLogWrapper::GlDrawElements(
/* [in] */ Int32 mode,
/* [in] */ Int32 count,
/* [in] */ Int32 type,
/* [in] */ Int32 offset)
{
Begin(String("GlDrawElementsEx"));
Arg(String("mode"), mode);
Arg(String("count"), count);
Arg(String("type"), type);
Arg(String("offset"), offset);
End();
ECode ec = mgl11->GlDrawElements(mode, count, type, offset);
CheckError();
return ec;
}
ECode GLLogWrapper::GlGenBuffers(
/* [in] */ Int32 n,
/* [in] */ ArrayOf<Int32>* buffers,
/* [in] */ Int32 offset)
{
Begin(String("glGenBuffers"));
Arg(String("n"), n);
Arg(String("buffers"), ParamsToString(buffers));
Arg(String("offset"), offset);
End();
ECode ec = mgl11->GlGenBuffers(n, buffers, offset);
CheckError();
return ec;
}
ECode GLLogWrapper::GlGenBuffers(
/* [in] */ Int32 n,
/* [in] */ IInt32Buffer* buffers)
{
Begin(String("GlGenBuffersEx"));
Arg(String("n"), n);
Arg(String("buffers"), ParamsToString(buffers));
End();
ECode ec = mgl11->GlGenBuffers(n, buffers);
CheckError();
return ec;
}
ECode GLLogWrapper::GlGetBooleanv(
/* [in] */ Int32 pname,
/* [in] */ ArrayOf<Boolean>* params,
/* [in] */ Int32 offset)
{
Begin(String("glGetBooleanv"));
Arg(String("pname"), pname);
Arg(String("params"), ParamsToString(params));
Arg(String("offset"), offset);
End();
ECode ec = mgl11->GlGetBooleanv(pname, params, offset);
CheckError();
return ec;
}
ECode GLLogWrapper::GlGetBooleanv(
/* [in] */ Int32 pname,
/* [in] */ IInt32Buffer* params)
{
Begin(String("GlGetBooleanvEx"));
Arg(String("pname"), pname);
Arg(String("params"), ParamsToString(params));
End();
ECode ec = mgl11->GlGetBooleanv(pname, params);
CheckError();
return ec;
}
ECode GLLogWrapper::GlGetBufferParameteriv(
/* [in] */ Int32 target,
/* [in] */ Int32 pname,
/* [in] */ ArrayOf<Int32>* params,
/* [in] */ Int32 offset)
{
Begin(String("glGetBufferParameteriv"));
Arg(String("target"), target);
Arg(String("pname"), pname);
Arg(String("params"), ParamsToString(params));
Arg(String("offset"), offset);
End();
ECode ec = mgl11->GlGetBufferParameteriv(target, pname, params, offset);
CheckError();
return ec;
}
ECode GLLogWrapper::GlGetBufferParameteriv(
/* [in] */ Int32 target,
/* [in] */ Int32 pname,
/* [in] */ IInt32Buffer* params)
{
Begin(String("GlGetBufferParameterivEx"));
Arg(String("target"), target);
Arg(String("pname"), pname);
Arg(String("params"), ParamsToString(params));
End();
ECode ec = mgl11->GlGetBufferParameteriv(target, pname, params);
CheckError();
return ec;
}
ECode GLLogWrapper::GlGetClipPlanef(
/* [in] */ Int32 pname,
/* [in] */ ArrayOf<Float>* eqn,
/* [in] */ Int32 offset)
{
Begin(String("glGetClipPlanef"));
Arg(String("pname"), pname);
Arg(String("eqn"), ParamsToString(eqn));
Arg(String("offset"), offset);
End();
ECode ec = mgl11->GlGetClipPlanef(pname, eqn, offset);
CheckError();
return ec;
}
ECode GLLogWrapper::GlGetClipPlanef(
/* [in] */ Int32 pname,
/* [in] */ IFloatBuffer* eqn)
{
Begin(String("GlGetClipPlanefEx"));
Arg(String("pname"), pname);
Arg(String("eqn"), ParamsToString(eqn));
End();
ECode ec = mgl11->GlGetClipPlanef(pname, eqn);
CheckError();
return ec;
}
ECode GLLogWrapper::GlGetClipPlanex(
/* [in] */ Int32 pname,
/* [in] */ ArrayOf<Int32>* eqn,
/* [in] */ Int32 offset)
{
Begin(String("glGetClipPlanex"));
Arg(String("pname"), pname);
Arg(String("eqn"), ParamsToString(eqn));
Arg(String("offset"), offset);
End();
return mgl11->GlGetClipPlanex(pname, eqn, offset);
}
ECode GLLogWrapper::GlGetClipPlanex(
/* [in] */ Int32 pname,
/* [in] */ IInt32Buffer* eqn)
{
Begin(String("GlGetClipPlanexEx"));
Arg(String("pname"), pname);
Arg(String("eqn"), ParamsToString(eqn));
End();
ECode ec = mgl11->GlGetClipPlanex(pname, eqn);
CheckError();
return ec;
}
ECode GLLogWrapper::GlGetFixedv(
/* [in] */ Int32 pname,
/* [in] */ ArrayOf<Int32>* params,
/* [in] */ Int32 offset)
{
Begin(String("glGetFixedv"));
Arg(String("pname"), pname);
Arg(String("params"), ParamsToString(params));
Arg(String("offset"), offset);
End();
return mgl11->GlGetFixedv(pname, params, offset);
}
ECode GLLogWrapper::GlGetFixedv(
/* [in] */ Int32 pname,
/* [in] */ IInt32Buffer* params)
{
Begin(String("GlGetFixedvEx"));
Arg(String("pname"), pname);
Arg(String("params"), ParamsToString(params));
End();
ECode ec = mgl11->GlGetFixedv(pname, params);
CheckError();
return ec;
}
ECode GLLogWrapper::GlGetFloatv(
/* [in] */ Int32 pname,
/* [in] */ ArrayOf<Float>* params,
/* [in] */ Int32 offset)
{
Begin(String("glGetFloatv"));
Arg(String("pname"), pname);
Arg(String("params"), ParamsToString(params));
Arg(String("offset"), offset);
End();
return mgl11->GlGetFloatv(pname, params, offset);
}
ECode GLLogWrapper::GlGetFloatv(
/* [in] */ Int32 pname,
/* [in] */ IFloatBuffer* params)
{
Begin(String("GlGetFloatvEx"));
Arg(String("pname"), pname);
Arg(String("params"), ParamsToString(params));
End();
ECode ec = mgl11->GlGetFloatv(pname, params);
CheckError();
return ec;
}
ECode GLLogWrapper::GlGetLightfv(
/* [in] */ Int32 light,
/* [in] */ Int32 pname,
/* [in] */ ArrayOf<Float>* params,
/* [in] */ Int32 offset)
{
Begin(String("glGetLightfv"));
Arg(String("light"), light);
Arg(String("pname"), pname);
Arg(String("params"), ParamsToString(params));
Arg(String("offset"), offset);
End();
ECode ec = mgl11->GlGetLightfv(light, pname, params, offset);
CheckError();
return ec;
}
ECode GLLogWrapper::GlGetLightfv(
/* [in] */ Int32 light,
/* [in] */ Int32 pname,
/* [in] */ IFloatBuffer* params)
{
Begin(String("GlGetLightfvEx"));
Arg(String("light"), light);
Arg(String("pname"), pname);
Arg(String("params"), ParamsToString(params));
End();
ECode ec = mgl11->GlGetLightfv(light, pname, params);
CheckError();
return ec;
}
ECode GLLogWrapper::GlGetLightxv(
/* [in] */ Int32 light,
/* [in] */ Int32 pname,
/* [in] */ ArrayOf<Int32>* params,
/* [in] */ Int32 offset)
{
Begin(String("glGetLightxv"));
Arg(String("light"), light);
Arg(String("pname"), pname);
Arg(String("params"), ParamsToString(params));
Arg(String("offset"), offset);
End();
ECode ec = mgl11->GlGetLightxv(light, pname, params, offset);
CheckError();
return ec;
}
ECode GLLogWrapper::GlGetLightxv(
/* [in] */ Int32 light,
/* [in] */ Int32 pname,
/* [in] */ IInt32Buffer* params)
{
Begin(String("GlGetLightxvEx"));
Arg(String("light"), light);
Arg(String("pname"), pname);
Arg(String("params"), ParamsToString(params));
End();
ECode ec = mgl11->GlGetLightxv(light, pname, params);
CheckError();
return ec;
}
ECode GLLogWrapper::GlGetMaterialfv(
/* [in] */ Int32 face,
/* [in] */ Int32 pname,
/* [in] */ ArrayOf<Float>* params,
/* [in] */ Int32 offset)
{
Begin(String("glGetMaterialfv"));
Arg(String("face"), face);
Arg(String("pname"), pname);
Arg(String("params"), ParamsToString(params));
Arg(String("offset"), offset);
End();
ECode ec = mgl11->GlGetMaterialfv(face, pname, params, offset);
CheckError();
return ec;
}
ECode GLLogWrapper::GlGetMaterialfv(
/* [in] */ Int32 face,
/* [in] */ Int32 pname,
/* [in] */ IFloatBuffer* params)
{
Begin(String("GlGetMaterialfvEx"));
Arg(String("face"), face);
Arg(String("pname"), pname);
Arg(String("params"), ParamsToString(params));
End();
ECode ec = mgl11->GlGetMaterialfv(face, pname, params);
CheckError();
return ec;
}
ECode GLLogWrapper::GlGetMaterialxv(
/* [in] */ Int32 face,
/* [in] */ Int32 pname,
/* [in] */ ArrayOf<Int32>* params,
/* [in] */ Int32 offset)
{
Begin(String("glGetMaterialxv"));
Arg(String("face"), face);
Arg(String("pname"), pname);
Arg(String("params"), ParamsToString(params));
Arg(String("offset"), offset);
End();
ECode ec = mgl11->GlGetMaterialxv(face, pname, params, offset);
CheckError();
return ec;
}
ECode GLLogWrapper::GlGetMaterialxv(
/* [in] */ Int32 face,
/* [in] */ Int32 pname,
/* [in] */ IInt32Buffer* params)
{
Begin(String("GlGetMaterialxvEx"));
Arg(String("face"), face);
Arg(String("pname"), pname);
Arg(String("params"), ParamsToString(params));
End();
ECode ec = mgl11->GlGetMaterialxv(face, pname, params);
CheckError();
return ec;
}
ECode GLLogWrapper::GlGetTexEnviv(
/* [in] */ Int32 env,
/* [in] */ Int32 pname,
/* [in] */ ArrayOf<Int32>* params,
/* [in] */ Int32 offset)
{
Begin(String("glGetTexEnviv"));
Arg(String("env"), env);
Arg(String("pname"), pname);
Arg(String("params"), ParamsToString(params));
Arg(String("offset"), offset);
End();
ECode ec = mgl11->GlGetTexEnviv(env, pname, params, offset);
CheckError();
return ec;
}
ECode GLLogWrapper::GlGetTexEnviv(
/* [in] */ Int32 env,
/* [in] */ Int32 pname,
/* [in] */ IInt32Buffer* params)
{
Begin(String("GlGetTexEnvivEx"));
Arg(String("env"), env);
Arg(String("pname"), pname);
Arg(String("params"), ParamsToString(params));
End();
ECode ec = mgl11->GlGetTexEnviv(env, pname, params);
CheckError();
return ec;
}
ECode GLLogWrapper::GlGetTexEnvxv(
/* [in] */ Int32 env,
/* [in] */ Int32 pname,
/* [in] */ ArrayOf<Int32>* params,
/* [in] */ Int32 offset)
{
Begin(String("glGetTexEnviv"));
Arg(String("env"), env);
Arg(String("pname"), pname);
Arg(String("params"), ParamsToString(params));
Arg(String("offset"), offset);
End();
ECode ec = mgl11->GlGetTexEnviv(env, pname, params, offset);
CheckError();
return ec;
}
ECode GLLogWrapper::GlGetTexEnvxv(
/* [in] */ Int32 env,
/* [in] */ Int32 pname,
/* [in] */ IInt32Buffer* params)
{
Begin(String("GlGetTexEnvxvEx"));
Arg(String("env"), env);
Arg(String("pname"), pname);
Arg(String("params"), ParamsToString(params));
End();
ECode ec = mgl11->GlGetTexEnvxv(env, pname, params);
CheckError();
return ec;
}
ECode GLLogWrapper::GlGetTexParameterfv(
/* [in] */ Int32 target,
/* [in] */ Int32 pname,
/* [in] */ ArrayOf<Float>* params,
/* [in] */ Int32 offset)
{
Begin(String("glGetTexParameterfv"));
Arg(String("target"), target);
Arg(String("pname"), pname);
Arg(String("params"), ParamsToString(params));
Arg(String("offset"), offset);
End();
ECode ec = mgl11->GlGetTexParameterfv(target, pname, params, offset);
CheckError();
return ec;
}
ECode GLLogWrapper::GlGetTexParameterfv(
/* [in] */ Int32 target,
/* [in] */ Int32 pname,
/* [in] */ IFloatBuffer* params)
{
Begin(String("GlGetTexParameterfvEx"));
Arg(String("target"), target);
Arg(String("pname"), pname);
Arg(String("params"), ParamsToString(params));
End();
ECode ec = mgl11->GlGetTexParameterfv(target, pname, params);
CheckError();
return ec;
}
ECode GLLogWrapper::GlGetTexParameteriv(
/* [in] */ Int32 target,
/* [in] */ Int32 pname,
/* [in] */ ArrayOf<Int32>* params,
/* [in] */ Int32 offset)
{
Begin(String("glGetTexParameteriv"));
Arg(String("target"), target);
Arg(String("pname"), pname);
Arg(String("params"), ParamsToString(params));
Arg(String("offset"), offset);
End();
ECode ec = mgl11->GlGetTexEnviv(target, pname, params, offset);
CheckError();
return ec;
}
ECode GLLogWrapper::GlGetTexParameteriv(
/* [in] */ Int32 target,
/* [in] */ Int32 pname,
/* [in] */ IInt32Buffer* params)
{
Begin(String("GlGetTexParameterivEx"));
Arg(String("target"), target);
Arg(String("pname"), pname);
Arg(String("params"), ParamsToString(params));
End();
ECode ec = mgl11->GlGetTexParameteriv(target, pname, params);
CheckError();
return ec;
}
ECode GLLogWrapper::GlGetTexParameterxv(
/* [in] */ Int32 target,
/* [in] */ Int32 pname,
/* [in] */ ArrayOf<Int32>* params,
/* [in] */ Int32 offset)
{
Begin(String("glGetTexParameterxv"));
Arg(String("target"), target);
Arg(String("pname"), pname);
Arg(String("params"), ParamsToString(params));
Arg(String("offset"), offset);
End();
ECode ec = mgl11->GlGetTexParameterxv(target, pname, params, offset);
CheckError();
return ec;
}
ECode GLLogWrapper::GlGetTexParameterxv(
/* [in] */ Int32 target,
/* [in] */ Int32 pname,
/* [in] */ IInt32Buffer* params)
{
Begin(String("GlGetTexParameterxvEx"));
Arg(String("target"), target);
Arg(String("pname"), pname);
Arg(String("params"), ParamsToString(params));
End();
ECode ec = mgl11->GlGetTexParameterxv(target, pname, params);
CheckError();
return ec;
}
ECode GLLogWrapper::GlIsBuffer(
/* [in] */ Int32 buffer,
/* [out] */ Boolean* result)
{
VALIDATE_NOT_NULL(result)
Begin(String("glIsBuffer"));
Arg(String("buffer"), buffer);
End();
ECode ec = mgl11->GlIsBuffer(buffer, result);
CheckError();
return ec;
}
ECode GLLogWrapper::GlIsEnabled(
/* [in] */ Int32 cap,
/* [out] */ Boolean* result)
{
VALIDATE_NOT_NULL(result)
Begin(String("glIsEnabled"));
Arg(String("cap"), cap);
End();
ECode ec = mgl11->GlIsEnabled(cap, result);
CheckError();
return ec;
}
ECode GLLogWrapper::GlIsTexture(
/* [in] */ Int32 texture,
/* [out] */ Boolean* result)
{
VALIDATE_NOT_NULL(result)
Begin(String("glIsTexture"));
Arg(String("texture"), texture);
End();
ECode ec = mgl11->GlIsTexture(texture, result);
CheckError();
return ec;
}
ECode GLLogWrapper::GlNormalPointer(
/* [in] */ Int32 type,
/* [in] */ Int32 stride,
/* [in] */ Int32 offset)
{
Begin(String("GlNormalPointerEx"));
Arg(String("type"), type);
Arg(String("stride"), stride);
Arg(String("offset"), offset);
End();
return mgl11->GlNormalPointer(type, stride, offset);
}
ECode GLLogWrapper::GlPointParameterf(
/* [in] */ Int32 pname,
/* [in] */ Float param)
{
Begin(String("glPointParameterf"));
Arg(String("pname"), pname);
Arg(String("param"), param);
End();
ECode ec = mgl11->GlPointParameterf( pname, param);
CheckError();
return ec;
}
ECode GLLogWrapper::GlPointParameterfv(
/* [in] */ Int32 pname,
/* [in] */ ArrayOf<Float>* params,
/* [in] */ Int32 offset)
{
Begin(String("glPointParameterfv"));
Arg(String("pname"), pname);
Arg(String("params"), ParamsToString(params));
Arg(String("offset"), offset);
End();
ECode ec = mgl11->GlPointParameterfv(pname, params, offset);
CheckError();
return ec;
}
ECode GLLogWrapper::GlPointParameterfv(
/* [in] */ Int32 pname,
/* [in] */ IFloatBuffer* params)
{
Begin(String("GlPointParameterfvEx"));
Arg(String("pname"), pname);
Arg(String("params"), ParamsToString(params));
End();
ECode ec = mgl11->GlPointParameterfv(pname, params);
CheckError();
return ec;
}
ECode GLLogWrapper::GlPointParameterx(
/* [in] */ Int32 pname,
/* [in] */ Int32 param)
{
Begin(String("glPointParameterfv"));
Arg(String("pname"), pname);
Arg(String("param"), param);
End();
ECode ec = mgl11->GlPointParameterx( pname, param);
CheckError();
return ec;
}
ECode GLLogWrapper::GlPointParameterxv(
/* [in] */ Int32 pname,
/* [in] */ ArrayOf<Int32>* params,
/* [in] */ Int32 offset)
{
Begin(String("glPointParameterxv"));
Arg(String("pname"), pname);
Arg(String("params"), ParamsToString(params));
Arg(String("offset"), offset);
End();
ECode ec = mgl11->GlPointParameterxv(pname, params, offset);
CheckError();
return ec;
}
ECode GLLogWrapper::GlPointParameterxv(
/* [in] */ Int32 pname,
/* [in] */ IInt32Buffer* params)
{
Begin(String("GlPointParameterxvEx"));
Arg(String("pname"), pname);
Arg(String("params"), ParamsToString(params));
End();
ECode ec = mgl11->GlPointParameterxv( pname, params);
CheckError();
return ec;
}
ECode GLLogWrapper::GlPointSizePointerOES(
/* [in] */ Int32 type,
/* [in] */ Int32 stride,
/* [in] */ IBuffer* pointer)
{
Begin(String("glPointSizePointerOES"));
Arg(String("type"), type);
Arg(String("stride"), stride);
Arg(String("params"), ParamsToString(pointer));
End();
ECode ec = mgl11->GlPointSizePointerOES( type, stride, pointer);
CheckError();
return ec;
}
ECode GLLogWrapper::GlTexCoordPointer(
/* [in] */ Int32 size,
/* [in] */ Int32 type,
/* [in] */ Int32 stride,
/* [in] */ Int32 offset)
{
Begin(String("GlTexCoordPointerEx"));
Arg(String("size"), size);
Arg(String("type"), type);
Arg(String("stride"), stride);
Arg(String("offset"), offset);
End();
return mgl11->GlTexCoordPointer(size, type, stride, offset);
}
ECode GLLogWrapper::GlTexEnvi(
/* [in] */ Int32 target,
/* [in] */ Int32 pname,
/* [in] */ Int32 param)
{
Begin(String("glTexEnvi"));
Arg(String("target"), target);
Arg(String("pname"), pname);
Arg(String("param"), param);
End();
ECode ec = mgl11->GlTexEnvi(target, pname, param);
CheckError();
return ec;
}
ECode GLLogWrapper::GlTexEnviv(
/* [in] */ Int32 target,
/* [in] */ Int32 pname,
/* [in] */ ArrayOf<Int32>* params,
/* [in] */ Int32 offset)
{
Begin(String("glTexEnviv"));
Arg(String("target"), target);
Arg(String("pname"), pname);
Arg(String("params"), ParamsToString(params));
Arg(String("offset"), offset);
End();
ECode ec = mgl11->GlTexEnviv(target, pname, params, offset);
CheckError();
return ec;
}
ECode GLLogWrapper::GlTexEnviv(
/* [in] */ Int32 target,
/* [in] */ Int32 pname,
/* [in] */ IInt32Buffer* params)
{
Begin(String("GlTexEnvivEx"));
Arg(String("target"), target);
Arg(String("pname"), pname);
Arg(String("params"), ParamsToString(params));
End();
ECode ec = mgl11->GlTexEnviv( target, pname, params);
CheckError();
return ec;
}
ECode GLLogWrapper::GlTexParameteri(
/* [in] */ Int32 target,
/* [in] */ Int32 pname,
/* [in] */ Int32 param)
{
Begin(String("glTexParameterxv"));
Arg(String("target"), target);
Arg(String("pname"), pname);
Arg(String("param"), param);
End();
ECode ec = mgl11->GlTexParameteri(target, pname, param);
CheckError();
return ec;
}
ECode GLLogWrapper::GlTexParameteriv(
/* [in] */ Int32 target,
/* [in] */ Int32 pname,
/* [in] */ ArrayOf<Int32>* params,
/* [in] */ Int32 offset)
{
Begin(String("glTexParameteriv"));
Arg(String("target"), GetTextureTarget(target));
Arg(String("pname"), GetTexturePName(pname));
Arg(String("params"), 4, params, offset);
End();
ECode ec = mgl11->GlTexParameteriv(target, pname, params, offset);
CheckError();
return ec;
}
ECode GLLogWrapper::GlTexParameteriv(
/* [in] */ Int32 target,
/* [in] */ Int32 pname,
/* [in] */ IInt32Buffer* params)
{
Begin(String("GlTexParameterivEx"));
Arg(String("target"), GetTextureTarget(target));
Arg(String("pname"), GetTexturePName(pname));
Arg(String("params"), 4, params);
End();
ECode ec = mgl11->GlTexParameteriv(target, pname, params);
CheckError();
return ec;
}
ECode GLLogWrapper::GlTexParameterxv(
/* [in] */ Int32 target,
/* [in] */ Int32 pname,
/* [in] */ ArrayOf<Int32>* params,
/* [in] */ Int32 offset)
{
Begin(String("glTexParameterxv"));
Arg(String("target"), target);
Arg(String("pname"), pname);
Arg(String("params"), ParamsToString(params));
Arg(String("offset"), offset);
End();
ECode ec = mgl11->GlTexParameterxv(target, pname, params, offset);
CheckError();
return ec;
}
ECode GLLogWrapper::GlTexParameterxv(
/* [in] */ Int32 target,
/* [in] */ Int32 pname,
/* [in] */ IInt32Buffer* params)
{
Begin(String("GlTexParameterxvEx"));
Arg(String("target"), target);
Arg(String("pname"), pname);
Arg(String("params"), ParamsToString(params));
End();
ECode ec = mgl11->GlTexParameterxv(target, pname, params);
CheckError();
return ec;
}
ECode GLLogWrapper::GlVertexPointer(
/* [in] */ Int32 size,
/* [in] */ Int32 type,
/* [in] */ Int32 stride,
/* [in] */ Int32 offset)
{
Begin(String("GlVertexPointerEx"));
Arg(String("size"), size);
Arg(String("type"), type);
Arg(String("stride"), stride);
Arg(String("offset"), offset);
End();
return mgl11->GlVertexPointer(size, type, stride, offset);
}
ECode GLLogWrapper::GlCurrentPaletteMatrixOES(
/* [in] */ Int32 matrixpaletteindex)
{
Begin(String("glCurrentPaletteMatrixOES"));
Arg(String("matrixpaletteindex"), matrixpaletteindex);
End();
ECode ec = mgl11Ext->GlCurrentPaletteMatrixOES(matrixpaletteindex);
CheckError();
return ec;
}
ECode GLLogWrapper::GlDrawTexfOES(
/* [in] */ Float x,
/* [in] */ Float y,
/* [in] */ Float z,
/* [in] */ Float width,
/* [in] */ Float height)
{
Begin(String("glDrawTexfOES"));
Arg(String("x"), x);
Arg(String("y"), y);
Arg(String("z"), z);
Arg(String("width"), width);
Arg(String("height"), height);
End();
ECode ec = mgl11Ext->GlDrawTexfOES(x, y, z, width, height);
CheckError();
return ec;
}
ECode GLLogWrapper::GlDrawTexfvOES(
/* [in] */ ArrayOf<Float>* coords,
/* [in] */ Int32 offset)
{
Begin(String("glDrawTexfvOES"));
Arg(String("coords"), 5, coords, offset);
Arg(String("offset"), offset);
End();
ECode ec = mgl11Ext->GlDrawTexfvOES(coords, offset);
CheckError();
return ec;
}
ECode GLLogWrapper::GlDrawTexfvOES(
/* [in] */ IFloatBuffer* coords)
{
Begin(String("GlDrawTexfvOESEx"));
Arg(String("coords"), 5, coords);
End();
ECode ec = mgl11Ext->GlDrawTexfvOES(coords);
CheckError();
return ec;
}
ECode GLLogWrapper::GlDrawTexiOES(
/* [in] */ Int32 x,
/* [in] */ Int32 y,
/* [in] */ Int32 z,
/* [in] */ Int32 width,
/* [in] */ Int32 height)
{
Begin(String("glDrawTexiOES"));
Arg(String("x"), x);
Arg(String("y"), y);
Arg(String("z"), z);
Arg(String("width"), width);
Arg(String("height"), height);
End();
ECode ec = mgl11Ext->GlDrawTexiOES(x, y, z, width, height);
CheckError();
return ec;
}
ECode GLLogWrapper::GlDrawTexivOES(
/* [in] */ ArrayOf<Int32>* coords,
/* [in] */ Int32 offset)
{
Begin(String("glDrawTexivOES"));
Arg(String("coords"), 5, coords, offset);
Arg(String("offset"), offset);
End();
ECode ec = mgl11Ext->GlDrawTexivOES(coords, offset);
CheckError();
return ec;
}
ECode GLLogWrapper::GlDrawTexivOES(
/* [in] */ IInt32Buffer* coords)
{
Begin(String("GlDrawTexivOESEx"));
Arg(String("coords"), 5, coords);
End();
ECode ec = mgl11Ext->GlDrawTexivOES(coords);
CheckError();
return ec;
}
ECode GLLogWrapper::GlDrawTexsOES(
/* [in] */ Int16 x,
/* [in] */ Int16 y,
/* [in] */ Int16 z,
/* [in] */ Int16 width,
/* [in] */ Int16 height)
{
Begin(String("glDrawTexsOES"));
Arg(String("x"), x);
Arg(String("y"), y);
Arg(String("z"), z);
Arg(String("width"), width);
Arg(String("height"), height);
End();
ECode ec = mgl11Ext->GlDrawTexsOES(x, y, z, width, height);
CheckError();
return ec;
}
ECode GLLogWrapper::GlDrawTexsvOES(
/* [in] */ ArrayOf<Int16>* coords,
/* [in] */ Int32 offset)
{
Begin(String("glDrawTexsvOES"));
Arg(String("coords"), 5, coords, offset);
Arg(String("offset"), offset);
End();
ECode ec = mgl11Ext->GlDrawTexsvOES(coords, offset);
CheckError();
return ec;
}
ECode GLLogWrapper::GlDrawTexsvOES(
/* [in] */ IInt16Buffer* coords)
{
Begin(String("GlDrawTexsvOESEx"));
Arg(String("coords"), 5, coords);
End();
ECode ec = mgl11Ext->GlDrawTexsvOES(coords);
CheckError();
return ec;
}
ECode GLLogWrapper::GlDrawTexxOES(
/* [in] */ Int32 x,
/* [in] */ Int32 y,
/* [in] */ Int32 z,
/* [in] */ Int32 width,
/* [in] */ Int32 height)
{
Begin(String("glDrawTexxOES"));
Arg(String("x"), x);
Arg(String("y"), y);
Arg(String("z"), z);
Arg(String("width"), width);
Arg(String("height"), height);
End();
ECode ec = mgl11Ext->GlDrawTexxOES(x, y, z, width, height);
CheckError();
return ec;
}
ECode GLLogWrapper::GlDrawTexxvOES(
/* [in] */ ArrayOf<Int32>* coords,
/* [in] */ Int32 offset)
{
Begin(String("glDrawTexxvOES"));
Arg(String("coords"), 5, coords, offset);
Arg(String("offset"), offset);
End();
ECode ec = mgl11Ext->GlDrawTexxvOES(coords, offset);
CheckError();
return ec;
}
ECode GLLogWrapper::GlDrawTexxvOES(
/* [in] */ IInt32Buffer* coords)
{
Begin(String("GlDrawTexxvOESEx"));
Arg(String("coords"), 5, coords);
End();
ECode ec = mgl11Ext->GlDrawTexxvOES(coords);
CheckError();
return ec;
}
ECode GLLogWrapper::GlLoadPaletteFromModelViewMatrixOES()
{
Begin(String("glLoadPaletteFromModelViewMatrixOES"));
End();
ECode ec = mgl11Ext->GlLoadPaletteFromModelViewMatrixOES();
CheckError();
return ec;
}
ECode GLLogWrapper::GlMatrixIndexPointerOES(
/* [in] */ Int32 size,
/* [in] */ Int32 type,
/* [in] */ Int32 stride,
/* [in] */ IBuffer* pointer)
{
Begin(String("glMatrixIndexPointerOES"));
ArgPointer(size, type, stride, pointer);
End();
ECode ec = mgl11Ext->GlMatrixIndexPointerOES(size, type, stride, pointer);
CheckError();
return ec;
}
ECode GLLogWrapper::GlMatrixIndexPointerOES(
/* [in] */ Int32 size,
/* [in] */ Int32 type,
/* [in] */ Int32 stride,
/* [in] */ Int32 offset)
{
Begin(String("GlMatrixIndexPointerOESEx"));
Arg(String("size"), size);
Arg(String("type"), type);
Arg(String("stride"), stride);
Arg(String("offset"), offset);
End();
ECode ec = mgl11Ext->GlMatrixIndexPointerOES(size, type, stride, offset);
CheckError();
return ec;
}
ECode GLLogWrapper::GlWeightPointerOES(
/* [in] */ Int32 size,
/* [in] */ Int32 type,
/* [in] */ Int32 stride,
/* [in] */ IBuffer* pointer)
{
Begin(String("glWeightPointerOES"));
ArgPointer(size, type, stride, pointer);
End();
ECode ec = mgl11Ext->GlWeightPointerOES(size, type, stride, pointer);
CheckError();
return ec;
}
ECode GLLogWrapper::GlWeightPointerOES(
/* [in] */ Int32 size,
/* [in] */ Int32 type,
/* [in] */ Int32 stride,
/* [in] */ Int32 offset)
{
Begin(String("GlWeightPointerOESEx"));
Arg(String("size"), size);
Arg(String("type"), type);
Arg(String("stride"), stride);
Arg(String("offset"), offset);
End();
ECode ec = mgl11Ext->GlWeightPointerOES(size, type, stride, offset);
CheckError();
return ec;
}
ECode GLLogWrapper::GlBindFramebufferOES(
/* [in] */ Int32 target,
/* [in] */ Int32 framebuffer)
{
Begin(String("glBindFramebufferOES"));
Arg(String("target"), target);
Arg(String("framebuffer"), framebuffer);
End();
ECode ec = mgl11ExtensionPack->GlBindFramebufferOES(target, framebuffer);
CheckError();
return ec;
}
ECode GLLogWrapper::GlBindRenderbufferOES(
/* [in] */ Int32 target,
/* [in] */ Int32 renderbuffer)
{
Begin(String("glBindRenderbufferOES"));
Arg(String("target"), target);
Arg(String("renderbuffer"), renderbuffer);
End();
ECode ec = mgl11ExtensionPack->GlBindRenderbufferOES(target, renderbuffer);
CheckError();
return ec;
}
ECode GLLogWrapper::GlBlendEquation(
/* [in] */ Int32 mode)
{
Begin(String("glBlendEquation"));
Arg(String("mode"), mode);
End();
ECode ec = mgl11ExtensionPack->GlBlendEquation(mode);
CheckError();
return ec;
}
ECode GLLogWrapper::GlBlendEquationSeparate(
/* [in] */ Int32 modeRGB,
/* [in] */ Int32 modeAlpha)
{
Begin(String("glBlendEquationSeparate"));
Arg(String("modeRGB"), modeRGB);
Arg(String("modeAlpha"), modeAlpha);
End();
ECode ec = mgl11ExtensionPack->GlBlendEquationSeparate(modeRGB, modeAlpha);
CheckError();
return ec;
}
ECode GLLogWrapper::GlBlendFuncSeparate(
/* [in] */ Int32 srcRGB,
/* [in] */ Int32 dstRGB,
/* [in] */ Int32 srcAlpha,
/* [in] */ Int32 dstAlpha)
{
Begin(String("glBlendFuncSeparate"));
Arg(String("srcRGB"), srcRGB);
Arg(String("dstRGB"), dstRGB);
Arg(String("srcAlpha"), srcAlpha);
Arg(String("dstAlpha"), dstAlpha);
End();
ECode ec = mgl11ExtensionPack->GlBlendFuncSeparate(srcRGB, dstRGB, srcAlpha, dstAlpha);
CheckError();
return ec;
}
ECode GLLogWrapper::GlCheckFramebufferStatusOES(
/* [in] */ Int32 target,
/* [out] */ Int32* status)
{
VALIDATE_NOT_NULL(status)
Begin(String("glCheckFramebufferStatusOES"));
Arg(String("target"), target);
End();
ECode ec = mgl11ExtensionPack->GlCheckFramebufferStatusOES(target, status);
CheckError();
return ec;
}
ECode GLLogWrapper::GlDeleteFramebuffersOES(
/* [in] */ Int32 n,
/* [in] */ ArrayOf<Int32>* framebuffers,
/* [in] */ Int32 offset)
{
Begin(String("glDeleteFramebuffersOES"));
Arg(String("n"), n);
Arg(String("framebuffers"), ParamsToString(framebuffers));
Arg(String("offset"), offset);
End();
ECode ec = mgl11ExtensionPack->GlDeleteFramebuffersOES(n, framebuffers, offset);
CheckError();
return ec;
}
ECode GLLogWrapper::GlDeleteFramebuffersOES(
/* [in] */ Int32 n,
/* [in] */ IInt32Buffer* framebuffers)
{
Begin(String("GlDeleteFramebuffersOESEx"));
Arg(String("n"), n);
Arg(String("framebuffers"), ParamsToString(framebuffers));
End();
ECode ec = mgl11ExtensionPack->GlDeleteFramebuffersOES(n, framebuffers);
CheckError();
return ec;
}
ECode GLLogWrapper::GlDeleteRenderbuffersOES(
/* [in] */ Int32 n,
/* [in] */ ArrayOf<Int32>* renderbuffers,
/* [in] */ Int32 offset)
{
Begin(String("glDeleteRenderbuffersOES"));
Arg(String("n"), n);
Arg(String("renderbuffers"), ParamsToString(renderbuffers));
Arg(String("offset"), offset);
End();
ECode ec = mgl11ExtensionPack->GlDeleteRenderbuffersOES(n, renderbuffers, offset);
CheckError();
return ec;
}
ECode GLLogWrapper::GlDeleteRenderbuffersOES(
/* [in] */ Int32 n,
/* [in] */ IInt32Buffer* renderbuffers)
{
Begin(String("GlDeleteRenderbuffersOESEx"));
Arg(String("n"), n);
Arg(String("renderbuffers"), ParamsToString(renderbuffers));
End();
ECode ec = mgl11ExtensionPack->GlDeleteRenderbuffersOES(n, renderbuffers);
CheckError();
return ec;
}
ECode GLLogWrapper::GlFramebufferRenderbufferOES(
/* [in] */ Int32 target,
/* [in] */ Int32 attachment,
/* [in] */ Int32 renderbuffertarget,
/* [in] */ Int32 renderbuffer)
{
Begin(String("glFramebufferRenderbufferOES"));
Arg(String("target"), target);
Arg(String("attachment"), attachment);
Arg(String("renderbuffertarget"), renderbuffertarget);
Arg(String("renderbuffer"), renderbuffer);
End();
ECode ec = mgl11ExtensionPack->GlFramebufferRenderbufferOES(target, attachment, renderbuffertarget, renderbuffer);
CheckError();
return ec;
}
ECode GLLogWrapper::GlFramebufferTexture2DOES(
/* [in] */ Int32 target,
/* [in] */ Int32 attachment,
/* [in] */ Int32 textarget,
/* [in] */ Int32 texture,
/* [in] */ Int32 level)
{
Begin(String("glFramebufferTexture2DOES"));
Arg(String("target"), target);
Arg(String("attachment"), attachment);
Arg(String("textarget"), textarget);
Arg(String("texture"), texture);
Arg(String("level"), level);
End();
ECode ec = mgl11ExtensionPack->GlFramebufferTexture2DOES(target, attachment, textarget, texture, level);
CheckError();
return ec;
}
ECode GLLogWrapper::GlGenerateMipmapOES(
/* [in] */ Int32 target)
{
Begin(String("glGenerateMipmapOES"));
Arg(String("target"), target);
End();
ECode ec = mgl11ExtensionPack->GlGenerateMipmapOES(target);
CheckError();
return ec;
}
ECode GLLogWrapper::GlGenFramebuffersOES(
/* [in] */ Int32 n,
/* [in] */ ArrayOf<Int32>* framebuffers,
/* [in] */ Int32 offset)
{
Begin(String("glGenFramebuffersOES"));
Arg(String("n"), n);
Arg(String("framebuffers"), ParamsToString(framebuffers));
Arg(String("offset"), offset);
End();
ECode ec = mgl11ExtensionPack->GlGenFramebuffersOES(n, framebuffers, offset);
CheckError();
return ec;
}
ECode GLLogWrapper::GlGenFramebuffersOES(
/* [in] */ Int32 n,
/* [in] */ IInt32Buffer* framebuffers)
{
Begin(String("GlGenFramebuffersOESEx"));
Arg(String("n"), n);
Arg(String("framebuffers"), ParamsToString(framebuffers));
End();
ECode ec = mgl11ExtensionPack->GlGenFramebuffersOES(n, framebuffers);
CheckError();
return ec;
}
ECode GLLogWrapper::GlGenRenderbuffersOES(
/* [in] */ Int32 n,
/* [in] */ ArrayOf<Int32>* renderbuffers,
/* [in] */ Int32 offset)
{
Begin(String("glGenRenderbuffersOES"));
Arg(String("n"), n);
Arg(String("renderbuffers"), ParamsToString(renderbuffers));
Arg(String("offset"), offset);
End();
ECode ec = mgl11ExtensionPack->GlGenRenderbuffersOES(n, renderbuffers, offset);
CheckError();
return ec;
}
ECode GLLogWrapper::GlGenRenderbuffersOES(
/* [in] */ Int32 n,
/* [in] */ IInt32Buffer* renderbuffers)
{
Begin(String("GlGenRenderbuffersOESEx"));
Arg(String("n"), n);
Arg(String("renderbuffers"), ParamsToString(renderbuffers));
End();
ECode ec = mgl11ExtensionPack->GlGenRenderbuffersOES(n, renderbuffers);
CheckError();
return ec;
}
ECode GLLogWrapper::GlGetFramebufferAttachmentParameterivOES(
/* [in] */ Int32 target,
/* [in] */ Int32 attachment,
/* [in] */ Int32 pname,
/* [in] */ ArrayOf<Int32>* params,
/* [in] */ Int32 offset)
{
Begin(String("glGetFramebufferAttachmentParameterivOES"));
Arg(String("target"), target);
Arg(String("attachment"), attachment);
Arg(String("pname"), pname);
Arg(String("params"), ParamsToString(params));
Arg(String("offset"), offset);
End();
ECode ec = mgl11ExtensionPack->GlGetFramebufferAttachmentParameterivOES(target, attachment, pname, params, offset);
CheckError();
return ec;
}
ECode GLLogWrapper::GlGetFramebufferAttachmentParameterivOES(
/* [in] */ Int32 target,
/* [in] */ Int32 attachment,
/* [in] */ Int32 pname,
/* [in] */ IInt32Buffer* params)
{
Begin(String("GlGetFramebufferAttachmentParameterivOESEx"));
Arg(String("target"), target);
Arg(String("attachment"), attachment);
Arg(String("pname"), pname);
Arg(String("params"), ParamsToString(params));
End();
ECode ec = mgl11ExtensionPack->GlGetFramebufferAttachmentParameterivOES(target, attachment, pname, params);
CheckError();
return ec;
}
ECode GLLogWrapper::GlGetRenderbufferParameterivOES(
/* [in] */ Int32 target,
/* [in] */ Int32 pname,
/* [in] */ ArrayOf<Int32>* params,
/* [in] */ Int32 offset)
{
Begin(String("glGetRenderbufferParameterivOES"));
Arg(String("target"), target);
Arg(String("pname"), pname);
Arg(String("params"), ParamsToString(params));
Arg(String("offset"), offset);
End();
ECode ec = mgl11ExtensionPack->GlGetRenderbufferParameterivOES(target, pname, params, offset);
CheckError();
return ec;
}
ECode GLLogWrapper::GlGetRenderbufferParameterivOES(
/* [in] */ Int32 target,
/* [in] */ Int32 pname,
/* [in] */ IInt32Buffer* params)
{
Begin(String("GlGetRenderbufferParameterivOESEx"));
Arg(String("target"), target);
Arg(String("pname"), pname);
Arg(String("params"), ParamsToString(params));
End();
ECode ec = mgl11ExtensionPack->GlGetRenderbufferParameterivOES(target, pname, params);
CheckError();
return ec;
}
ECode GLLogWrapper::GlGetTexGenfv(
/* [in] */ Int32 coord,
/* [in] */ Int32 pname,
/* [in] */ ArrayOf<Float>* params,
/* [in] */ Int32 offset)
{
Begin(String("glGetTexGenfv"));
Arg(String("coord"), coord);
Arg(String("pname"), pname);
Arg(String("params"), ParamsToString(params));
Arg(String("offset"), offset);
End();
ECode ec = mgl11ExtensionPack->GlGetTexGenfv(coord, pname, params, offset);
CheckError();
return ec;
}
ECode GLLogWrapper::GlGetTexGenfv(
/* [in] */ Int32 coord,
/* [in] */ Int32 pname,
/* [in] */ IFloatBuffer* params)
{
Begin(String("GlGetTexGenfvEx"));
Arg(String("coord"), coord);
Arg(String("pname"), pname);
Arg(String("params"), ParamsToString(params));
End();
ECode ec = mgl11ExtensionPack->GlGetTexGenfv(coord, pname, params);
CheckError();
return ec;
}
ECode GLLogWrapper::GlGetTexGeniv(
/* [in] */ Int32 coord,
/* [in] */ Int32 pname,
/* [in] */ ArrayOf<Int32>* params,
/* [in] */ Int32 offset)
{
Begin(String("glGetTexGeniv"));
Arg(String("coord"), coord);
Arg(String("pname"), pname);
Arg(String("params"), ParamsToString(params));
Arg(String("offset"), offset);
End();
ECode ec = mgl11ExtensionPack->GlGetTexGeniv(coord, pname, params, offset);
CheckError();
return ec;
}
ECode GLLogWrapper::GlGetTexGeniv(
/* [in] */ Int32 coord,
/* [in] */ Int32 pname,
/* [in] */ IInt32Buffer* params)
{
Begin(String("GlGetTexGenivEx"));
Arg(String("coord"), coord);
Arg(String("pname"), pname);
Arg(String("params"), ParamsToString(params));
End();
ECode ec = mgl11ExtensionPack->GlGetTexGeniv(coord, pname, params);
CheckError();
return ec;
}
ECode GLLogWrapper::GlGetTexGenxv(
/* [in] */ Int32 coord,
/* [in] */ Int32 pname,
/* [in] */ ArrayOf<Int32>* params,
/* [in] */ Int32 offset)
{
Begin(String("glGetTexGenxv"));
Arg(String("coord"), coord);
Arg(String("pname"), pname);
Arg(String("params"), ParamsToString(params));
Arg(String("offset"), offset);
End();
ECode ec = mgl11ExtensionPack->GlGetTexGenxv(coord, pname, params, offset);
CheckError();
return ec;
}
ECode GLLogWrapper::GlGetTexGenxv(
/* [in] */ Int32 coord,
/* [in] */ Int32 pname,
/* [in] */ IInt32Buffer* params)
{
Begin(String("GlGetTexGenxvEx"));
Arg(String("coord"), coord);
Arg(String("pname"), pname);
Arg(String("params"), ParamsToString(params));
End();
ECode ec = mgl11ExtensionPack->GlGetTexGenxv(coord, pname, params);
CheckError();
return ec;
}
ECode GLLogWrapper::GlIsFramebufferOES(
/* [in] */ Int32 framebuffer,
/* [out] */ Boolean* result)
{
VALIDATE_NOT_NULL(result)
Begin(String("glIsFramebufferOES"));
Arg(String("framebuffer"), framebuffer);
End();
ECode ec = mgl11ExtensionPack->GlIsFramebufferOES(framebuffer, result);
CheckError();
return ec;
}
ECode GLLogWrapper::GlIsRenderbufferOES(
/* [in] */ Int32 renderbuffer,
/* [out] */ Boolean* result)
{
VALIDATE_NOT_NULL(result)
Begin(String("glIsRenderbufferOES"));
Arg(String("renderbuffer"), renderbuffer);
End();
ECode ec = mgl11ExtensionPack->GlIsRenderbufferOES(renderbuffer, result);
CheckError();
return ec;
}
ECode GLLogWrapper::GlRenderbufferStorageOES(
/* [in] */ Int32 target,
/* [in] */ Int32 internalformat,
/* [in] */ Int32 width,
/* [in] */ Int32 height)
{
Begin(String("glRenderbufferStorageOES"));
Arg(String("target"), target);
Arg(String("internalformat"), internalformat);
Arg(String("width"), width);
Arg(String("height"), height);
End();
ECode ec = mgl11ExtensionPack->GlRenderbufferStorageOES(target, internalformat, width, height);
CheckError();
return ec;
}
ECode GLLogWrapper::GlTexGenf(
/* [in] */ Int32 coord,
/* [in] */ Int32 pname,
/* [in] */ Float param)
{
Begin(String("glTexGenf"));
Arg(String("coord"), coord);
Arg(String("pname"), pname);
Arg(String("param"), param);
End();
ECode ec = mgl11ExtensionPack->GlTexGenf(coord, pname, param);
CheckError();
return ec;
}
ECode GLLogWrapper::GlTexGenfv(
/* [in] */ Int32 coord,
/* [in] */ Int32 pname,
/* [in] */ ArrayOf<Float>* params,
/* [in] */ Int32 offset)
{
Begin(String("glTexGenfv"));
Arg(String("coord"), coord);
Arg(String("pname"), pname);
Arg(String("params"), ParamsToString(params));
Arg(String("offset"), offset);
End();
ECode ec = mgl11ExtensionPack->GlTexGenfv(coord, pname, params, offset);
CheckError();
return ec;
}
ECode GLLogWrapper::GlTexGenfv(
/* [in] */ Int32 coord,
/* [in] */ Int32 pname,
/* [in] */ IFloatBuffer* params)
{
Begin(String("GlTexGenfvEx"));
Arg(String("coord"), coord);
Arg(String("pname"), pname);
Arg(String("params"), ParamsToString(params));
End();
ECode ec = mgl11ExtensionPack->GlTexGenfv(coord, pname, params);
CheckError();
return ec;
}
ECode GLLogWrapper::GlTexGeni(
/* [in] */ Int32 coord,
/* [in] */ Int32 pname,
/* [in] */ Int32 param)
{
Begin(String("glTexGeni"));
Arg(String("coord"), coord);
Arg(String("pname"), pname);
Arg(String("param"), param);
End();
ECode ec = mgl11ExtensionPack->GlTexGeni(coord, pname, param);
CheckError();
return ec;
}
ECode GLLogWrapper::GlTexGeniv(
/* [in] */ Int32 coord,
/* [in] */ Int32 pname,
/* [in] */ ArrayOf<Int32>* params,
/* [in] */ Int32 offset)
{
Begin(String("glTexGeniv"));
Arg(String("coord"), coord);
Arg(String("pname"), pname);
Arg(String("params"), ParamsToString(params));
Arg(String("offset"), offset);
End();
ECode ec = mgl11ExtensionPack->GlTexGeniv(coord, pname, params, offset);
CheckError();
return ec;
}
ECode GLLogWrapper::GlTexGeniv(
/* [in] */ Int32 coord,
/* [in] */ Int32 pname,
/* [in] */ IInt32Buffer* params)
{
Begin(String("GlTexGenivEx"));
Arg(String("coord"), coord);
Arg(String("pname"), pname);
Arg(String("params"), ParamsToString(params));
End();
ECode ec = mgl11ExtensionPack->GlTexGeniv(coord, pname, params);
CheckError();
return ec;
}
ECode GLLogWrapper::GlTexGenx(
/* [in] */ Int32 coord,
/* [in] */ Int32 pname,
/* [in] */ Int32 param)
{
Begin(String("glTexGenx"));
Arg(String("coord"), coord);
Arg(String("pname"), pname);
Arg(String("param"), param);
End();
ECode ec = mgl11ExtensionPack->GlTexGenx(coord, pname, param);
CheckError();
return ec;
}
ECode GLLogWrapper::GlTexGenxv(
/* [in] */ Int32 coord,
/* [in] */ Int32 pname,
/* [in] */ ArrayOf<Int32>* params,
/* [in] */ Int32 offset)
{
Begin(String("glTexGenxv"));
Arg(String("coord"), coord);
Arg(String("pname"), pname);
Arg(String("params"), ParamsToString(params));
Arg(String("offset"), offset);
End();
ECode ec = mgl11ExtensionPack->GlTexGenxv(coord, pname, params, offset);
CheckError();
return ec;
}
ECode GLLogWrapper::GlTexGenxv(
/* [in] */ Int32 coord,
/* [in] */ Int32 pname,
/* [in] */ IInt32Buffer* params)
{
Begin(String("GlTexGenxvEx"));
Arg(String("coord"), coord);
Arg(String("pname"), pname);
Arg(String("params"), ParamsToString(params));
End();
ECode ec = mgl11ExtensionPack->GlTexGenxv(coord, pname, params);
CheckError();
return ec;
}
template<typename T>
String GLLogWrapper::TranArrayToString(
/* [in] */ ArrayOf<T>* array)
{
StringBuilder bd;
Int32 len = array->GetLength();
for(Int32 i = 0; i < len; i++)
{
bd += (*array)[i];
bd += ' ';
}
return bd.ToString();
}
template<typename T>
String GLLogWrapper::ParamsToString(
/* [in] */ ArrayOf<T>* array)
{
return TranArrayToString(array);
}
template<class T>
String GLLogWrapper::ParamsToString(
/* [in] */ T* buf)
{
IObject* obj = IObject::Probe(buf);
String str;
obj->ToString(&str);
return str;
}
} // namespace Opengl
} // namespace Droid
} // namespace Elastos
| 25.646227 | 119 | 0.599184 | [
"model"
] |
29343f6e6c04d96081962b219c40fc76b23859d9 | 23,084 | hpp | C++ | src/sparse/KokkosSparse_gauss_seidel_handle.hpp | kuberry/kokkos-kernels | 30be76be52f1d62f9b5798984674ad46a59e5070 | [
"BSD-3-Clause"
] | null | null | null | src/sparse/KokkosSparse_gauss_seidel_handle.hpp | kuberry/kokkos-kernels | 30be76be52f1d62f9b5798984674ad46a59e5070 | [
"BSD-3-Clause"
] | null | null | null | src/sparse/KokkosSparse_gauss_seidel_handle.hpp | kuberry/kokkos-kernels | 30be76be52f1d62f9b5798984674ad46a59e5070 | [
"BSD-3-Clause"
] | null | null | null | /*
//@HEADER
// ************************************************************************
//
// KokkosKernels 0.9: Linear Algebra and Graph Kernels
// Copyright 2017 Sandia Corporation
//
// Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
// the U.S. Government retains certain rights in this software.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// 3. Neither the name of the Corporation nor the names of the
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY SANDIA CORPORATION "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 SANDIA CORPORATION OR THE
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Questions? Contact Siva Rajamanickam (srajama@sandia.gov)
//
// ************************************************************************
//@HEADER
*/
#include <Kokkos_MemoryTraits.hpp>
#include <Kokkos_Core.hpp>
#include <KokkosKernels_Utils.hpp>
#ifndef _GAUSSSEIDELHANDLE_HPP
#define _GAUSSSEIDELHANDLE_HPP
//#define VERBOSE
namespace KokkosSparse{
enum GSAlgorithm{GS_DEFAULT, GS_PERMUTED, GS_TEAM, GS_CLUSTER};
enum ClusteringAlgorithm{CLUSTER_DEFAULT, CLUSTER_BALLOON, CLUSTER_CUTHILL_MCKEE, CLUSTER_DO_NOTHING, NUM_CLUSTERING_ALGORITHMS};
inline const char* getClusterAlgoName(ClusteringAlgorithm ca)
{
switch(ca)
{
case CLUSTER_DEFAULT:
return "Default";
case CLUSTER_BALLOON:
return "Balloon";
case CLUSTER_CUTHILL_MCKEE:
return "Cuthill-McKee";
case CLUSTER_DO_NOTHING:
return "No-op";
default:;
}
return "INVALID CLUSTERING ALGORITHM";
}
template <class size_type_, class lno_t_, class scalar_t_,
class ExecutionSpace,
class TemporaryMemorySpace,
class PersistentMemorySpace>
class GaussSeidelHandle{
public:
typedef ExecutionSpace HandleExecSpace;
typedef TemporaryMemorySpace HandleTempMemorySpace;
typedef PersistentMemorySpace HandlePersistentMemorySpace;
typedef typename std::remove_const<size_type_>::type size_type;
typedef const size_type const_size_type;
typedef typename std::remove_const<lno_t_>::type nnz_lno_t;
typedef const nnz_lno_t const_nnz_lno_t;
typedef typename std::remove_const<scalar_t_>::type nnz_scalar_t;
typedef const nnz_scalar_t const_nnz_scalar_t;
typedef typename Kokkos::View<size_type *, HandleTempMemorySpace> row_lno_temp_work_view_t;
typedef typename Kokkos::View<size_type *, HandlePersistentMemorySpace> row_lno_persistent_work_view_t;
typedef typename row_lno_persistent_work_view_t::HostMirror row_lno_persistent_work_host_view_t; //Host view type
typedef typename Kokkos::View<nnz_scalar_t *, HandleTempMemorySpace> scalar_temp_work_view_t;
typedef typename Kokkos::View<nnz_scalar_t *, HandlePersistentMemorySpace> scalar_persistent_work_view_t;
typedef typename scalar_persistent_work_view_t::HostMirror scalar_persistent_work_host_view_t; //Host view type
typedef typename Kokkos::View<nnz_lno_t *, HandleTempMemorySpace> nnz_lno_temp_work_view_t;
typedef typename Kokkos::View<nnz_lno_t *, HandlePersistentMemorySpace> nnz_lno_persistent_work_view_t;
typedef typename nnz_lno_persistent_work_view_t::HostMirror nnz_lno_persistent_work_host_view_t; //Host view type
protected:
GSAlgorithm algorithm_type;
nnz_lno_persistent_work_host_view_t color_xadj;
nnz_lno_persistent_work_view_t color_adj;
nnz_lno_t numColors;
bool called_symbolic;
bool called_numeric;
int suggested_vector_size;
int suggested_team_size;
public:
/**
* \brief Default constructor.
*/
GaussSeidelHandle(GSAlgorithm gs) :
algorithm_type(gs),
color_xadj(), color_adj(), numColors(0),
called_symbolic(false), called_numeric(false),
suggested_vector_size(0), suggested_team_size(0)
{}
virtual ~GaussSeidelHandle() = default;
//getters
GSAlgorithm get_algorithm_type() const {return this->algorithm_type;}
virtual bool is_owner_of_coloring() const {return false;}
nnz_lno_persistent_work_host_view_t get_color_xadj() const {
return this->color_xadj;
}
nnz_lno_persistent_work_view_t get_color_adj() const {
return this->color_adj;
}
nnz_lno_t get_num_colors() const {
return this->numColors;
}
bool is_symbolic_called() const {
return this->called_symbolic;
}
bool is_numeric_called() const {
return this->called_numeric;
}
//setters
void set_algorithm_type(const GSAlgorithm sgs_algo){
this->algorithm_type = sgs_algo;
this->called_symbolic = false;
}
void set_call_symbolic(bool call = true) {
this->called_symbolic = call;
}
void set_call_numeric(bool call = true) {
this->called_numeric = call;
}
void set_color_xadj(const nnz_lno_persistent_work_host_view_t &color_xadj_) {
this->color_xadj = color_xadj_;
}
void set_color_adj(const nnz_lno_persistent_work_view_t &color_adj_) {
this->color_adj = color_adj_;
}
void set_num_colors(const nnz_lno_t &numColors_) {
this->numColors = numColors_;
}
void vector_team_size(
int max_allowed_team_size,
int &suggested_vector_size_, //output
int &suggested_team_size_, //output
size_type nr, size_type nnz){
if (this->suggested_team_size && this->suggested_vector_size) {
suggested_vector_size_ = this->suggested_vector_size;
suggested_team_size_ = this->suggested_team_size;
return;
}
else {
#ifdef KOKKOS_ENABLE_DEPRECATED_CODE
KokkosKernels::Impl::get_suggested_vector_team_size<size_type, ExecutionSpace>(max_allowed_team_size, suggested_vector_size_, suggested_team_size_, nr, nnz);
#else
KokkosKernels::Impl::get_suggested_vector_size<size_type, ExecutionSpace>(suggested_vector_size_, nr, nnz);
KokkosKernels::Impl::get_suggested_team_size<ExecutionSpace>(max_allowed_team_size, suggested_vector_size_, suggested_team_size_);
#endif
this->suggested_team_size = suggested_vector_size_;
this->suggested_vector_size = suggested_vector_size_;
}
}
};
template <class size_type_, class lno_t_, class scalar_t_,
class ExecutionSpace,
class TemporaryMemorySpace,
class PersistentMemorySpace>
class PointGaussSeidelHandle
: public GaussSeidelHandle<size_type_, lno_t_, scalar_t_, ExecutionSpace, TemporaryMemorySpace, PersistentMemorySpace>
{
public:
typedef GaussSeidelHandle<size_type_, lno_t_, scalar_t_, ExecutionSpace, TemporaryMemorySpace, PersistentMemorySpace> GSHandle;
typedef ExecutionSpace HandleExecSpace;
typedef TemporaryMemorySpace HandleTempMemorySpace;
typedef PersistentMemorySpace HandlePersistentMemorySpace;
typedef typename std::remove_const<size_type_>::type size_type;
typedef const size_type const_size_type;
typedef typename std::remove_const<lno_t_>::type nnz_lno_t;
typedef const nnz_lno_t const_nnz_lno_t;
typedef typename std::remove_const<scalar_t_>::type nnz_scalar_t;
typedef const nnz_scalar_t const_nnz_scalar_t;
typedef typename Kokkos::View<size_type *, HandleTempMemorySpace> row_lno_temp_work_view_t;
typedef typename Kokkos::View<size_type *, HandlePersistentMemorySpace> row_lno_persistent_work_view_t;
typedef typename row_lno_persistent_work_view_t::HostMirror row_lno_persistent_work_host_view_t; //Host view type
typedef typename Kokkos::View<nnz_scalar_t *, HandleTempMemorySpace> scalar_temp_work_view_t;
typedef typename Kokkos::View<nnz_scalar_t *, HandlePersistentMemorySpace> scalar_persistent_work_view_t;
typedef typename Kokkos::View<nnz_scalar_t **, Kokkos::LayoutLeft, HandlePersistentMemorySpace> scalar_persistent_work_view2d_t;
typedef typename scalar_persistent_work_view_t::HostMirror scalar_persistent_work_host_view_t; //Host view type
typedef typename Kokkos::View<nnz_lno_t *, HandleTempMemorySpace> nnz_lno_temp_work_view_t;
typedef typename Kokkos::View<nnz_lno_t *, HandlePersistentMemorySpace> nnz_lno_persistent_work_view_t;
typedef typename nnz_lno_persistent_work_view_t::HostMirror nnz_lno_persistent_work_host_view_t; //Host view type
private:
row_lno_persistent_work_view_t permuted_xadj;
nnz_lno_persistent_work_view_t permuted_adj;
scalar_persistent_work_view_t permuted_adj_vals;
nnz_lno_persistent_work_view_t old_to_new_map;
scalar_persistent_work_view2d_t permuted_y_vector;
scalar_persistent_work_view2d_t permuted_x_vector;
scalar_persistent_work_view_t permuted_inverse_diagonal;
nnz_lno_t block_size; //this is for block sgs
nnz_lno_t max_nnz_input_row;
nnz_lno_t num_values_in_l1, num_values_in_l2, num_big_rows;
size_t level_1_mem, level_2_mem;
bool owner_of_coloring;
public:
/**
* \brief Default constructor.
*/
PointGaussSeidelHandle(GSAlgorithm gs = GS_DEFAULT) :
GSHandle(gs),
permuted_xadj(), permuted_adj(), permuted_adj_vals(), old_to_new_map(),
permuted_y_vector(), permuted_x_vector(),
permuted_inverse_diagonal(), block_size(1),
max_nnz_input_row(-1),
num_values_in_l1(-1), num_values_in_l2(-1),num_big_rows(0), level_1_mem(0), level_2_mem(0),
owner_of_coloring(false)
{
if (gs == GS_DEFAULT)
this->choose_default_algorithm();
}
bool is_owner_of_coloring() const override {return this->owner_of_coloring;}
void set_owner_of_coloring(bool owner = true) {this->owner_of_coloring = owner;}
void set_block_size(nnz_lno_t bs){this->block_size = bs; }
nnz_lno_t get_block_size() const {return this->block_size;}
/** \brief Chooses best algorithm based on the execution space. COLORING_EB if cuda, COLORING_VB otherwise.
*/
void choose_default_algorithm(){
#if defined( KOKKOS_ENABLE_SERIAL )
if (Kokkos::Impl::is_same< Kokkos::Serial , ExecutionSpace >::value){
this->algorithm_type = GS_PERMUTED;
#ifdef VERBOSE
std::cout << "Serial Execution Space, Default Algorithm: GS_PERMUTED" << std::endl;
#endif
}
#endif
#if defined( KOKKOS_ENABLE_THREADS )
if (Kokkos::Impl::is_same< Kokkos::Threads , ExecutionSpace >::value){
this->algorithm_type = GS_PERMUTED;
#ifdef VERBOSE
std::cout << "PTHREAD Execution Space, Default Algorithm: GS_PERMUTED" << std::endl;
#endif
}
#endif
#if defined( KOKKOS_ENABLE_OPENMP )
if (Kokkos::Impl::is_same< Kokkos::OpenMP, ExecutionSpace >::value){
this->algorithm_type = GS_PERMUTED;
#ifdef VERBOSE
std::cout << "OpenMP Execution Space, Default Algorithm: GS_PERMUTED" << std::endl;
#endif
}
#endif
#if defined( KOKKOS_ENABLE_CUDA )
if (Kokkos::Impl::is_same<Kokkos::Cuda, ExecutionSpace >::value){
this->algorithm_type = GS_TEAM;
#ifdef VERBOSE
std::cout << "Cuda Execution Space, Default Algorithm: GS_TEAM" << std::endl;
#endif
}
#endif
#if defined( KOKKOS_ENABLE_QTHREAD)
if (Kokkos::Impl::is_same< Kokkos::Qthread, ExecutionSpace >::value){
this->algorithm_type = GS_PERMUTED;
#ifdef VERBOSE
std::cout << "Qthread Execution Space, Default Algorithm: GS_PERMUTED" << std::endl;
#endif
}
#endif
}
~PointGaussSeidelHandle() = default;
//getters
row_lno_persistent_work_view_t get_new_xadj() const {
return this->permuted_xadj;
}
nnz_lno_persistent_work_view_t get_new_adj() const {
return this->permuted_adj;
}
scalar_persistent_work_view_t get_new_adj_val() const {
return this->permuted_adj_vals;
}
nnz_lno_persistent_work_view_t get_old_to_new_map() const {
return this->old_to_new_map;
}
//setters
void set_algorithm_type(const GSAlgorithm &sgs_algo){this->algorithm_type = sgs_algo;}
void set_call_symbolic(bool call = true){this->called_symbolic = call;}
void set_call_numeric(bool call = true){this->called_numeric = call;}
void set_num_colors(const nnz_lno_t &numColors_) {
this->numColors = numColors_;
}
void set_new_xadj(const row_lno_persistent_work_view_t &xadj_) {
this->permuted_xadj = xadj_;
}
void set_new_adj(const nnz_lno_persistent_work_view_t &adj_) {
this->permuted_adj = adj_;
}
void set_new_adj_val(const scalar_persistent_work_view_t &adj_vals_) {
this->permuted_adj_vals = adj_vals_;
}
void set_old_to_new_map(const nnz_lno_persistent_work_view_t &old_to_new_map_) {
this->old_to_new_map = old_to_new_map_;
}
void set_permuted_inverse_diagonal (const scalar_persistent_work_view_t permuted_inverse_diagonal_){
this->permuted_inverse_diagonal = permuted_inverse_diagonal_;
}
scalar_persistent_work_view_t get_permuted_inverse_diagonal() const {
return this->permuted_inverse_diagonal;
}
void set_level_1_mem(size_t _level_1_mem){
this->level_1_mem = _level_1_mem;
}
void set_level_2_mem(size_t _level_2_mem){
this->level_2_mem = _level_2_mem;
}
void set_num_values_in_l1(nnz_lno_t _num_values_in_l1){
this->num_values_in_l1 = _num_values_in_l1;
}
void set_num_values_in_l2(nnz_lno_t _num_values_in_l2){
this->num_values_in_l2 = _num_values_in_l2;
}
void set_num_big_rows(nnz_lno_t _big_rows){
this->num_big_rows = _big_rows;
}
size_t get_level_1_mem() const {
return this->level_1_mem;
}
size_t get_level_2_mem() const {
return this->level_2_mem;
}
nnz_lno_t get_num_values_in_l1() const {
return this->num_values_in_l1 ;
}
nnz_lno_t get_num_values_in_l2() const {
return this->num_values_in_l2;
}
nnz_lno_t get_num_big_rows() const {
return this->num_big_rows;
}
nnz_lno_t get_max_nnz() const {
if(max_nnz_input_row == static_cast<nnz_lno_t>(-1))
throw std::runtime_error("Requested max nnz per input row, but this has not been set in the PointGS handle.");
return this->max_nnz_input_row;
}
void set_max_nnz(nnz_lno_t num_result_nnz_) {
this->max_nnz_input_row = num_result_nnz_;
}
void allocate_x_y_vectors(nnz_lno_t num_rows, nnz_lno_t num_cols, nnz_lno_t num_vecs){
if(permuted_y_vector.extent(0) != size_t(num_rows) || permuted_y_vector.extent(1) != size_t(num_vecs)){
permuted_y_vector = scalar_persistent_work_view2d_t("PERMUTED Y VECTOR", num_rows, num_vecs);
}
if(permuted_x_vector.extent(0) != size_t(num_cols) || permuted_x_vector.extent(1) != size_t(num_vecs)){
permuted_x_vector = scalar_persistent_work_view2d_t("PERMUTED X VECTOR", num_cols, num_vecs);
}
}
scalar_persistent_work_view2d_t get_permuted_y_vector() const {return this->permuted_y_vector;}
scalar_persistent_work_view2d_t get_permuted_x_vector() const {return this->permuted_x_vector;}
void vector_team_size(
int max_allowed_team_size,
int &suggested_vector_size_,
int &suggested_team_size_,
size_type nr, size_type nnz){
//suggested_team_size_ = this->suggested_team_size = 1;
//suggested_vector_size_=this->suggested_vector_size = 1;
//return;
if (this->suggested_team_size && this->suggested_vector_size) {
suggested_vector_size_ = this->suggested_vector_size;
suggested_team_size_ = this->suggested_team_size;
return;
}
else {
#ifdef KOKKOS_ENABLE_DEPRECATED_CODE
KokkosKernels::Impl::get_suggested_vector_team_size<size_type, ExecutionSpace>(
max_allowed_team_size, suggested_vector_size_, suggested_team_size_, nr, nnz);
#else
KokkosKernels::Impl::get_suggested_vector_size<size_type, ExecutionSpace>(suggested_vector_size_, nr, nnz);
KokkosKernels::Impl::get_suggested_team_size<ExecutionSpace>(max_allowed_team_size, suggested_vector_size_, suggested_team_size_);
#endif
this->suggested_team_size = suggested_vector_size_;
this->suggested_vector_size = suggested_vector_size_;
}
}
};
template <class size_type_, class lno_t_, class scalar_t_,
class ExecutionSpace,
class TemporaryMemorySpace,
class PersistentMemorySpace>
class ClusterGaussSeidelHandle
: public GaussSeidelHandle<size_type_, lno_t_, scalar_t_, ExecutionSpace, TemporaryMemorySpace, PersistentMemorySpace>
{
public:
typedef GaussSeidelHandle<size_type_, lno_t_, scalar_t_, ExecutionSpace, TemporaryMemorySpace, PersistentMemorySpace> GSHandle;
typedef ExecutionSpace HandleExecSpace;
typedef TemporaryMemorySpace HandleTempMemorySpace;
typedef PersistentMemorySpace HandlePersistentMemorySpace;
typedef typename std::remove_const<size_type_>::type size_type;
typedef const size_type const_size_type;
typedef typename std::remove_const<lno_t_>::type nnz_lno_t;
typedef const nnz_lno_t const_nnz_lno_t;
typedef typename std::remove_const<scalar_t_>::type nnz_scalar_t;
typedef const nnz_scalar_t const_nnz_scalar_t;
typedef typename Kokkos::View<size_type *, HandleTempMemorySpace> row_lno_temp_work_view_t;
typedef typename Kokkos::View<size_type *, HandlePersistentMemorySpace> row_lno_persistent_work_view_t;
typedef typename row_lno_persistent_work_view_t::HostMirror row_lno_persistent_work_host_view_t; //Host view type
typedef typename Kokkos::View<nnz_scalar_t *, HandleTempMemorySpace> scalar_temp_work_view_t;
typedef typename Kokkos::View<nnz_scalar_t *, HandlePersistentMemorySpace> scalar_persistent_work_view_t;
typedef typename scalar_persistent_work_view_t::HostMirror scalar_persistent_work_host_view_t; //Host view type
typedef typename Kokkos::View<nnz_lno_t *, HandleTempMemorySpace> nnz_lno_temp_work_view_t;
typedef typename Kokkos::View<nnz_lno_t *, HandlePersistentMemorySpace> nnz_lno_persistent_work_view_t;
typedef typename nnz_lno_persistent_work_view_t::HostMirror nnz_lno_persistent_work_host_view_t; //Host view type
private:
ClusteringAlgorithm cluster_algo;
//This is the user-configurable target cluster size.
//Some clusters may be slightly larger or smaller,
//but cluster_xadj always has the exact size of each.
nnz_lno_t cluster_size;
int suggested_vector_size;
int suggested_team_size;
scalar_persistent_work_view_t inverse_diagonal;
//cluster_xadj and cluster_adj encode the vertices in each cluster
nnz_lno_persistent_work_view_t cluster_xadj;
nnz_lno_persistent_work_view_t cluster_adj;
//vert_clusters(i) is the cluster that vertex i belongs to
nnz_lno_persistent_work_view_t vert_clusters;
public:
/**
* \brief Default constructor.
*/
//Constructor for cluster-coloring based GS and SGS
ClusterGaussSeidelHandle(ClusteringAlgorithm cluster_algo_, nnz_lno_t cluster_size_)
: GSHandle(GS_CLUSTER), cluster_algo(cluster_algo_), cluster_size(cluster_size_),
inverse_diagonal(), cluster_xadj(), cluster_adj(), vert_clusters()
{}
void set_cluster_size(nnz_lno_t cs) {this->cluster_size = cs;}
nnz_lno_t get_cluster_size() const {return this->cluster_size;}
void set_vert_clusters(nnz_lno_persistent_work_view_t& vert_clusters_) {
this->vert_clusters = vert_clusters_;
}
void set_cluster_xadj(nnz_lno_persistent_work_view_t& cluster_xadj_) {
this->cluster_xadj = cluster_xadj_;
}
void set_cluster_adj(nnz_lno_persistent_work_view_t& cluster_adj_) {
this->cluster_adj = cluster_adj_;
}
nnz_lno_persistent_work_view_t get_vert_clusters() const {
if(!this->is_symbolic_called())
throw std::runtime_error("vert_clusters does not exist until after symbolic setup.");
return vert_clusters;
}
nnz_lno_persistent_work_view_t get_cluster_xadj() const {
if(!this->is_symbolic_called())
throw std::runtime_error("cluster_xadj does not exist until after symbolic setup.");
return cluster_xadj;
}
nnz_lno_persistent_work_view_t get_cluster_adj() const {
if(!this->is_symbolic_called())
throw std::runtime_error("cluster_adj does not exist until after symbolic setup.");
return cluster_adj;
}
void set_inverse_diagonal(scalar_persistent_work_view_t& inv_diag) {
this->inverse_diagonal = inv_diag;
}
scalar_persistent_work_view_t get_inverse_diagonal() const {
if(!this->is_symbolic_called())
throw std::runtime_error("inverse diagonal does not exist until after numeric setup.");
return inverse_diagonal;
}
bool use_teams() const
{
bool return_value = false;
#if defined( KOKKOS_ENABLE_SERIAL )
if (Kokkos::Impl::is_same< Kokkos::Serial , ExecutionSpace >::value) {
return_value = false;
}
#endif
#if defined( KOKKOS_ENABLE_THREADS )
if (Kokkos::Impl::is_same< Kokkos::Threads , ExecutionSpace >::value){
return_value = false;
}
#endif
#if defined( KOKKOS_ENABLE_OPENMP )
if (Kokkos::Impl::is_same< Kokkos::OpenMP, ExecutionSpace >::value){
return_value = false;
}
#endif
#if defined( KOKKOS_ENABLE_CUDA )
if (Kokkos::Impl::is_same<Kokkos::Cuda, ExecutionSpace >::value){
return_value = true;
}
#endif
#if defined( KOKKOS_ENABLE_QTHREAD)
if (Kokkos::Impl::is_same< Kokkos::Qthread, ExecutionSpace >::value){
return_value = false;
}
#endif
return return_value;
}
~ClusterGaussSeidelHandle() = default;
ClusteringAlgorithm get_clustering_algo() const {return this->cluster_algo;}
};
}
#endif
| 38.092409 | 165 | 0.730073 | [
"vector"
] |
a09d8ac0990c838293ed901847e4fdd2c643ddea | 1,755 | hpp | C++ | joystick/joystick.hpp | jakah/hu-ipass | ac313632d08741a77fb7545828299dd93de8621e | [
"BSL-1.0"
] | null | null | null | joystick/joystick.hpp | jakah/hu-ipass | ac313632d08741a77fb7545828299dd93de8621e | [
"BSL-1.0"
] | null | null | null | joystick/joystick.hpp | jakah/hu-ipass | ac313632d08741a77fb7545828299dd93de8621e | [
"BSL-1.0"
] | null | null | null | #include "hwlib.hpp"
#ifndef JOYSTICK_HPP
#define JOYSTICK_HPP
/// \file
/// \class joystick
/// \brief
/// the joystick class
/// \details
/// This class is an abstracion for a joystick. Two analog pins go in and you can call
/// functions to check if the joystick is at a certain position
class joystick{
private:
int position;
hwlib::adc & pin_x;
hwlib::adc & pin_y;
public:
/// \brief
/// constructor for joystick class
/// \details
/// Constructs a joystick object using the two anolog pins of the potentiometers.
/// \param[in] hwlib::adc & pin_x , the pin that gives the anolog value for the x potentiometer
/// \param[in] hwlib::adc & pin_y , the pin that gives the anolog value for the y potentiometer
joystick(hwlib::adc & pin_x, hwlib::adc & pin_y);
/// \brief
/// check if the joystick is up
/// \details
/// This function checks if the joystick is in the up position.
/// \result true if in the up position, false if not in the up position
bool up();
/// \brief
/// check if the joystick is down
/// \details
/// This function checks if the joystick is in the down position.
/// \result true if in the down position, false if not in the down position
bool down();
/// \brief
/// check if the joystick is left
/// \details
/// This function checks if the joystick is in the left position.
/// \result true if in the left position, false if not in the left position
bool left();
/// \brief
/// check if the joystick is right
/// \details
/// This function checks if the joystick is in the right position.
/// \result true if in the right position, false if not in the right position
bool right();
};
#endif | 35.1 | 99 | 0.654701 | [
"object"
] |
a0a277db0ea1426488343637ce1cb24ffdd0c665 | 34,681 | cpp | C++ | android-opencv/opencv/modules/legacy/src/corrimages.cpp | agunksetiajaty/viewercv | 539d9f60bc61c3a2761157aa4e44e5d00048dbf1 | [
"Apache-2.0"
] | 1 | 2015-11-06T02:07:38.000Z | 2015-11-06T02:07:38.000Z | android-opencv/opencv/modules/legacy/src/corrimages.cpp | agunksetiajaty/viewercv | 539d9f60bc61c3a2761157aa4e44e5d00048dbf1 | [
"Apache-2.0"
] | null | null | null | android-opencv/opencv/modules/legacy/src/corrimages.cpp | agunksetiajaty/viewercv | 539d9f60bc61c3a2761157aa4e44e5d00048dbf1 | [
"Apache-2.0"
] | null | null | null | /*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// Intel License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2000, Intel Corporation, all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's 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.
//
// * The name of Intel Corporation may not 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 Intel Corporation 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.
//
//M*/
#include "precomp.hpp"
//#include "cvtypes.h"
//#include <float.h>
//#include <limits.h>
//#include "cv.h"
//#include "highgui.h"
#include <stdio.h>
/* Valery Mosyagin */
/* ===== Function for find corresponding between images ===== */
/* Create feature points on image and return number of them. Array points fills by found points */
int icvCreateFeaturePoints(IplImage* image, CvMat* points, CvMat* status) {
int foundFeaturePoints = 0;
IplImage* grayImage = 0;
IplImage* eigImage = 0;
IplImage* tmpImage = 0;
CvPoint2D32f* cornerPoints = 0;
CV_FUNCNAME("icvFeatureCreatePoints");
__BEGIN__;
/* Test for errors */
if (image == 0 || points == 0) {
CV_ERROR(CV_StsNullPtr, "Some of parameters is a NULL pointer");
}
/* Test image size */
int w, h;
w = image->width;
h = image->height;
if (w <= 0 || h <= 0) {
CV_ERROR(CV_StsOutOfRange, "Size of image must be > 0");
}
/* Test for matrices */
if (!CV_IS_MAT(points)) {
CV_ERROR(CV_StsUnsupportedFormat, "Input parameter points must be a matrix");
}
int needNumPoints;
needNumPoints = points->cols;
if (needNumPoints <= 0) {
CV_ERROR(CV_StsOutOfRange, "Number of need points must be > 0");
}
if (points->rows != 2) {
CV_ERROR(CV_StsOutOfRange, "Number of point coordinates must be == 2");
}
if (status != 0) {
/* If status matrix exist test it for correct */
if (!CV_IS_MASK_ARR(status)) {
CV_ERROR(CV_StsUnsupportedFormat, "Statuses must be a mask arrays");
}
if (status->cols != needNumPoints) {
CV_ERROR(CV_StsUnmatchedSizes, "Size of points and statuses must be the same");
}
if (status->rows != 1) {
CV_ERROR(CV_StsUnsupportedFormat, "Number of rows of status must be 1");
}
}
/* Create temporary images */
CV_CALL(grayImage = cvCreateImage(cvSize(w, h), 8, 1));
CV_CALL(eigImage = cvCreateImage(cvSize(w, h), 32, 1));
CV_CALL(tmpImage = cvCreateImage(cvSize(w, h), 32, 1));
/* Create points */
CV_CALL(cornerPoints = (CvPoint2D32f*)cvAlloc(sizeof(CvPoint2D32f) * needNumPoints));
int foundNum;
double quality;
double minDist;
cvCvtColor(image, grayImage, CV_BGR2GRAY);
foundNum = needNumPoints;
quality = 0.01;
minDist = 5;
cvGoodFeaturesToTrack(grayImage, eigImage, tmpImage, cornerPoints, &foundNum, quality, minDist);
/* Copy found points to result */
int i;
for (i = 0; i < foundNum; i++) {
cvmSet(points, 0, i, cornerPoints[i].x);
cvmSet(points, 1, i, cornerPoints[i].y);
}
/* Set status if need */
if (status) {
for (i = 0; i < foundNum; i++) {
status->data.ptr[i] = 1;
}
for (i = foundNum; i < needNumPoints; i++) {
status->data.ptr[i] = 0;
}
}
foundFeaturePoints = foundNum;
__END__;
/* Free allocated memory */
cvReleaseImage(&grayImage);
cvReleaseImage(&eigImage);
cvReleaseImage(&tmpImage);
cvFree(&cornerPoints);
return foundFeaturePoints;
}
/*-------------------------------------------------------------------------------------*/
/* For given points1 (with pntStatus) on image1 finds corresponding points2 on image2 and set pntStatus2 for them */
/* Returns number of corresponding points */
int icvFindCorrForGivenPoints(IplImage* image1, /* Image 1 */
IplImage* image2,/* Image 2 */
CvMat* points1,
CvMat* pntStatus1,
CvMat* points2,
CvMat* pntStatus2,
int useFilter,/*Use fundamental matrix to filter points */
double threshold) { /* Threshold for good points in filter */
int resNumCorrPoints = 0;
CvPoint2D32f* cornerPoints1 = 0;
CvPoint2D32f* cornerPoints2 = 0;
char* status = 0;
float* errors = 0;
CvMat* tmpPoints1 = 0;
CvMat* tmpPoints2 = 0;
CvMat* pStatus = 0;
IplImage* grayImage1 = 0;
IplImage* grayImage2 = 0;
IplImage* pyrImage1 = 0;
IplImage* pyrImage2 = 0;
CV_FUNCNAME("icvFindCorrForGivenPoints");
__BEGIN__;
/* Test input data for errors */
/* Test for null pointers */
if (image1 == 0 || image2 == 0 ||
points1 == 0 || points2 == 0 ||
pntStatus1 == 0 || pntStatus2 == 0) {
CV_ERROR(CV_StsNullPtr, "Some of parameters is a NULL pointer");
}
/* Test image size */
int w, h;
w = image1->width;
h = image1->height;
if (w <= 0 || h <= 0) {
CV_ERROR(CV_StsOutOfRange, "Size of image1 must be > 0");
}
if (image2->width != w || image2->height != h) {
CV_ERROR(CV_StsUnmatchedSizes, "Size of images must be the same");
}
/* Test for matrices */
if (!CV_IS_MAT(points1) || !CV_IS_MAT(points2) ||
!CV_IS_MAT(pntStatus1) || !CV_IS_MAT(pntStatus2)) {
CV_ERROR(CV_StsUnsupportedFormat, "Input parameters (points and status) must be a matrices");
}
/* Test type of status matrices */
if (!CV_IS_MASK_ARR(pntStatus1) || !CV_IS_MASK_ARR(pntStatus2)) {
CV_ERROR(CV_StsUnsupportedFormat, "Statuses must be a mask arrays");
}
/* Test number of points */
int numPoints;
numPoints = points1->cols;
if (numPoints <= 0) {
CV_ERROR(CV_StsOutOfRange, "Number of points1 must be > 0");
}
if (points2->cols != numPoints || pntStatus1->cols != numPoints || pntStatus2->cols != numPoints) {
CV_ERROR(CV_StsUnmatchedSizes, "Number of points and statuses must be the same");
}
if (points1->rows != 2 || points2->rows != 2) {
CV_ERROR(CV_StsOutOfRange, "Number of points coordinates must be 2");
}
if (pntStatus1->rows != 1 || pntStatus2->rows != 1) {
CV_ERROR(CV_StsOutOfRange, "Status must be a matrix 1xN");
}
/* ----- End test ----- */
/* Compute number of visible points on image1 */
int numVisPoints;
numVisPoints = cvCountNonZero(pntStatus1);
if (numVisPoints > 0) {
/* Create temporary images */
/* We must use iplImage againts hughgui images */
/*
CvvImage grayImage1;
CvvImage grayImage2;
CvvImage pyrImage1;
CvvImage pyrImage2;
*/
/* Create Ipl images */
CV_CALL(grayImage1 = cvCreateImage(cvSize(w, h), 8, 1));
CV_CALL(grayImage2 = cvCreateImage(cvSize(w, h), 8, 1));
CV_CALL(pyrImage1 = cvCreateImage(cvSize(w, h), 8, 1));
CV_CALL(pyrImage2 = cvCreateImage(cvSize(w, h), 8, 1));
CV_CALL(cornerPoints1 = (CvPoint2D32f*)cvAlloc(sizeof(CvPoint2D32f) * numVisPoints));
CV_CALL(cornerPoints2 = (CvPoint2D32f*)cvAlloc(sizeof(CvPoint2D32f) * numVisPoints));
CV_CALL(status = (char*)cvAlloc(sizeof(char) * numVisPoints));
CV_CALL(errors = (float*)cvAlloc(2 * sizeof(float) * numVisPoints));
int i;
for (i = 0; i < numVisPoints; i++) {
status[i] = 1;
}
/* !!! Need test creation errors */
/*
if( !grayImage1.Create(w,h,8)) EXIT;
if( !grayImage2.Create(w,h,8)) EXIT;
if( !pyrImage1. Create(w,h,8)) EXIT;
if( !pyrImage2. Create(w,h,8)) EXIT;
*/
cvCvtColor(image1, grayImage1, CV_BGR2GRAY);
cvCvtColor(image2, grayImage2, CV_BGR2GRAY);
/*
grayImage1.CopyOf(image1,0);
grayImage2.CopyOf(image2,0);
*/
/* Copy points good points from input data */
uchar* stat1 = pntStatus1->data.ptr;
uchar* stat2 = pntStatus2->data.ptr;
int curr = 0;
for (i = 0; i < numPoints; i++) {
if (stat1[i]) {
cornerPoints1[curr].x = (float)cvmGet(points1, 0, i);
cornerPoints1[curr].y = (float)cvmGet(points1, 1, i);
curr++;
}
}
/* Define number of levels of pyramid */
cvCalcOpticalFlowPyrLK(grayImage1, grayImage2,
pyrImage1, pyrImage2,
cornerPoints1, cornerPoints2,
numVisPoints, cvSize(10, 10), 3,
status, errors,
cvTermCriteria(CV_TERMCRIT_ITER | CV_TERMCRIT_EPS, 20, 0.03),
0/*CV_LKFLOW_PYR_A_READY*/);
memset(stat2, 0, sizeof(uchar)*numPoints);
int currVis = 0;
int totalCorns = 0;
/* Copy new points and set status */
/* stat1 may not be the same as stat2 */
for (i = 0; i < numPoints; i++) {
if (stat1[i]) {
if (status[currVis] && errors[currVis] < 1000) {
stat2[i] = 1;
cvmSet(points2, 0, i, cornerPoints2[currVis].x);
cvmSet(points2, 1, i, cornerPoints2[currVis].y);
totalCorns++;
}
currVis++;
}
}
resNumCorrPoints = totalCorns;
/* Filter points using RANSAC */
if (useFilter) {
resNumCorrPoints = 0;
/* Use RANSAC filter for found points */
if (totalCorns > 7) {
/* Create array with good points only */
CV_CALL(tmpPoints1 = cvCreateMat(2, totalCorns, CV_64F));
CV_CALL(tmpPoints2 = cvCreateMat(2, totalCorns, CV_64F));
/* Copy just good points */
int currPoint = 0;
for (i = 0; i < numPoints; i++) {
if (stat2[i]) {
cvmSet(tmpPoints1, 0, currPoint, cvmGet(points1, 0, i));
cvmSet(tmpPoints1, 1, currPoint, cvmGet(points1, 1, i));
cvmSet(tmpPoints2, 0, currPoint, cvmGet(points2, 0, i));
cvmSet(tmpPoints2, 1, currPoint, cvmGet(points2, 1, i));
currPoint++;
}
}
/* Compute fundamental matrix */
CvMat fundMatr;
double fundMatr_dat[9];
fundMatr = cvMat(3, 3, CV_64F, fundMatr_dat);
CV_CALL(pStatus = cvCreateMat(1, totalCorns, CV_32F));
int num = cvFindFundamentalMat(tmpPoints1, tmpPoints2, &fundMatr, CV_FM_RANSAC, threshold, 0.99, pStatus);
if (num > 0) {
int curr = 0;
/* Set final status for points2 */
for (i = 0; i < numPoints; i++) {
if (stat2[i]) {
if (cvmGet(pStatus, 0, curr) == 0) {
stat2[i] = 0;
}
curr++;
}
}
resNumCorrPoints = curr;
}
}
}
}
__END__;
/* Free allocated memory */
cvFree(&cornerPoints1);
cvFree(&cornerPoints2);
cvFree(&status);
cvFree(&errors);
cvFree(&tmpPoints1);
cvFree(&tmpPoints2);
cvReleaseMat(&pStatus);
cvReleaseImage(&grayImage1);
cvReleaseImage(&grayImage2);
cvReleaseImage(&pyrImage1);
cvReleaseImage(&pyrImage2);
return resNumCorrPoints;
}
/*-------------------------------------------------------------------------------------*/
int icvGrowPointsAndStatus(CvMat** oldPoints, CvMat** oldStatus, CvMat* addPoints, CvMat* addStatus, int addCreateNum) {
/* Add to existing points and status arrays new points or just grow */
CvMat* newOldPoint = 0;
CvMat* newOldStatus = 0;
int newTotalNumber = 0;
CV_FUNCNAME("icvGrowPointsAndStatus");
__BEGIN__;
/* Test for errors */
if (oldPoints == 0 || oldStatus == 0) {
CV_ERROR(CV_StsNullPtr, "Some of parameters is a NULL pointer");
}
if (*oldPoints == 0 || *oldStatus == 0) {
CV_ERROR(CV_StsNullPtr, "Some of parameters is a NULL pointer");
}
if (!CV_IS_MAT(*oldPoints)) {
CV_ERROR(CV_StsUnsupportedFormat, "oldPoints must be a pointer to a matrix");
}
if (!CV_IS_MASK_ARR(*oldStatus)) {
CV_ERROR(CV_StsUnsupportedFormat, "oldStatus must be a pointer to a mask array");
}
int oldNum;
oldNum = (*oldPoints)->cols;
if (oldNum < 1) {
CV_ERROR(CV_StsOutOfRange, "Number of old points must be > 0");
}
/* Define if need number of add points */
int addNum;
addNum = 0;
if (addPoints != 0 && addStatus != 0) {
/* We have aditional points */
if (CV_IS_MAT(addPoints) && CV_IS_MASK_ARR(addStatus)) {
addNum = addPoints->cols;
if (addStatus->cols != addNum) {
CV_ERROR(CV_StsOutOfRange, "Number of add points and statuses must be the same");
}
}
}
/* */
int numCoord;
numCoord = (*oldPoints)->rows;
newTotalNumber = oldNum + addNum + addCreateNum;
if (newTotalNumber) {
/* Free allocated memory */
newOldPoint = cvCreateMat(numCoord, newTotalNumber, CV_64F);
newOldStatus = cvCreateMat(1, newTotalNumber, CV_8S);
/* Copy old values to */
int i;
/* Clear all values */
cvZero(newOldPoint);
cvZero(newOldStatus);
for (i = 0; i < oldNum; i++) {
int currCoord;
for (currCoord = 0; currCoord < numCoord; currCoord++) {
cvmSet(newOldPoint, currCoord, i, cvmGet(*oldPoints, currCoord, i));
}
newOldStatus->data.ptr[i] = (*oldStatus)->data.ptr[i];
}
/* Copy additional points and statuses */
if (addNum) {
for (i = 0; i < addNum; i++) {
int currCoord;
for (currCoord = 0; currCoord < numCoord; currCoord++) {
cvmSet(newOldPoint, currCoord, i + oldNum, cvmGet(addPoints, currCoord, i));
}
newOldStatus->data.ptr[i+oldNum] = addStatus->data.ptr[i];
//cvmSet(newOldStatus,0,i,cvmGet(addStatus,0,i));
}
}
/* Delete previous data */
cvReleaseMat(oldPoints);
cvReleaseMat(oldStatus);
/* copy pointers */
*oldPoints = newOldPoint;
*oldStatus = newOldStatus;
}
__END__;
return newTotalNumber;
}
/*-------------------------------------------------------------------------------------*/
int icvRemoveDoublePoins(CvMat* oldPoints, /* Points on prev image */
CvMat* newPoints,/* New points */
CvMat* oldStatus,/* Status for old points */
CvMat* newStatus,
CvMat* origStatus,
float threshold) { /* Status for new points */
CvMemStorage* storage = 0;
CvSubdiv2D* subdiv = 0;
CvSeq* seq = 0;
int originalPoints = 0;
CV_FUNCNAME("icvRemoveDoublePoins");
__BEGIN__;
/* Test input data */
if (oldPoints == 0 || newPoints == 0 ||
oldStatus == 0 || newStatus == 0 || origStatus == 0) {
CV_ERROR(CV_StsNullPtr, "Some of parameters is a NULL pointer");
}
if (!CV_IS_MAT(oldPoints) || !CV_IS_MAT(newPoints)) {
CV_ERROR(CV_StsUnsupportedFormat, "Input parameters points must be a matrices");
}
if (!CV_IS_MASK_ARR(oldStatus) || !CV_IS_MASK_ARR(newStatus) || !CV_IS_MASK_ARR(origStatus)) {
CV_ERROR(CV_StsUnsupportedFormat, "Input parameters statuses must be a mask array");
}
int oldNumPoints;
oldNumPoints = oldPoints->cols;
if (oldNumPoints < 0) {
CV_ERROR(CV_StsOutOfRange, "Number of oldPoints must be >= 0");
}
if (oldStatus->cols != oldNumPoints) {
CV_ERROR(CV_StsUnmatchedSizes, "Number of old Points and old Statuses must be the same");
}
int newNumPoints;
newNumPoints = newPoints->cols;
if (newNumPoints < 0) {
CV_ERROR(CV_StsOutOfRange, "Number of newPoints must be >= 0");
}
if (newStatus->cols != newNumPoints) {
CV_ERROR(CV_StsUnmatchedSizes, "Number of new Points and new Statuses must be the same");
}
if (origStatus->cols != newNumPoints) {
CV_ERROR(CV_StsUnmatchedSizes, "Number of new Points and new original Status must be the same");
}
if (oldPoints->rows != 2) {
CV_ERROR(CV_StsOutOfRange, "OldPoints must have 2 coordinates >= 0");
}
if (newPoints->rows != 2) {
CV_ERROR(CV_StsOutOfRange, "NewPoints must have 2 coordinates >= 0");
}
if (oldStatus->rows != 1 || newStatus->rows != 1 || origStatus->rows != 1) {
CV_ERROR(CV_StsOutOfRange, "Statuses must have 1 row");
}
/* we have points on image and wants add new points */
/* use subdivision for find nearest points */
/* Define maximum and minimum X and Y */
float minX, minY;
float maxX, maxY;
minX = minY = FLT_MAX;
maxX = maxY = FLT_MIN;
int i;
for (i = 0; i < oldNumPoints; i++) {
if (oldStatus->data.ptr[i]) {
float x = (float)cvmGet(oldPoints, 0, i);
float y = (float)cvmGet(oldPoints, 1, i);
if (x < minX) {
minX = x;
}
if (x > maxX) {
maxX = x;
}
if (y < minY) {
minY = y;
}
if (y > maxY) {
maxY = y;
}
}
}
for (i = 0; i < newNumPoints; i++) {
if (newStatus->data.ptr[i]) {
float x = (float)cvmGet(newPoints, 0, i);
float y = (float)cvmGet(newPoints, 1, i);
if (x < minX) {
minX = x;
}
if (x > maxX) {
maxX = x;
}
if (y < minY) {
minY = y;
}
if (y > maxY) {
maxY = y;
}
}
}
/* Creare subdivision for old image */
storage = cvCreateMemStorage(0);
// subdiv = cvCreateSubdivDelaunay2D( cvRect( 0, 0, size.width, size.height ), storage );
subdiv = cvCreateSubdivDelaunay2D(cvRect(cvRound(minX) - 5, cvRound(minY) - 5, cvRound(maxX - minX) + 10, cvRound(maxY - minY) + 10), storage);
seq = cvCreateSeq(0, sizeof(*seq), sizeof(CvPoint2D32f), storage);
/* Insert each point from first image */
for (i = 0; i < oldNumPoints; i++) {
/* Add just exist points */
if (oldStatus->data.ptr[i]) {
CvPoint2D32f pt;
pt.x = (float)cvmGet(oldPoints, 0, i);
pt.y = (float)cvmGet(oldPoints, 1, i);
CvSubdiv2DPoint* point;
point = cvSubdivDelaunay2DInsert(subdiv, pt);
}
}
/* Find nearest points */
/* for each new point */
int flag;
for (i = 0; i < newNumPoints; i++) {
flag = 0;
/* Test just exist points */
if (newStatus->data.ptr[i]) {
flag = 1;
/* Let this is a good point */
//originalPoints++;
CvPoint2D32f pt;
pt.x = (float)cvmGet(newPoints, 0, i);
pt.y = (float)cvmGet(newPoints, 1, i);
CvSubdiv2DPoint* point = cvFindNearestPoint2D(subdiv, pt);
if (point) {
/* Test distance of found nearest point */
double minDistance = icvSqDist2D32f(pt, point->pt);
if (minDistance < threshold * threshold) {
/* Point is double. Turn it off */
/* Set status */
//newStatus->data.ptr[i] = 0;
/* No this is a double point */
//originalPoints--;
flag = 0;
}
}
}
originalPoints += flag;
origStatus->data .ptr[i] = (uchar)flag;
}
__END__;
cvReleaseMemStorage(&storage);
return originalPoints;
}
void icvComputeProjectMatrix(CvMat* objPoints, CvMat* projPoints, CvMat* projMatr);
/*-------------------------------------------------------------------------------------*/
void icvComputeProjectMatrixStatus(CvMat* objPoints4D, CvMat* points2, CvMat* status, CvMat* projMatr) {
/* Compute number of good points */
int num = cvCountNonZero(status);
/* Create arrays */
CvMat* objPoints = 0;
objPoints = cvCreateMat(4, num, CV_64F);
CvMat* points2D = 0;
points2D = cvCreateMat(2, num, CV_64F);
int currVis = 0;
int i;
#if 1
FILE* file;
file = fopen("d:\\test\\projStatus.txt", "w");
#endif
int totalNum = objPoints4D->cols;
for (i = 0; i < totalNum; i++) {
fprintf(file, "%d (%d) ", i, status->data.ptr[i]);
if (status->data.ptr[i]) {
#if 1
double X, Y, Z, W;
double x, y;
X = cvmGet(objPoints4D, 0, i);
Y = cvmGet(objPoints4D, 1, i);
Z = cvmGet(objPoints4D, 2, i);
W = cvmGet(objPoints4D, 3, i);
x = cvmGet(points2, 0, i);
y = cvmGet(points2, 1, i);
fprintf(file, "%d (%lf %lf %lf %lf) - (%lf %lf)", i, X, Y, Z, W, x, y);
#endif
cvmSet(objPoints, 0, currVis, cvmGet(objPoints4D, 0, i));
cvmSet(objPoints, 1, currVis, cvmGet(objPoints4D, 1, i));
cvmSet(objPoints, 2, currVis, cvmGet(objPoints4D, 2, i));
cvmSet(objPoints, 3, currVis, cvmGet(objPoints4D, 3, i));
cvmSet(points2D, 0, currVis, cvmGet(points2, 0, i));
cvmSet(points2D, 1, currVis, cvmGet(points2, 1, i));
currVis++;
}
fprintf(file, "\n");
}
#if 1
fclose(file);
#endif
icvComputeProjectMatrix(objPoints, points2D, projMatr);
/* Free allocated memory */
cvReleaseMat(&objPoints);
cvReleaseMat(&points2D);
}
/*-------------------------------------------------------------------------------------*/
/* For given N images
we have corresponding points on N images
computed projection matrices
reconstructed 4D points
we must to compute
*/
void icvAddNewImageToPrevious____(
IplImage* newImage,//Image to add
IplImage* oldImage,//Previous image
CvMat* oldPoints,// previous 2D points on prev image (some points may be not visible)
CvMat* oldPntStatus,//Status for each point on prev image
CvMat* objPoints4D,//prev 4D points
CvMat* newPoints, //Points on new image corr for prev
CvMat* newPntStatus,// New point status for new image
CvMat* newFPoints2D1,//new feature points on prev image
CvMat* newFPoints2D2,//new feature points on new image
CvMat* newFPointsStatus,
CvMat* newProjMatr,
int useFilter,
double threshold) { //New projection matrix
CvMat* points2 = 0;
CvMat* status = 0;
CvMat* newFPointsStatusTmp = 0;
//CV_FUNCNAME( "icvAddNewImageToPrevious____" );
__BEGIN__;
/* First found correspondence points for images */
/* Test input params */
int numPoints;
numPoints = oldPoints->cols;
/* Allocate memory */
points2 = cvCreateMat(2, numPoints, CV_64F);
status = cvCreateMat(1, numPoints, CV_8S);
newFPointsStatusTmp = cvCreateMat(1, newFPoints2D1->cols, CV_8S);
int corrNum;
corrNum = icvFindCorrForGivenPoints(oldImage, /* Image 1 */
newImage,/* Image 2 */
oldPoints,
oldPntStatus,
points2,
status,
useFilter,/*Use fundamental matrix to filter points */
threshold);/* Threshold for good points in filter */
cvCopy(status, newPntStatus);
cvCopy(points2, newPoints);
CvMat projMatr;
double projMatr_dat[12];
projMatr = cvMat(3, 4, CV_64F, projMatr_dat);
if (corrNum >= 6) {
/* We can compute projection matrix */
// icvComputeProjectMatrix(objPoints4D,points2,&projMatr);
icvComputeProjectMatrixStatus(objPoints4D, points2, status, &projMatr);
cvCopy(&projMatr, newProjMatr);
/* Create new points and find correspondence */
icvCreateFeaturePoints(newImage, newFPoints2D2, newFPointsStatus);
/* Good if we test new points before find corr points */
/* Find correspondence for new found points */
icvFindCorrForGivenPoints(newImage, /* Image 1 */
oldImage,/* Image 2 */
newFPoints2D2,
newFPointsStatus,//prev status
newFPoints2D1,
newFPointsStatusTmp,//new status
useFilter,/*Use fundamental matrix to filter points */
threshold);/* Threshold for good points in filter */
/* We generated new points on image test for exist points */
/* Remove all new double points */
int origNum;
/* Find point of old image */
origNum = icvRemoveDoublePoins(oldPoints, /* Points on prev image */
newFPoints2D1,/* New points */
oldPntStatus,/* Status for old points */
newFPointsStatusTmp,
newFPointsStatusTmp,//orig status
20);/* Status for new points */
/* Find double points on new image */
origNum = icvRemoveDoublePoins(newPoints, /* Points on prev image */
newFPoints2D2,/* New points */
newPntStatus,/* Status for old points */
newFPointsStatusTmp,
newFPointsStatusTmp,//orig status
20);/* Status for new points */
/* Add all new good points to result */
/* Copy new status to old */
cvCopy(newFPointsStatusTmp, newFPointsStatus);
}
__END__;
/* Free allocated memory */
return;
}
/*-------------------------------------------------------------------------------------*/
//int icvDelete//
//CreateGood
/*-------------------------------------------------------------------------------------*/
int icvDeleteSparsInPoints(int numImages,
CvMat** points,
CvMat** status,
CvMat* wasStatus) { /* status of previous configuration */
/* Delete points which no exist on any of images */
/* numImages - number of images */
/* points - arrays of points for each image. Changing */
/* status - arrays of status for each image. Changing */
/* Function returns number of common points */
int comNumber = 0;
CV_FUNCNAME("icvDeleteSparsInPoints");
__BEGIN__;
/* Test for errors */
if (numImages < 1) {
CV_ERROR(CV_StsOutOfRange, "Number of images must be more than 0");
}
if (points == 0 || status == 0) {
CV_ERROR(CV_StsNullPtr, "Some of parameters is a NULL pointer");
}
int numPoints;
numPoints = points[0]->cols;
////////// TESTS //////////
int numCoord;
numCoord = points[0]->rows;// !!! may be number of coordinates is not correct !!!
int i;
int currExistPoint;
currExistPoint = 0;
if (wasStatus) {
cvZero(wasStatus);
}
int currImage;
for (i = 0; i < numPoints; i++) {
int flag = 0;
for (currImage = 0; currImage < numImages; currImage++) {
flag |= status[currImage]->data.ptr[i];
}
if (flag) {
/* Current point exists */
/* Copy points and status */
if (currExistPoint != i) { /* Copy just if different */
for (currImage = 0; currImage < numImages; currImage++) {
/* Copy points */
for (int currCoord = 0; currCoord < numCoord; currCoord++) {
cvmSet(points[currImage], currCoord, currExistPoint, cvmGet(points[currImage], currCoord, i));
}
/* Copy status */
status[currImage]->data.ptr[currExistPoint] = status[currImage]->data.ptr[i];
}
}
if (wasStatus) {
wasStatus->data.ptr[i] = 1;
}
currExistPoint++;
}
}
/* Rest of final status of points must be set to 0 */
for (i = currExistPoint; i < numPoints; i++) {
for (currImage = 0; currImage < numImages; currImage++) {
status[currImage]->data.ptr[i] = 0;
}
}
comNumber = currExistPoint;
__END__;
return comNumber;
}
#if 0
/*-------------------------------------------------------------------------------------*/
void icvGrowPointsArray(CvMat** points) {
}
/*-------------------------------------------------------------------------------------*/
void icvAddNewArrayPoints() {
}
/*-------------------------------------------------------------------------------------*/
#endif
//////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////
/* Add image to existing images and corr points */
#if 0
/* Returns: 1 if new image was added good */
/* 0 image was not added. Not enought corr points */
int AddImageToStruct(IplImage* newImage, //Image to add
IplImage* oldImage,//Previous image
CvMat* oldPoints,// previous 2D points on prev image (some points may be not visible)
CvMat* oldPntStatus,//Status for each point on prev image
CvMat* objPoints4D,//prev 4D points
CvMat* newPntStatus,// New point status for new image
CvMat* newPoints,//New corresponding points on new image
CvMat* newPoints2D1,//new points on prev image
CvMat* newPoints2D2,//new points on new image
CvMat* newProjMatr);//New projection matrix
{
/* Add new image. Create new corr points */
/* Track exist points from oldImage to newImage */
/* Create new vector status */
CvMat* status;
int numPoints = oldPoints->cols;
status = cvCreateMat(1, numPoints, CV_64F);
/* Copy status */
cvConvert(pntStatus, status);
int corrNum = FindCorrForGivenPoints(oldImage, newImage, oldPoints, newPoints, status);
/* Status has new status of points */
CvMat projMatr;
double projMatr_dat[12];
projMatr = cvMat(3, 4, CV_64F, projMatr_dat);
/* If number of corr points is 6 or more can compute projection matrix */
if (corrNum >= 6) {
/* Compute projection matrix for new image using corresponding points */
icvComputeProjectMatrix(objPoints4D, newPoints, &projMatr);
CvMat* tmpPoints;
/* Create new points and find correspondence */
int num = FindFeaturePoints(newImage, &tmpPoints);
if (num > 0) {
CvMat* newPoints;
newPoints = cvCreateMat(2, num, CV_64F);
CvMat* status;
status = cvCreateMat(1, num, CV_64F);
/* Set status for all points */
int i;
for (i = 0; i < num; i++) {
cvmSet(status, 0, i, 1.0);
}
int corrNum2 = FindCorrForGivenPoints(oldImage, newImage, tmpPoints, newPoints, status);
/* !!! Filter points using projection matrices or not ??? */
/* !!! Need to filter nearest points */
/* Add new found points to exist points and optimize again */
CvMat* new2DPoints;
CvMat* newStatus;
/* add new status to old status */
} else {
/* No new points were found */
}
} else {
/* We can't compute projection matrix for new image */
return 0;
}
}
#endif
| 32.717925 | 147 | 0.533779 | [
"vector"
] |
a0a6ac18eb8f4deb076449ade67b83ad7435715c | 10,813 | hpp | C++ | NetKet/Machine/rbm_multival.hpp | stavros11/netket | 1cec25a4884bdbd2fddb5d24daae627cd89316d8 | [
"Apache-2.0"
] | null | null | null | NetKet/Machine/rbm_multival.hpp | stavros11/netket | 1cec25a4884bdbd2fddb5d24daae627cd89316d8 | [
"Apache-2.0"
] | null | null | null | NetKet/Machine/rbm_multival.hpp | stavros11/netket | 1cec25a4884bdbd2fddb5d24daae627cd89316d8 | [
"Apache-2.0"
] | 1 | 2019-09-15T17:24:23.000Z | 2019-09-15T17:24:23.000Z | // Copyright 2018 The Simons Foundation, Inc. - All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <Eigen/Dense>
#include <iostream>
#include <map>
#include <vector>
#include "Lookup/lookup.hpp"
#include "Utils/all_utils.hpp"
#include "abstract_machine.hpp"
#include "rbm_spin.hpp"
#ifndef NETKET_RBM_MULTIVAL_HPP
#define NETKET_RBM_MULTIVAL_HPP
namespace netket {
// Restricted Boltzman Machine wave function
// for generic (finite) local hilbert space
template <typename T>
class RbmMultival : public AbstractMachine<T> {
using VectorType = typename AbstractMachine<T>::VectorType;
using MatrixType = typename AbstractMachine<T>::MatrixType;
// number of visible units
int nv_;
// number of hidden units
int nh_;
// number of parameters
int npar_;
// weights
MatrixType W_;
// visible units bias
VectorType a_;
// hidden units bias
VectorType b_;
VectorType thetas_;
VectorType lnthetas_;
VectorType thetasnew_;
VectorType lnthetasnew_;
bool usea_;
bool useb_;
const Hilbert &hilbert_;
Eigen::VectorXd localconfs_;
Eigen::MatrixXd mask_;
Eigen::VectorXd vtilde_;
// local size of hilbert space
int ls_;
std::map<double, int> confindex_;
public:
using StateType = typename AbstractMachine<T>::StateType;
using LookupType = typename AbstractMachine<T>::LookupType;
// Json constructor
explicit RbmMultival(const Hilbert &hilbert, const json &pars)
: nv_(hilbert.Size()), hilbert_(hilbert), ls_(hilbert.LocalSize()) {
from_json(pars);
}
void Init() {
W_.resize(nv_ * ls_, nh_);
a_.resize(nv_ * ls_);
b_.resize(nh_);
thetas_.resize(nh_);
lnthetas_.resize(nh_);
thetasnew_.resize(nh_);
lnthetasnew_.resize(nh_);
npar_ = nv_ * nh_ * ls_;
if (usea_) {
npar_ += nv_ * ls_;
} else {
a_.setZero();
}
if (useb_) {
npar_ += nh_;
} else {
b_.setZero();
}
auto localstates = hilbert_.LocalStates();
localconfs_.resize(nv_ * ls_);
for (int i = 0; i < nv_ * ls_; i += ls_) {
for (int j = 0; j < ls_; j++) {
localconfs_(i + j) = localstates[j];
}
}
mask_.resize(nv_ * ls_, nv_);
mask_.setZero();
for (int i = 0; i < nv_ * ls_; i++) {
mask_(i, i / ls_) = 1;
}
for (int i = 0; i < ls_; i++) {
confindex_[localstates[i]] = i;
}
vtilde_.resize(nv_ * ls_);
InfoMessage() << "RBM Multival Initizialized with nvisible = " << nv_
<< " and nhidden = " << nh_ << std::endl;
InfoMessage() << "Using visible bias = " << usea_ << std::endl;
InfoMessage() << "Using hidden bias = " << useb_ << std::endl;
InfoMessage() << "Local size is = " << ls_ << std::endl;
}
int Nvisible() const override { return nv_; }
int Nhidden() const { return nh_; }
int Npar() const override { return npar_; }
void InitRandomPars(int seed, double sigma) override {
VectorType par(npar_);
netket::RandomGaussian(par, seed, sigma);
SetParameters(par);
}
void InitLookup(const Eigen::VectorXd &v, LookupType <) override {
if (lt.VectorSize() == 0) {
lt.AddVector(b_.size());
}
if (lt.V(0).size() != b_.size()) {
lt.V(0).resize(b_.size());
}
ComputeTheta(v, lt.V(0));
}
void UpdateLookup(const Eigen::VectorXd &v, const std::vector<int> &tochange,
const std::vector<double> &newconf,
LookupType <) override {
if (tochange.size() != 0) {
for (std::size_t s = 0; s < tochange.size(); s++) {
const int sf = tochange[s];
const int oldtilde = confindex_[v[sf]];
const int newtilde = confindex_[newconf[s]];
lt.V(0) -= W_.row(ls_ * sf + oldtilde);
lt.V(0) += W_.row(ls_ * sf + newtilde);
}
}
}
VectorType DerLog(const Eigen::VectorXd &v) override {
VectorType der(npar_);
der.setZero();
int k = 0;
ComputeTheta(v, thetas_);
if (usea_) {
for (; k < nv_ * ls_; k++) {
der(k) = vtilde_(k);
}
}
RbmSpin<T>::tanh(thetas_, lnthetas_);
if (useb_) {
for (int p = 0; p < nh_; p++) {
der(k) = lnthetas_(p);
k++;
}
}
for (int i = 0; i < nv_ * ls_; i++) {
for (int j = 0; j < nh_; j++) {
der(k) = lnthetas_(j) * vtilde_(i);
k++;
}
}
return der;
}
VectorType GetParameters() override {
VectorType pars(npar_);
int k = 0;
if (usea_) {
for (; k < nv_ * ls_; k++) {
pars(k) = a_(k);
}
}
if (useb_) {
for (int p = 0; p < nh_; p++) {
pars(k) = b_(p);
k++;
}
}
for (int i = 0; i < nv_ * ls_; i++) {
for (int j = 0; j < nh_; j++) {
pars(k) = W_(i, j);
k++;
}
}
return pars;
}
void SetParameters(const VectorType &pars) override {
int k = 0;
if (usea_) {
for (; k < nv_ * ls_; k++) {
a_(k) = pars(k);
}
}
if (useb_) {
for (int p = 0; p < nh_; p++) {
b_(p) = pars(k);
k++;
}
}
for (int i = 0; i < nv_ * ls_; i++) {
for (int j = 0; j < nh_; j++) {
W_(i, j) = pars(k);
k++;
}
}
}
// Value of the logarithm of the wave-function
T LogVal(const Eigen::VectorXd &v) override {
ComputeTheta(v, thetas_);
RbmSpin<T>::lncosh(thetas_, lnthetas_);
return (vtilde_.dot(a_) + lnthetas_.sum());
}
// Value of the logarithm of the wave-function
// using pre-computed look-up tables for efficiency
T LogVal(const Eigen::VectorXd &v, const LookupType <) override {
RbmSpin<T>::lncosh(lt.V(0), lnthetas_);
ComputeVtilde(v, vtilde_);
return (vtilde_.dot(a_) + lnthetas_.sum());
}
// Difference between logarithms of values, when one or more visible variables
// are being changed
VectorType LogValDiff(
const Eigen::VectorXd &v, const std::vector<std::vector<int>> &tochange,
const std::vector<std::vector<double>> &newconf) override {
const std::size_t nconn = tochange.size();
VectorType logvaldiffs = VectorType::Zero(nconn);
ComputeTheta(v, thetas_);
RbmSpin<T>::lncosh(thetas_, lnthetas_);
T logtsum = lnthetas_.sum();
for (std::size_t k = 0; k < nconn; k++) {
if (tochange[k].size() != 0) {
thetasnew_ = thetas_;
for (std::size_t s = 0; s < tochange[k].size(); s++) {
const int sf = tochange[k][s];
const int oldtilde = confindex_[v[sf]];
const int newtilde = confindex_[newconf[k][s]];
logvaldiffs(k) -= a_(ls_ * sf + oldtilde);
logvaldiffs(k) += a_(ls_ * sf + newtilde);
thetasnew_ -= W_.row(ls_ * sf + oldtilde);
thetasnew_ += W_.row(ls_ * sf + newtilde);
}
RbmSpin<T>::lncosh(thetasnew_, lnthetasnew_);
logvaldiffs(k) += lnthetasnew_.sum() - logtsum;
}
}
return logvaldiffs;
}
// Difference between logarithms of values, when one or more visible variables
// are being changed Version using pre-computed look-up tables for efficiency
// on a small number of local changes
T LogValDiff(const Eigen::VectorXd &v, const std::vector<int> &tochange,
const std::vector<double> &newconf,
const LookupType <) override {
T logvaldiff = 0.;
if (tochange.size() != 0) {
RbmSpin<T>::lncosh(lt.V(0), lnthetas_);
thetasnew_ = lt.V(0);
for (std::size_t s = 0; s < tochange.size(); s++) {
const int sf = tochange[s];
const int oldtilde = confindex_[v[sf]];
const int newtilde = confindex_[newconf[s]];
logvaldiff -= a_(ls_ * sf + oldtilde);
logvaldiff += a_(ls_ * sf + newtilde);
thetasnew_ -= W_.row(ls_ * sf + oldtilde);
thetasnew_ += W_.row(ls_ * sf + newtilde);
}
RbmSpin<T>::lncosh(thetasnew_, lnthetasnew_);
logvaldiff += (lnthetasnew_.sum() - lnthetas_.sum());
}
return logvaldiff;
}
// Computhes the values of the theta pseudo-angles
inline void ComputeTheta(const Eigen::VectorXd &v, VectorType &theta) {
ComputeVtilde(v, vtilde_);
theta = (W_.transpose() * vtilde_ + b_);
}
inline void ComputeVtilde(const Eigen::VectorXd &v, Eigen::VectorXd &vtilde) {
auto t = (localconfs_.array() == (mask_ * v).array());
vtilde = t.template cast<double>();
}
const Hilbert &GetHilbert() const { return hilbert_; }
void to_json(json &j) const override {
j["Machine"]["Name"] = "RbmMultival";
j["Machine"]["Nvisible"] = nv_;
j["Machine"]["Nhidden"] = nh_;
j["Machine"]["LocalSize"] = ls_;
j["Machine"]["UseVisibleBias"] = usea_;
j["Machine"]["UseHiddenBias"] = useb_;
j["Machine"]["a"] = a_;
j["Machine"]["b"] = b_;
j["Machine"]["W"] = W_;
}
void from_json(const json &pars) override {
if (pars.at("Machine").at("Name") != "RbmMultival") {
throw InvalidInputError(
"Error while constructing RbmMultival from Json input");
}
if (FieldExists(pars["Machine"], "Nvisible")) {
nv_ = pars["Machine"]["Nvisible"];
}
if (nv_ != hilbert_.Size()) {
throw InvalidInputError(
"Loaded wave-function has incompatible Hilbert space");
}
if (FieldExists(pars["Machine"], "LocalSize")) {
ls_ = pars["Machine"]["LocalSize"];
}
if (ls_ != hilbert_.LocalSize()) {
throw InvalidInputError(
"Loaded wave-function has incompatible Hilbert space");
}
if (FieldExists(pars["Machine"], "Nhidden")) {
nh_ = FieldVal(pars["Machine"], "Nhidden");
} else {
nh_ = nv_ * double(FieldVal(pars["Machine"], "Alpha"));
}
usea_ = FieldOrDefaultVal(pars["Machine"], "UseVisibleBias", true);
useb_ = FieldOrDefaultVal(pars["Machine"], "UseHiddenBias", true);
Init();
// Loading parameters, if defined in the input
if (FieldExists(pars["Machine"], "a")) {
a_ = pars["Machine"]["a"];
} else {
a_.setZero();
}
if (FieldExists(pars["Machine"], "b")) {
b_ = pars["Machine"]["b"];
} else {
b_.setZero();
}
if (FieldExists(pars["Machine"], "W")) {
W_ = pars["Machine"]["W"];
}
}
};
} // namespace netket
#endif
| 25.502358 | 80 | 0.582077 | [
"vector"
] |
a0aacf18c5e060584effadf61276ba7d6330fc65 | 1,993 | hpp | C++ | src/setka/init_guard.hpp | cppfw/setka | 050be1355eaf150d2c86433fba5c5d3d410d56c1 | [
"MIT"
] | null | null | null | src/setka/init_guard.hpp | cppfw/setka | 050be1355eaf150d2c86433fba5c5d3d410d56c1 | [
"MIT"
] | 2 | 2015-09-29T15:07:35.000Z | 2020-05-09T20:07:05.000Z | src/setka/init_guard.hpp | cppfw/setka | 050be1355eaf150d2c86433fba5c5d3d410d56c1 | [
"MIT"
] | 1 | 2020-12-15T01:42:48.000Z | 2020-12-15T01:42:48.000Z | /*
The MIT License (MIT)
Copyright (c) 2015-2021 Ivan Gagis <igagis@gmail.com>
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.
*/
/* ================ LICENSE END ================ */
#pragma once
#include <utki/singleton.hpp>
#include <utki/config.hpp>
namespace setka{
/**
* @brief Socket library singleton class.
* This is a Socket library singleton class. Creating an object of this class initializes the library
* while destroying this object de-initializes it. So, the convenient way of initializing the library
* is to create an object of this class on the stack. Thus, when the object goes out of scope its
* destructor will be called and the library will be de-initialized automatically.
* This is what C++ RAII is all about.
*/
class init_guard : public utki::intrusive_singleton<init_guard>{
friend class utki::intrusive_singleton<init_guard>;
static utki::intrusive_singleton<init_guard>::T_Instance instance;
public:
init_guard();
~init_guard()noexcept;
};
}
| 37.603774 | 102 | 0.757652 | [
"object"
] |
a0ab8d79f41b69d6ce3e6d29d63b8a75357e85fa | 81,589 | cpp | C++ | rmw_cyclonedds_cpp/src/rmw_node.cpp | alsora/rmw_cyclonedds | 1e09e160e9df293c20ec137080bdfbe31a559c3f | [
"Apache-2.0"
] | null | null | null | rmw_cyclonedds_cpp/src/rmw_node.cpp | alsora/rmw_cyclonedds | 1e09e160e9df293c20ec137080bdfbe31a559c3f | [
"Apache-2.0"
] | null | null | null | rmw_cyclonedds_cpp/src/rmw_node.cpp | alsora/rmw_cyclonedds | 1e09e160e9df293c20ec137080bdfbe31a559c3f | [
"Apache-2.0"
] | null | null | null | // Copyright 2019 ADLINK Technology Limited.
//
// 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 <mutex>
#include <unordered_set>
#include <algorithm>
#include <map>
#include <set>
#include <functional>
#include <atomic>
#include <regex>
#include "rcutils/logging_macros.h"
#include "rcutils/strdup.h"
#include "rmw/allocators.h"
#include "rmw/convert_rcutils_ret_to_rmw_ret.h"
#include "rmw/error_handling.h"
#include "rmw/names_and_types.h"
#include "rmw/get_service_names_and_types.h"
#include "rmw/get_topic_names_and_types.h"
#include "rmw/get_node_info_and_types.h"
#include "rmw/rmw.h"
#include "rmw/sanity_checks.h"
#include "rmw/impl/cpp/macros.hpp"
#include "rmw_cyclonedds_cpp/MessageTypeSupport.hpp"
#include "rmw_cyclonedds_cpp/ServiceTypeSupport.hpp"
#include "namespace_prefix.hpp"
#include "dds/dds.h"
#include "dds/ddsi/ddsi_sertopic.h"
#include "rmw_cyclonedds_cpp/serdes.hpp"
#include "rmw_cyclonedds_cpp/serdata.hpp"
#define RET_ERR_X(msg, code) do { RMW_SET_ERROR_MSG (msg); code; } while (0)
#define RET_NULL_X(var, code) do { if (!var) RET_ERR_X (#var " is null", code); } while (0)
#define RET_ALLOC_X(var, code) do { if (!var) RET_ERR_X ("failed to allocate " #var, code); } while (0)
#define RET_WRONG_IMPLID_X(var, code) do { \
RET_NULL_X (var, code); \
if ((var)->implementation_identifier != eclipse_cyclonedds_identifier) { \
RET_ERR_X (#var " not from this implementation", code); \
} \
} while (0)
#define RET_NULL_OR_EMPTYSTR_X(var, code) do { \
if (!var || strlen (var) == 0) { \
RET_ERR_X (#var " is null or empty string", code); \
} \
} while (0)
#define RET_ERR(msg) RET_ERR_X (msg, return RMW_RET_ERROR)
#define RET_NULL(var) RET_NULL_X (var, return RMW_RET_ERROR)
#define RET_ALLOC(var) RET_ALLOC_X (var, return RMW_RET_ERROR)
#define RET_WRONG_IMPLID(var) RET_WRONG_IMPLID_X (var, return RMW_RET_ERROR)
#define RET_NULL_OR_EMPTYSTR(var) RET_NULL_OR_EMPTYSTR_X (var, return RMW_RET_ERROR)
const char *const eclipse_cyclonedds_identifier = "rmw_cyclonedds_cpp";
const char * const eclipse_cyclonedds_serialization_format = "cdr";
/* instance handles are unsigned 64-bit integers carefully constructed to be as close to uniformly
distributed as possible for no other reason than making them near-perfect hash keys, hence we can
improve over the default hash function */
struct dds_instance_handle_hash {
public:
std::size_t operator() (dds_instance_handle_t const& x) const noexcept {
return static_cast<std::size_t> (x);
}
};
bool operator< (dds_builtintopic_guid_t const& a, dds_builtintopic_guid_t const& b) {
return (memcmp (&a, &b, sizeof (dds_builtintopic_guid_t)) < 0);
}
static const dds_entity_t builtin_topics[] = {
DDS_BUILTIN_TOPIC_DCPSPARTICIPANT,
DDS_BUILTIN_TOPIC_DCPSSUBSCRIPTION,
DDS_BUILTIN_TOPIC_DCPSPUBLICATION
};
struct CddsNode {
dds_entity_t pp;
dds_entity_t pub;
dds_entity_t sub;
rmw_guard_condition_t *graph_guard_condition;
};
struct CddsPublisher {
dds_entity_t pubh;
dds_instance_handle_t pubiid;
struct ddsi_sertopic *sertopic;
};
struct CddsSubscription {
dds_entity_t subh;
dds_entity_t rdcondh;
struct ddsi_sertopic *sertopic;
};
struct CddsCS {
CddsPublisher *pub;
CddsSubscription *sub;
};
struct CddsClient {
CddsCS client;
};
struct CddsService {
CddsCS service;
};
struct CddsGuardCondition {
dds_entity_t gcondh;
};
struct CddsWaitset {
dds_entity_t waitseth;
std::vector<dds_attach_t> trigs;
std::mutex lock;
bool inuse;
std::vector<CddsSubscription *> subs;
std::vector<CddsGuardCondition *> gcs;
std::vector<CddsClient *> cls;
std::vector<CddsService *> srvs;
};
struct Cdds {
std::mutex lock;
uint32_t refcount;
dds_entity_t ppant;
dds_entity_t builtin_readers[sizeof (builtin_topics) / sizeof (builtin_topics[0])];
/* set of waitsets protected by lock, used to invalidate all waitsets caches when an entity is
deleted */
std::unordered_set<CddsWaitset *> waitsets;
/* set of nodes is used to trigger graph guard conditions when something changes, but that
something also changes when creating the built-in readers when Cdds::lock is already held */
std::mutex nodes_lock;
std::unordered_set<CddsNode *> nodes;
Cdds () : refcount (0), ppant (0) {}
};
static Cdds gcdds;
static void clean_waitset_caches ();
#ifndef WIN32
/* TODO(allenh1): check for Clang */
#pragma GCC visibility push (default)
#endif
extern "C" const char *rmw_get_implementation_identifier ()
{
return eclipse_cyclonedds_identifier;
}
extern "C" const char *rmw_get_serialization_format()
{
return eclipse_cyclonedds_serialization_format;
}
extern "C" rmw_ret_t rmw_set_log_severity (rmw_log_severity_t severity)
{
static_cast<void>(severity);
RMW_SET_ERROR_MSG ("unimplemented");
return RMW_RET_ERROR;
}
extern "C" rmw_ret_t rmw_context_fini (rmw_context_t *context)
{
RCUTILS_CHECK_ARGUMENT_FOR_NULL (context, RMW_RET_INVALID_ARGUMENT);
RMW_CHECK_TYPE_IDENTIFIERS_MATCH (
context,
context->implementation_identifier,
eclipse_cyclonedds_identifier,
return RMW_RET_INCORRECT_RMW_IMPLEMENTATION);
// context impl is explicitly supposed to be nullptr for now, see rmw_init's code
// RCUTILS_CHECK_ARGUMENT_FOR_NULL(context->impl, RMW_RET_INVALID_ARGUMENT);
*context = rmw_get_zero_initialized_context ();
return RMW_RET_OK;
}
extern "C" rmw_ret_t rmw_init_options_init (rmw_init_options_t *init_options, rcutils_allocator_t allocator)
{
RMW_CHECK_ARGUMENT_FOR_NULL (init_options, RMW_RET_INVALID_ARGUMENT);
RCUTILS_CHECK_ALLOCATOR (&allocator, return RMW_RET_INVALID_ARGUMENT);
if (NULL != init_options->implementation_identifier) {
RMW_SET_ERROR_MSG ("expected zero-initialized init_options");
return RMW_RET_INVALID_ARGUMENT;
}
init_options->instance_id = 0;
init_options->implementation_identifier = eclipse_cyclonedds_identifier;
init_options->allocator = allocator;
init_options->impl = nullptr;
return RMW_RET_OK;
}
extern "C" rmw_ret_t rmw_init_options_copy (const rmw_init_options_t *src, rmw_init_options_t *dst)
{
RMW_CHECK_ARGUMENT_FOR_NULL (src, RMW_RET_INVALID_ARGUMENT);
RMW_CHECK_ARGUMENT_FOR_NULL (dst, RMW_RET_INVALID_ARGUMENT);
RMW_CHECK_TYPE_IDENTIFIERS_MATCH (
src,
src->implementation_identifier,
eclipse_cyclonedds_identifier,
return RMW_RET_INCORRECT_RMW_IMPLEMENTATION);
if (NULL != dst->implementation_identifier) {
RMW_SET_ERROR_MSG ("expected zero-initialized dst");
return RMW_RET_INVALID_ARGUMENT;
}
*dst = *src;
return RMW_RET_OK;
}
extern "C" rmw_ret_t rmw_init_options_fini (rmw_init_options_t *init_options)
{
RMW_CHECK_ARGUMENT_FOR_NULL (init_options, RMW_RET_INVALID_ARGUMENT);
RCUTILS_CHECK_ALLOCATOR (&init_options->allocator, return RMW_RET_INVALID_ARGUMENT);
RMW_CHECK_TYPE_IDENTIFIERS_MATCH (
init_options,
init_options->implementation_identifier,
eclipse_cyclonedds_identifier,
return RMW_RET_INCORRECT_RMW_IMPLEMENTATION);
*init_options = rmw_get_zero_initialized_init_options ();
return RMW_RET_OK;
}
extern "C" rmw_ret_t rmw_init (const rmw_init_options_t *options, rmw_context_t *context)
{
static_cast<void>(options);
static_cast<void>(context);
RCUTILS_CHECK_ARGUMENT_FOR_NULL (options, RMW_RET_INVALID_ARGUMENT);
RCUTILS_CHECK_ARGUMENT_FOR_NULL (context, RMW_RET_INVALID_ARGUMENT);
RMW_CHECK_TYPE_IDENTIFIERS_MATCH (
options,
options->implementation_identifier,
eclipse_cyclonedds_identifier,
return RMW_RET_INCORRECT_RMW_IMPLEMENTATION);
context->instance_id = options->instance_id;
context->implementation_identifier = eclipse_cyclonedds_identifier;
context->impl = nullptr;
return RMW_RET_OK;
}
extern "C" rmw_ret_t rmw_node_assert_liveliness (const rmw_node_t *node)
{
RET_WRONG_IMPLID (node);
return RMW_RET_OK;
}
extern "C" rmw_ret_t rmw_shutdown (rmw_context_t *context)
{
RCUTILS_CHECK_ARGUMENT_FOR_NULL (context, RMW_RET_INVALID_ARGUMENT);
RMW_CHECK_TYPE_IDENTIFIERS_MATCH (
context,
context->implementation_identifier,
eclipse_cyclonedds_identifier,
return RMW_RET_INCORRECT_RMW_IMPLEMENTATION);
// context impl is explicitly supposed to be nullptr for now, see rmw_init's code
// RCUTILS_CHECK_ARGUMENT_FOR_NULL (context->impl, RMW_RET_INVALID_ARGUMENT);
*context = rmw_get_zero_initialized_context ();
return RMW_RET_OK;
}
static void ggcallback (dds_entity_t rd, void *varg)
{
static_cast<void>(varg);
void *msg = 0;
dds_sample_info_t info;
while (dds_take (rd, &msg, &info, 1, 1) > 0) {
dds_return_loan (rd, &msg, 1);
}
{
std::lock_guard<std::mutex> lock (gcdds.nodes_lock);
for (auto&& node_impl : gcdds.nodes) {
if (rmw_trigger_guard_condition (node_impl->graph_guard_condition) != RMW_RET_OK) {
RCUTILS_LOG_ERROR_NAMED ("rmw_cyclonedds_cpp", "failed to trigger graph guard condition");
}
}
}
}
static dds_entity_t ref_ppant ()
{
std::lock_guard<std::mutex> lock (gcdds.lock);
if (gcdds.refcount == 0) {
if ((gcdds.ppant = dds_create_participant (DDS_DOMAIN_DEFAULT, nullptr, nullptr)) < 0) {
RMW_SET_ERROR_MSG ("failed to create participant");
return gcdds.ppant;
}
static_assert (sizeof (gcdds.builtin_readers) / sizeof (gcdds.builtin_readers[0]) ==
sizeof (builtin_topics) / sizeof (builtin_topics[0]),
"mismatch between array of built-in topics and array of built-in readers");
dds_listener_t *gglistener = dds_create_listener (nullptr);
dds_lset_data_available (gglistener, ggcallback);
for (size_t i = 0; i < sizeof (builtin_topics) / sizeof (builtin_topics[0]); i++) {
dds_entity_t rd = dds_create_reader (gcdds.ppant, builtin_topics[i], nullptr, gglistener);
if (rd < 0) {
RCUTILS_LOG_ERROR_NAMED ("rmw_cyclonedds_cpp", "rmw_create_node: failed to create DDS built-in reader");
while (i--) {
dds_delete (gcdds.builtin_readers[i]);
}
dds_delete (gcdds.ppant);
gcdds.ppant = 0;
return 0;
}
gcdds.builtin_readers[i] = rd;
}
dds_delete_listener (gglistener);
}
gcdds.refcount++;
return gcdds.ppant;
}
static void unref_ppant ()
{
std::lock_guard<std::mutex> lock (gcdds.lock);
if (--gcdds.refcount == 0) {
dds_delete (gcdds.ppant);
gcdds.ppant = 0;
}
}
/////////////////////////////////////////////////////////////////////////////////////////
/////////// ///////////
/////////// NODES ///////////
/////////// ///////////
/////////////////////////////////////////////////////////////////////////////////////////
static std::string get_node_user_data (const char *node_name, const char *node_namespace)
{
return (std::string ("name=") + std::string (node_name) +
std::string (";namespace=") + std::string (node_namespace) +
std::string (";"));
}
extern "C" rmw_node_t *rmw_create_node (rmw_context_t *context, const char *name, const char *namespace_, size_t domain_id, const rmw_node_security_options_t *security_options)
{
static_cast<void>(context);
RET_NULL_X (name, return nullptr);
RET_NULL_X (namespace_, return nullptr);
(void) domain_id;
(void) security_options;
dds_qos_t *qos = dds_create_qos ();
std::string user_data = get_node_user_data (name, namespace_);
dds_qset_userdata (qos, user_data.c_str (), user_data.size ());
dds_entity_t pp = dds_create_participant (DDS_DOMAIN_DEFAULT, qos, nullptr);
dds_delete_qos (qos);
if (pp < 0) {
RCUTILS_LOG_ERROR_NAMED ("rmw_cyclonedds_cpp", "rmw_create_node: failed to create DDS participant");
return nullptr;
}
dds_entity_t pub, sub;
if ((pub = dds_create_publisher (pp, nullptr, nullptr)) < 0) {
RCUTILS_LOG_ERROR_NAMED ("rmw_cyclonedds_cpp", "rmw_create_node: failed to create DDS publisher");
dds_delete (pp);
return nullptr;
}
if ((sub = dds_create_subscriber (pp, nullptr, nullptr)) < 0) {
RCUTILS_LOG_ERROR_NAMED ("rmw_cyclonedds_cpp", "rmw_create_node: failed to create DDS subscriber");
dds_delete (pp);
return nullptr;
}
auto *node_impl = new CddsNode ();
rmw_node_t *node_handle = nullptr;
RET_ALLOC_X (node_impl, goto fail_node_impl);
rmw_guard_condition_t *graph_guard_condition;
if (!(graph_guard_condition = rmw_create_guard_condition (context))) {
goto fail_ggc;
}
node_impl->pp = pp;
node_impl->pub = pub;
node_impl->sub = sub;
node_impl->graph_guard_condition = graph_guard_condition;
{
std::lock_guard<std::mutex> lock (gcdds.nodes_lock);
gcdds.nodes.insert (node_impl);
}
/* FIXME: should there be a (potentially spurious) trigger of the graph guard condition here? */
node_handle = rmw_node_allocate ();
RET_ALLOC_X (node_handle, goto fail_node_handle);
node_handle->implementation_identifier = eclipse_cyclonedds_identifier;
node_handle->data = node_impl;
node_handle->name = static_cast<const char *> (rmw_allocate (sizeof (char) * strlen (name) + 1));
RET_ALLOC_X (node_handle->name, goto fail_node_handle_name);
memcpy (const_cast<char *> (node_handle->name), name, strlen (name) + 1);
node_handle->namespace_ = static_cast<const char *> (rmw_allocate (sizeof (char) * strlen (namespace_) + 1));
RET_ALLOC_X (node_handle->namespace_, goto fail_node_handle_namespace);
memcpy (const_cast<char *> (node_handle->namespace_), namespace_, strlen (namespace_) + 1);
return node_handle;
#if 0
fail_add_node:
rmw_free (const_cast<char *> (node_handle->namespace_));
#endif
fail_node_handle_namespace:
rmw_free (const_cast<char *> (node_handle->name));
fail_node_handle_name:
rmw_node_free (node_handle);
fail_node_handle:
{
std::lock_guard<std::mutex> lock (gcdds.nodes_lock);
gcdds.nodes.erase (node_impl);
}
if (RMW_RET_OK != rmw_destroy_guard_condition (graph_guard_condition)) {
RCUTILS_LOG_ERROR_NAMED ("rmw_cyclonedds_cpp", "failed to destroy guard condition during error handling");
}
fail_ggc:
delete node_impl;
fail_node_impl:
dds_delete (pp);
return nullptr;
}
extern "C" rmw_ret_t rmw_destroy_node (rmw_node_t *node)
{
rmw_ret_t result_ret = RMW_RET_OK;
RET_WRONG_IMPLID (node);
auto node_impl = static_cast<CddsNode *> (node->data);
RET_NULL (node_impl);
rmw_free (const_cast<char *> (node->name));
rmw_free (const_cast<char *> (node->namespace_));
rmw_node_free (node);
{
std::lock_guard<std::mutex> lock (gcdds.nodes_lock);
gcdds.nodes.erase (node_impl);
}
if (RMW_RET_OK != rmw_destroy_guard_condition (node_impl->graph_guard_condition)) {
RMW_SET_ERROR_MSG ("failed to destroy graph guard condition");
result_ret = RMW_RET_ERROR;
}
if (dds_delete (node_impl->pp) < 0) {
RMW_SET_ERROR_MSG ("failed to destroy DDS participant");
result_ret = RMW_RET_ERROR;
}
delete node_impl;
return result_ret;
}
extern "C" const rmw_guard_condition_t *rmw_node_get_graph_guard_condition (const rmw_node_t *node)
{
RET_WRONG_IMPLID_X (node, return nullptr);
auto node_impl = static_cast<CddsNode *> (node->data);
RET_NULL_X (node_impl, return nullptr);
return node_impl->graph_guard_condition;
}
/////////////////////////////////////////////////////////////////////////////////////////
/////////// ///////////
/////////// (DE)SERIALIZATION ///////////
/////////// ///////////
/////////////////////////////////////////////////////////////////////////////////////////
using MessageTypeSupport_c = rmw_cyclonedds_cpp::MessageTypeSupport<rosidl_typesupport_introspection_c__MessageMembers>;
using MessageTypeSupport_cpp = rmw_cyclonedds_cpp::MessageTypeSupport<rosidl_typesupport_introspection_cpp::MessageMembers>;
extern "C" rmw_ret_t rmw_get_serialized_message_size (const rosidl_message_type_support_t *type_support, const rosidl_message_bounds_t *message_bounds, size_t *size)
{
static_cast<void>(type_support);
static_cast<void>(message_bounds);
static_cast<void>(size);
RMW_SET_ERROR_MSG ("rmw_get_serialized_message_size: unimplemented");
return RMW_RET_ERROR;
}
extern "C" rmw_ret_t rmw_serialize (const void *ros_message, const rosidl_message_type_support_t *type_support, rmw_serialized_message_t *serialized_message)
{
std::vector<unsigned char> data;
cycser sd (data);
rmw_ret_t ret;
const rosidl_message_type_support_t *ts;
if ((ts = get_message_typesupport_handle (type_support, rosidl_typesupport_introspection_c__identifier)) != nullptr) {
auto members = static_cast<const rosidl_typesupport_introspection_c__MessageMembers *> (ts->data);
MessageTypeSupport_c msgts (members);
msgts.serializeROSmessage (ros_message, sd, nullptr);
} else if ((ts = get_message_typesupport_handle (type_support, rosidl_typesupport_introspection_cpp::typesupport_identifier)) != nullptr) {
auto members = static_cast<const rosidl_typesupport_introspection_cpp::MessageMembers *> (ts->data);
MessageTypeSupport_cpp msgts (members);
msgts.serializeROSmessage (ros_message, sd, nullptr);
} else {
RMW_SET_ERROR_MSG ("rmw_serialize: type support trouble");
return RMW_RET_ERROR;
}
/* FIXME: what about the header - should be included or not? */
if ((ret = rmw_serialized_message_resize (serialized_message, data.size ())) != RMW_RET_OK) {
return ret;
}
memcpy (serialized_message->buffer, data.data (), data.size ());
serialized_message->buffer_length = data.size ();
return RMW_RET_OK;
}
extern "C" rmw_ret_t rmw_deserialize (const rmw_serialized_message_t *serialized_message, const rosidl_message_type_support_t *type_support, void *ros_message)
{
cycdeser sd (serialized_message->buffer, serialized_message->buffer_length);
bool ok;
const rosidl_message_type_support_t *ts;
if ((ts = get_message_typesupport_handle (type_support, rosidl_typesupport_introspection_c__identifier)) != nullptr) {
auto members = static_cast<const rosidl_typesupport_introspection_c__MessageMembers *> (ts->data);
MessageTypeSupport_c msgts (members);
ok = msgts.deserializeROSmessage (sd, ros_message, nullptr);
} else if ((ts = get_message_typesupport_handle (type_support, rosidl_typesupport_introspection_cpp::typesupport_identifier)) != nullptr) {
auto members = static_cast<const rosidl_typesupport_introspection_cpp::MessageMembers *> (ts->data);
MessageTypeSupport_cpp msgts (members);
ok = msgts.deserializeROSmessage (sd, ros_message, nullptr);
} else {
RMW_SET_ERROR_MSG ("rmw_serialize: type support trouble");
return RMW_RET_ERROR;
}
return ok ? RMW_RET_OK : RMW_RET_ERROR;
}
/////////////////////////////////////////////////////////////////////////////////////////
/////////// ///////////
/////////// PUBLICATIONS ///////////
/////////// ///////////
/////////////////////////////////////////////////////////////////////////////////////////
extern "C" rmw_ret_t rmw_publish (const rmw_publisher_t *publisher, const void *ros_message, rmw_publisher_allocation_t *allocation)
{
static_cast<void>(allocation); // unused
RET_WRONG_IMPLID (publisher);
RET_NULL (ros_message);
auto pub = static_cast<CddsPublisher *> (publisher->data);
assert (pub);
if (dds_write (pub->pubh, ros_message) >= 0) {
return RMW_RET_OK;
} else {
RMW_SET_ERROR_MSG ("failed to publish data");
return RMW_RET_ERROR;
}
}
extern "C" rmw_ret_t rmw_publish_serialized_message (const rmw_publisher_t *publisher, const rmw_serialized_message_t *serialized_message, rmw_publisher_allocation_t *allocation)
{
static_cast<void>(allocation); // unused
RET_WRONG_IMPLID (publisher);
RET_NULL (serialized_message);
auto pub = static_cast<CddsPublisher *> (publisher->data);
struct ddsi_serdata *d = serdata_rmw_from_serialized_message (pub->sertopic, serialized_message->buffer, serialized_message->buffer_length);
const bool ok = (dds_writecdr (pub->pubh, d) >= 0);
return ok ? RMW_RET_OK : RMW_RET_ERROR;
}
static const rosidl_message_type_support_t *get_typesupport (const rosidl_message_type_support_t *type_supports)
{
const rosidl_message_type_support_t *ts;
if ((ts = get_message_typesupport_handle (type_supports, rosidl_typesupport_introspection_c__identifier)) != nullptr) {
return ts;
} else if ((ts = get_message_typesupport_handle (type_supports, rosidl_typesupport_introspection_cpp::typesupport_identifier)) != nullptr) {
return ts;
} else {
RMW_SET_ERROR_MSG ("type support not from this implementation");
return nullptr;
}
}
static std::string make_fqtopic (const char *prefix, const char *topic_name, const char *suffix, bool avoid_ros_namespace_conventions)
{
if (avoid_ros_namespace_conventions) {
return std::string (topic_name) + "__" + std::string (suffix);
} else {
return std::string (prefix) + std::string (topic_name) + std::string (suffix);
}
}
static std::string make_fqtopic (const char *prefix, const char *topic_name, const char *suffix, const rmw_qos_profile_t *qos_policies)
{
return make_fqtopic (prefix, topic_name, suffix, qos_policies->avoid_ros_namespace_conventions);
}
static dds_qos_t *create_readwrite_qos (const rmw_qos_profile_t *qos_policies, bool ignore_local_publications)
{
dds_qos_t *qos = dds_create_qos ();
switch (qos_policies->history) {
case RMW_QOS_POLICY_HISTORY_SYSTEM_DEFAULT:
case RMW_QOS_POLICY_HISTORY_UNKNOWN:
case RMW_QOS_POLICY_HISTORY_KEEP_LAST:
if (qos_policies->depth > INT32_MAX) {
RMW_SET_ERROR_MSG ("unsupported history depth");
dds_delete_qos (qos);
return nullptr;
}
dds_qset_history (qos, DDS_HISTORY_KEEP_LAST, static_cast<uint32_t> (qos_policies->depth));
break;
case RMW_QOS_POLICY_HISTORY_KEEP_ALL:
dds_qset_history (qos, DDS_HISTORY_KEEP_ALL, DDS_LENGTH_UNLIMITED);
break;
}
switch (qos_policies->reliability) {
case RMW_QOS_POLICY_RELIABILITY_SYSTEM_DEFAULT:
case RMW_QOS_POLICY_RELIABILITY_UNKNOWN:
case RMW_QOS_POLICY_RELIABILITY_RELIABLE:
dds_qset_reliability (qos, DDS_RELIABILITY_RELIABLE, DDS_INFINITY);
break;
case RMW_QOS_POLICY_RELIABILITY_BEST_EFFORT:
dds_qset_reliability (qos, DDS_RELIABILITY_BEST_EFFORT, 0);
break;
}
switch (qos_policies->durability) {
case RMW_QOS_POLICY_DURABILITY_SYSTEM_DEFAULT:
case RMW_QOS_POLICY_DURABILITY_UNKNOWN:
case RMW_QOS_POLICY_DURABILITY_VOLATILE:
dds_qset_durability (qos, DDS_DURABILITY_VOLATILE);
break;
case RMW_QOS_POLICY_DURABILITY_TRANSIENT_LOCAL:
dds_qset_durability (qos, DDS_DURABILITY_TRANSIENT_LOCAL);
break;
}
if (ignore_local_publications) {
dds_qset_ignorelocal (qos, DDS_IGNORELOCAL_PARTICIPANT);
}
return qos;
}
static bool get_readwrite_qos (dds_entity_t handle, rmw_qos_profile_t *qos_policies)
{
dds_qos_t *qos = dds_create_qos ();
if (dds_get_qos (handle, qos) < 0) {
RMW_SET_ERROR_MSG ("get_readwrite_qos: invalid handle");
goto error;
}
{
dds_history_kind_t kind;
int32_t depth;
if (!dds_qget_history (qos, &kind, &depth)) {
RMW_SET_ERROR_MSG ("get_readwrite_qos: history not set");
goto error;
}
switch (kind) {
case DDS_HISTORY_KEEP_LAST:
qos_policies->history = RMW_QOS_POLICY_HISTORY_KEEP_LAST;
qos_policies->depth = (uint32_t) depth;
break;
case DDS_HISTORY_KEEP_ALL:
qos_policies->history = RMW_QOS_POLICY_HISTORY_KEEP_ALL;
qos_policies->depth = 0;
break;
}
}
{
dds_reliability_kind_t kind;
dds_duration_t max_blocking_time;
if (!dds_qget_reliability (qos, &kind, &max_blocking_time)) {
RMW_SET_ERROR_MSG ("get_readwrite_qos: history not set");
goto error;
}
switch (kind) {
case DDS_RELIABILITY_BEST_EFFORT:
qos_policies->reliability = RMW_QOS_POLICY_RELIABILITY_BEST_EFFORT;
break;
case DDS_RELIABILITY_RELIABLE:
qos_policies->reliability = RMW_QOS_POLICY_RELIABILITY_RELIABLE;
break;
}
}
{
dds_durability_kind_t kind;
if (!dds_qget_durability (qos, &kind)){
RMW_SET_ERROR_MSG ("get_readwrite_qos: durability not set");
goto error;
}
switch (kind)
{
case DDS_DURABILITY_VOLATILE:
qos_policies->durability = RMW_QOS_POLICY_DURABILITY_VOLATILE;
break;
case DDS_DURABILITY_TRANSIENT_LOCAL:
qos_policies->durability = RMW_QOS_POLICY_DURABILITY_TRANSIENT_LOCAL;
break;
case DDS_DURABILITY_TRANSIENT:
case DDS_DURABILITY_PERSISTENT:
qos_policies->durability = RMW_QOS_POLICY_DURABILITY_UNKNOWN;
break;
}
}
dds_delete_qos (qos);
return true;
error:
dds_delete_qos (qos);
return false;
}
static CddsPublisher *create_cdds_publisher (const rmw_node_t *node, const rosidl_message_type_support_t *type_supports, const char *topic_name, const rmw_qos_profile_t *qos_policies)
{
RET_WRONG_IMPLID_X (node, return nullptr);
RET_NULL_OR_EMPTYSTR_X (topic_name, return nullptr);
RET_NULL_X (qos_policies, return nullptr);
auto node_impl = static_cast<CddsNode *> (node->data);
RET_NULL_X (node_impl, return nullptr);
const rosidl_message_type_support_t *type_support = get_typesupport (type_supports);
RET_NULL_X (type_support, return nullptr);
CddsPublisher *pub = new CddsPublisher ();
dds_entity_t topic;
dds_qos_t *qos;
std::string fqtopic_name = make_fqtopic (ros_topic_prefix, topic_name, "", qos_policies);
auto sertopic = create_sertopic (fqtopic_name.c_str (), type_support->typesupport_identifier, create_message_type_support (type_support->data, type_support->typesupport_identifier), false);
if ((topic = dds_create_topic_arbitrary (gcdds.ppant, sertopic, nullptr, nullptr, nullptr)) < 0) {
RMW_SET_ERROR_MSG ("failed to create topic");
goto fail_topic;
}
if ((qos = create_readwrite_qos (qos_policies, false)) == nullptr) {
goto fail_qos;
}
if ((pub->pubh = dds_create_writer (node_impl->pub, topic, qos, nullptr)) < 0) {
RMW_SET_ERROR_MSG ("failed to create writer");
goto fail_writer;
}
if (dds_get_instance_handle (pub->pubh, &pub->pubiid) < 0) {
RMW_SET_ERROR_MSG ("failed to get instance handle for writer");
goto fail_instance_handle;
}
/* FIXME: not guaranteed that "topic" will refer to "sertopic" because topic might have been
created earlier, but the two are equivalent, so this'll do */
pub->sertopic = sertopic;
dds_delete_qos (qos);
dds_delete (topic);
return pub;
fail_instance_handle:
if (dds_delete (pub->pubh) < 0) {
RCUTILS_LOG_ERROR_NAMED ("rmw_cyclonedds_cpp", "failed to destroy writer during error handling");
}
fail_writer:
dds_delete_qos (qos);
fail_qos:
dds_delete (topic);
fail_topic:
delete pub;
return nullptr;
}
extern "C" rmw_ret_t rmw_init_publisher_allocation (const rosidl_message_type_support_t * type_support, const rosidl_message_bounds_t * message_bounds , rmw_publisher_allocation_t * allocation)
{
static_cast<void>(type_support);
static_cast<void>(message_bounds);
static_cast<void>(allocation);
RMW_SET_ERROR_MSG ("rmw_init_publisher_allocation: unimplemented");
return RMW_RET_ERROR;
}
extern "C" rmw_ret_t rmw_fini_publisher_allocation (rmw_publisher_allocation_t *allocation)
{
static_cast<void>(allocation);
RMW_SET_ERROR_MSG ("rmw_fini_publisher_allocation: unimplemented");
return RMW_RET_ERROR;
}
extern "C" rmw_publisher_t *rmw_create_publisher (const rmw_node_t *node, const rosidl_message_type_support_t *type_supports, const char *topic_name, const rmw_qos_profile_t *qos_policies)
{
CddsPublisher *pub;
rmw_publisher_t *rmw_publisher;
if ((pub = create_cdds_publisher (node, type_supports, topic_name, qos_policies)) == nullptr) {
goto fail_common_init;
}
rmw_publisher = rmw_publisher_allocate ();
RET_ALLOC_X (rmw_publisher, goto fail_publisher);
rmw_publisher->implementation_identifier = eclipse_cyclonedds_identifier;
rmw_publisher->data = pub;
rmw_publisher->topic_name = reinterpret_cast<char *> (rmw_allocate (strlen (topic_name) + 1));
RET_ALLOC_X (rmw_publisher->topic_name, goto fail_topic_name);
memcpy (const_cast<char *> (rmw_publisher->topic_name), topic_name, strlen (topic_name) + 1);
return rmw_publisher;
fail_topic_name:
rmw_publisher_free (rmw_publisher);
fail_publisher:
if (dds_delete (pub->pubh) < 0) {
RCUTILS_LOG_ERROR_NAMED ("rmw_cyclonedds_cpp", "failed to delete writer during error handling");
}
delete pub;
fail_common_init:
return nullptr;
}
extern "C" rmw_ret_t rmw_get_gid_for_publisher (const rmw_publisher_t *publisher, rmw_gid_t *gid)
{
RET_WRONG_IMPLID (publisher);
RET_NULL (gid);
auto pub = static_cast<const CddsPublisher *> (publisher->data);
RET_NULL (pub);
gid->implementation_identifier = eclipse_cyclonedds_identifier;
memset (gid->data, 0, sizeof (gid->data));
assert (sizeof (pub->pubiid) <= sizeof (gid->data));
memcpy (gid->data, &pub->pubiid, sizeof (pub->pubiid));
return RMW_RET_OK;
}
extern "C" rmw_ret_t rmw_compare_gids_equal (const rmw_gid_t *gid1, const rmw_gid_t *gid2, bool *result)
{
RET_WRONG_IMPLID (gid1);
RET_WRONG_IMPLID (gid2);
RET_NULL (result);
/* alignment is potentially lost because of the translation to an array of bytes, so use
memcmp instead of a simple integer comparison */
*result = memcmp (gid1->data, gid2->data, sizeof (gid1->data)) == 0;
return RMW_RET_OK;
}
extern "C" rmw_ret_t rmw_publisher_count_matched_subscriptions (const rmw_publisher_t *publisher, size_t *subscription_count)
{
RET_WRONG_IMPLID (publisher);
auto pub = static_cast<CddsPublisher *> (publisher->data);
dds_publication_matched_status_t status;
if (dds_get_publication_matched_status (pub->pubh, &status) < 0) {
return RMW_RET_ERROR;
} else {
*subscription_count = status.current_count;
return RMW_RET_OK;
}
}
rmw_ret_t rmw_publisher_assert_liveliness (const rmw_publisher_t *publisher)
{
RET_WRONG_IMPLID (publisher);
return RMW_RET_OK;
}
rmw_ret_t rmw_publisher_get_actual_qos (const rmw_publisher_t *publisher, rmw_qos_profile_t *qos)
{
RET_NULL (qos);
RET_WRONG_IMPLID (publisher);
auto pub = static_cast<CddsPublisher *> (publisher->data);
if (get_readwrite_qos (pub->pubh, qos)) {
return RMW_RET_OK;
} else {
return RMW_RET_ERROR;
}
}
extern "C" rmw_ret_t rmw_destroy_publisher (rmw_node_t *node, rmw_publisher_t *publisher)
{
RET_WRONG_IMPLID (node);
RET_WRONG_IMPLID (publisher);
auto pub = static_cast<CddsPublisher *> (publisher->data);
if (pub != nullptr) {
if (dds_delete (pub->pubh) < 0) {
RMW_SET_ERROR_MSG ("failed to delete writer");
}
ddsi_sertopic_unref (pub->sertopic);
delete pub;
}
rmw_free (const_cast<char *> (publisher->topic_name));
publisher->topic_name = nullptr;
rmw_publisher_free (publisher);
return RMW_RET_OK;
}
/////////////////////////////////////////////////////////////////////////////////////////
/////////// ///////////
/////////// SUBSCRIPTIONS ///////////
/////////// ///////////
/////////////////////////////////////////////////////////////////////////////////////////
static CddsSubscription *create_cdds_subscription (const rmw_node_t *node, const rosidl_message_type_support_t *type_supports, const char *topic_name, const rmw_qos_profile_t *qos_policies, bool ignore_local_publications)
{
RET_WRONG_IMPLID_X (node, return nullptr);
RET_NULL_OR_EMPTYSTR_X (topic_name, return nullptr);
RET_NULL_X (qos_policies, return nullptr);
auto node_impl = static_cast<CddsNode *> (node->data);
RET_NULL_X (node_impl, return nullptr);
const rosidl_message_type_support_t *type_support = get_typesupport (type_supports);
RET_NULL_X (type_support, return nullptr);
CddsSubscription *sub = new CddsSubscription ();
dds_entity_t topic;
dds_qos_t *qos;
std::string fqtopic_name = make_fqtopic (ros_topic_prefix, topic_name, "", qos_policies);
auto sertopic = create_sertopic (fqtopic_name.c_str (), type_support->typesupport_identifier, create_message_type_support (type_support->data, type_support->typesupport_identifier), false);
if ((topic = dds_create_topic_arbitrary (gcdds.ppant, sertopic, nullptr, nullptr, nullptr)) < 0) {
RMW_SET_ERROR_MSG ("failed to create topic");
goto fail_topic;
}
if ((qos = create_readwrite_qos (qos_policies, ignore_local_publications)) == nullptr) {
goto fail_qos;
}
if ((sub->subh = dds_create_reader (node_impl->sub, topic, qos, nullptr)) < 0) {
RMW_SET_ERROR_MSG ("failed to create reader");
goto fail_reader;
}
if ((sub->rdcondh = dds_create_readcondition (sub->subh, DDS_ANY_STATE)) < 0) {
RMW_SET_ERROR_MSG ("failed to create readcondition");
goto fail_readcond;
}
/* FIXME: not guaranteed that "topic" will refer to "sertopic" because topic might have been
created earlier, but the two are equivalent, so this'll do */
sub->sertopic = sertopic;
dds_delete_qos (qos);
dds_delete (topic);
return sub;
fail_readcond:
if (dds_delete (sub->subh) < 0) {
RCUTILS_LOG_ERROR_NAMED ("rmw_cyclonedds_cpp", "failed to delete reader during error handling");
}
fail_reader:
dds_delete_qos (qos);
fail_qos:
dds_delete (topic);
fail_topic:
delete sub;
return nullptr;
}
extern "C" rmw_ret_t rmw_init_subscription_allocation (const rosidl_message_type_support_t *type_support, const rosidl_message_bounds_t *message_bounds, rmw_subscription_allocation_t *allocation)
{
static_cast<void>(type_support);
static_cast<void>(message_bounds);
static_cast<void>(allocation);
RMW_SET_ERROR_MSG ("rmw_init_subscription_allocation: unimplemented");
return RMW_RET_ERROR;
}
extern "C" rmw_ret_t rmw_fini_subscription_allocation (rmw_subscription_allocation_t *allocation)
{
static_cast<void>(allocation);
RMW_SET_ERROR_MSG ("rmw_fini_subscription_allocation: unimplemented");
return RMW_RET_ERROR;
}
extern "C" rmw_subscription_t *rmw_create_subscription (const rmw_node_t *node, const rosidl_message_type_support_t *type_supports, const char *topic_name, const rmw_qos_profile_t *qos_policies, bool ignore_local_publications)
{
CddsSubscription *sub;
rmw_subscription_t *rmw_subscription;
if ((sub = create_cdds_subscription (node, type_supports, topic_name, qos_policies, ignore_local_publications)) == nullptr) {
goto fail_common_init;
}
rmw_subscription = rmw_subscription_allocate ();
RET_ALLOC_X (rmw_subscription, goto fail_subscription);
rmw_subscription->implementation_identifier = eclipse_cyclonedds_identifier;
rmw_subscription->data = sub;
rmw_subscription->topic_name = reinterpret_cast<const char *> (rmw_allocate (strlen (topic_name) + 1));
RET_ALLOC_X (rmw_subscription->topic_name, goto fail_topic_name);
memcpy (const_cast<char *> (rmw_subscription->topic_name), topic_name, strlen (topic_name) + 1);
return rmw_subscription;
fail_topic_name:
rmw_subscription_free (rmw_subscription);
fail_subscription:
if (dds_delete (sub->rdcondh) < 0) {
RCUTILS_LOG_ERROR_NAMED ("rmw_cyclonedds_cpp", "failed to delete readcondition during error handling");
}
if (dds_delete (sub->subh) < 0) {
RCUTILS_LOG_ERROR_NAMED ("rmw_cyclonedds_cpp", "failed to delete reader during error handling");
}
delete sub;
fail_common_init:
return nullptr;
}
extern "C" rmw_ret_t rmw_subscription_count_matched_publishers (const rmw_subscription_t *subscription, size_t *publisher_count)
{
RET_WRONG_IMPLID (subscription);
auto sub = static_cast<CddsSubscription *> (subscription->data);
dds_subscription_matched_status_t status;
if (dds_get_subscription_matched_status (sub->subh, &status) < 0) {
return RMW_RET_ERROR;
} else {
*publisher_count = status.current_count;
return RMW_RET_OK;
}
}
extern "C" rmw_ret_t rmw_subscription_get_actual_qos(const rmw_subscription_t *subscription, rmw_qos_profile_t *qos)
{
RET_NULL (qos);
RET_WRONG_IMPLID (subscription);
auto sub = static_cast<CddsSubscription *> (subscription->data);
if (get_readwrite_qos (sub->subh, qos)) {
return RMW_RET_OK;
} else {
return RMW_RET_ERROR;
}
}
extern "C" rmw_ret_t rmw_destroy_subscription (rmw_node_t *node, rmw_subscription_t *subscription)
{
RET_WRONG_IMPLID (node);
RET_WRONG_IMPLID (subscription);
auto sub = static_cast<CddsSubscription *> (subscription->data);
if (sub != nullptr) {
clean_waitset_caches ();
if (dds_delete (sub->rdcondh) < 0) {
RMW_SET_ERROR_MSG ("failed to delete readcondition");
}
if (dds_delete (sub->subh) < 0) {
RMW_SET_ERROR_MSG ("failed to delete reader");
}
ddsi_sertopic_unref (sub->sertopic);
delete sub;
}
rmw_free (const_cast<char *> (subscription->topic_name));
subscription->topic_name = nullptr;
rmw_subscription_free (subscription);
return RMW_RET_OK;
}
static rmw_ret_t rmw_take_int (const rmw_subscription_t *subscription, void *ros_message, bool *taken, rmw_message_info_t *message_info)
{
RET_NULL (taken);
RET_NULL (ros_message);
RET_WRONG_IMPLID (subscription);
CddsSubscription *sub = static_cast<CddsSubscription *> (subscription->data);
RET_NULL (sub);
dds_sample_info_t info;
while (dds_take (sub->subh, &ros_message, &info, 1, 1) == 1) {
if (info.valid_data) {
if (message_info) {
message_info->publisher_gid.implementation_identifier = eclipse_cyclonedds_identifier;
memset (message_info->publisher_gid.data, 0, sizeof (message_info->publisher_gid.data));
assert (sizeof (info.publication_handle) <= sizeof (message_info->publisher_gid.data));
memcpy (message_info->publisher_gid.data, &info.publication_handle, sizeof (info.publication_handle));
}
*taken = true;
return RMW_RET_OK;
}
}
*taken = false;
return RMW_RET_OK;
}
static rmw_ret_t rmw_take_ser_int (const rmw_subscription_t *subscription, rmw_serialized_message_t *serialized_message, bool *taken, rmw_message_info_t *message_info)
{
RET_NULL (taken);
RET_NULL (serialized_message);
RET_WRONG_IMPLID (subscription);
CddsSubscription *sub = static_cast<CddsSubscription *> (subscription->data);
RET_NULL (sub);
dds_sample_info_t info;
struct ddsi_serdata *dcmn;
while (dds_takecdr (sub->subh, &dcmn, 1, &info, DDS_ANY_STATE) == 1) {
if (info.valid_data) {
if (message_info) {
message_info->publisher_gid.implementation_identifier = eclipse_cyclonedds_identifier;
memset (message_info->publisher_gid.data, 0, sizeof (message_info->publisher_gid.data));
assert (sizeof (info.publication_handle) <= sizeof (message_info->publisher_gid.data));
memcpy (message_info->publisher_gid.data, &info.publication_handle, sizeof (info.publication_handle));
}
auto d = static_cast<struct serdata_rmw *> (dcmn);
/* FIXME: what about the header - should be included or not? */
if (rmw_serialized_message_resize (serialized_message, d->data.size ()) != RMW_RET_OK) {
ddsi_serdata_unref (dcmn);
*taken = false;
return RMW_RET_ERROR;
}
memcpy (serialized_message->buffer, d->data.data (), d->data.size ());
serialized_message->buffer_length = d->data.size ();
ddsi_serdata_unref (dcmn);
*taken = true;
return RMW_RET_OK;
}
ddsi_serdata_unref (dcmn);
}
*taken = false;
return RMW_RET_OK;
}
extern "C" rmw_ret_t rmw_take (const rmw_subscription_t *subscription, void *ros_message, bool *taken, rmw_subscription_allocation_t *allocation)
{
static_cast<void>(allocation);
return rmw_take_int (subscription, ros_message, taken, nullptr);
}
extern "C" rmw_ret_t rmw_take_with_info (const rmw_subscription_t *subscription, void *ros_message, bool *taken, rmw_message_info_t *message_info, rmw_subscription_allocation_t *allocation)
{
static_cast<void>(allocation);
return rmw_take_int (subscription, ros_message, taken, message_info);
}
extern "C" rmw_ret_t rmw_take_serialized_message (const rmw_subscription_t *subscription, rmw_serialized_message_t *serialized_message, bool *taken, rmw_subscription_allocation_t *allocation)
{
static_cast<void>(allocation);
return rmw_take_ser_int (subscription, serialized_message, taken, nullptr);
}
extern "C" rmw_ret_t rmw_take_serialized_message_with_info (const rmw_subscription_t *subscription, rmw_serialized_message_t *serialized_message, bool *taken, rmw_message_info_t *message_info, rmw_subscription_allocation_t *allocation)
{
static_cast<void>(allocation);
return rmw_take_ser_int (subscription, serialized_message, taken, message_info);
}
extern "C" rmw_ret_t rmw_take_event (const rmw_events_t *event_handle, void *event_info, bool *taken)
{
static_cast<void>(event_info);
static_cast<void>(event_handle);
RET_NULL (taken);
*taken = false;
return RMW_RET_OK;
}
/////////////////////////////////////////////////////////////////////////////////////////
/////////// ///////////
/////////// GUARDS AND WAITSETS ///////////
/////////// ///////////
/////////////////////////////////////////////////////////////////////////////////////////
extern "C" rmw_guard_condition_t *rmw_create_guard_condition (rmw_context_t *context)
{
static_cast<void>(context);
rmw_guard_condition_t *guard_condition_handle;
auto *gcond_impl = new CddsGuardCondition ();
if (ref_ppant () < 0) {
goto fail_ppant;
}
if ((gcond_impl->gcondh = dds_create_guardcondition (gcdds.ppant)) < 0) {
RMW_SET_ERROR_MSG ("failed to create guardcondition");
goto fail_guardcond;
}
guard_condition_handle = new rmw_guard_condition_t;
guard_condition_handle->implementation_identifier = eclipse_cyclonedds_identifier;
guard_condition_handle->data = gcond_impl;
return guard_condition_handle;
fail_guardcond:
unref_ppant ();
fail_ppant:
delete (gcond_impl);
return nullptr;
}
extern "C" rmw_ret_t rmw_destroy_guard_condition (rmw_guard_condition_t *guard_condition_handle)
{
RET_NULL (guard_condition_handle);
auto *gcond_impl = static_cast<CddsGuardCondition *> (guard_condition_handle->data);
clean_waitset_caches ();
dds_delete (gcond_impl->gcondh);
unref_ppant ();
delete gcond_impl;
delete guard_condition_handle;
return RMW_RET_OK;
}
extern "C" rmw_ret_t rmw_trigger_guard_condition (const rmw_guard_condition_t *guard_condition_handle)
{
RET_WRONG_IMPLID (guard_condition_handle);
auto *gcond_impl = static_cast<CddsGuardCondition *> (guard_condition_handle->data);
dds_set_guardcondition (gcond_impl->gcondh, true);
return RMW_RET_OK;
}
extern "C" rmw_wait_set_t *rmw_create_wait_set (rmw_context_t *context, size_t max_conditions)
{
static_cast<void>(context);
(void) max_conditions;
rmw_wait_set_t *wait_set = rmw_wait_set_allocate ();
CddsWaitset *ws = nullptr;
RET_ALLOC_X (wait_set, goto fail_alloc_wait_set);
wait_set->implementation_identifier = eclipse_cyclonedds_identifier;
wait_set->data = rmw_allocate (sizeof (CddsWaitset));
RET_ALLOC_X (wait_set->data, goto fail_alloc_wait_set_data);
// This should default-construct the fields of CddsWaitset
ws = static_cast<CddsWaitset *> (wait_set->data);
RMW_TRY_PLACEMENT_NEW (ws, ws, goto fail_placement_new, CddsWaitset, );
if (!ws) {
RMW_SET_ERROR_MSG ("failed to construct wait set info struct");
goto fail_ws;
}
ws->inuse = false;
if ((ws->waitseth = dds_create_waitset (gcdds.ppant)) < 0) {
RMW_SET_ERROR_MSG ("failed to create waitset");
goto fail_waitset;
}
{
std::lock_guard<std::mutex> lock (gcdds.lock);
gcdds.waitsets.insert (ws);
}
return wait_set;
fail_waitset:
fail_ws:
RMW_TRY_DESTRUCTOR_FROM_WITHIN_FAILURE (ws->~CddsWaitset (), ws);
fail_placement_new:
rmw_free (wait_set->data);
fail_alloc_wait_set_data:
rmw_wait_set_free (wait_set);
fail_alloc_wait_set:
return nullptr;
}
extern "C" rmw_ret_t rmw_destroy_wait_set (rmw_wait_set_t *wait_set)
{
RET_WRONG_IMPLID (wait_set);
auto result = RMW_RET_OK;
auto ws = static_cast<CddsWaitset *> (wait_set->data);
RET_NULL (ws);
dds_delete (ws->waitseth);
{
std::lock_guard<std::mutex> lock (gcdds.lock);
gcdds.waitsets.erase (ws);
}
RMW_TRY_DESTRUCTOR (ws->~CddsWaitset (), ws, result = RMW_RET_ERROR);
rmw_free (wait_set->data);
rmw_wait_set_free (wait_set);
return result;
}
template<typename T>
static bool require_reattach (const std::vector<T *>& cached, size_t count, void **ary)
{
if (ary == nullptr || count == 0) {
return (cached.size () != 0);
} else if (count != cached.size ()) {
return true;
} else {
return (memcmp (static_cast<const void *> (cached.data ()), static_cast<void *> (ary), count * sizeof (void *)) != 0);
}
}
static void waitset_detach (CddsWaitset *ws)
{
for (auto&& x : ws->subs) dds_waitset_detach (ws->waitseth, x->rdcondh);
for (auto&& x : ws->gcs) dds_waitset_detach (ws->waitseth, x->gcondh);
for (auto&& x : ws->srvs) dds_waitset_detach (ws->waitseth, x->service.sub->rdcondh);
for (auto&& x : ws->cls) dds_waitset_detach (ws->waitseth, x->client.sub->rdcondh);
ws->subs.resize (0);
ws->gcs.resize (0);
ws->srvs.resize (0);
ws->cls.resize (0);
}
static void clean_waitset_caches ()
{
/* Called whenever a subscriber, guard condition, service or client is deleted (as these may
have been cached in a waitset), and drops all cached entities from all waitsets (just to keep
life simple). I'm assuming one is not allowed to delete an entity while it is still being
used ... */
std::lock_guard<std::mutex> lock (gcdds.lock);
for (auto&& ws : gcdds.waitsets) {
std::lock_guard<std::mutex> lock (ws->lock);
if (!ws->inuse) {
waitset_detach (ws);
}
}
}
extern "C" rmw_ret_t rmw_wait (rmw_subscriptions_t *subs, rmw_guard_conditions_t *gcs, rmw_services_t *srvs, rmw_clients_t *cls, rmw_events_t *evs, rmw_wait_set_t *wait_set, const rmw_time_t *wait_timeout)
{
static_cast<void>(evs);
RET_NULL (wait_set);
CddsWaitset *ws = static_cast<CddsWaitset *> (wait_set->data);
RET_NULL (ws);
{
std::lock_guard<std::mutex> lock (ws->lock);
if (ws->inuse) {
RMW_SET_ERROR_MSG ("concurrent calls to rmw_wait on a single waitset is not supported");
return RMW_RET_ERROR;
}
ws->inuse = true;
}
if (require_reattach (ws->subs, subs ? subs->subscriber_count : 0, subs ? subs->subscribers : nullptr) ||
require_reattach (ws->gcs, gcs ? gcs->guard_condition_count : 0, gcs ? gcs->guard_conditions : nullptr) ||
require_reattach (ws->srvs, srvs ? srvs->service_count : 0, srvs ? srvs->services : nullptr) ||
require_reattach (ws->cls, cls ? cls->client_count : 0, cls ? cls->clients : nullptr)) {
size_t nelems = 0;
waitset_detach (ws);
#define ATTACH(type, var, name, cond) do { \
ws->var.resize (0); \
if (var) { \
ws->var.reserve (var->name##_count); \
for (size_t i = 0; i < var->name##_count; i++) { \
auto x = static_cast<type *> (var->name##s[i]); \
ws->var.push_back (x); \
dds_waitset_attach (ws->waitseth, x->cond, nelems); \
nelems++; \
} \
} \
} while (0)
ATTACH (CddsSubscription, subs, subscriber, rdcondh);
ATTACH (CddsGuardCondition, gcs, guard_condition, gcondh);
ATTACH (CddsService, srvs, service, service.sub->rdcondh);
ATTACH (CddsClient, cls, client, client.sub->rdcondh);
#undef ATTACH
ws->trigs.resize (nelems + 1);
}
const dds_duration_t timeout =
(wait_timeout == NULL) ? DDS_NEVER : (dds_duration_t) wait_timeout->sec * 1000000000 + wait_timeout->nsec;
const dds_return_t ntrig = dds_waitset_wait (ws->waitseth, ws->trigs.data (), ws->trigs.capacity (), timeout);
ws->trigs.resize (ntrig);
std::sort (ws->trigs.begin (), ws->trigs.end ());
ws->trigs.push_back ((dds_attach_t) -1);
{
long trig_idx = 0;
bool dummy;
size_t nelems = 0;
#define DETACH(type, var, name, cond, on_triggered) do { \
if (var) { \
for (size_t i = 0; i < var->name##_count; i++) { \
auto x = static_cast<type *> (var->name##s[i]); \
/*dds_waitset_detach (ws->waitseth, x->cond);*/ \
if (ws->trigs[trig_idx] == (long) nelems) { \
on_triggered; \
trig_idx++; \
} else { \
var->name##s[i] = nullptr; \
} \
nelems++; \
} \
} \
} while (0)
DETACH (CddsSubscription, subs, subscriber, rdcondh, (void) x);
DETACH (CddsGuardCondition, gcs, guard_condition, gcondh, dds_take_guardcondition (x->gcondh, &dummy));
DETACH (CddsService, srvs, service, service.sub->rdcondh, (void) x);
DETACH (CddsClient, cls, client, client.sub->rdcondh, (void) x);
#undef DETACH
}
{
std::lock_guard<std::mutex> lock (ws->lock);
ws->inuse = false;
}
return (ws->trigs.size () == 1) ? RMW_RET_TIMEOUT : RMW_RET_OK;
}
/////////////////////////////////////////////////////////////////////////////////////////
/////////// ///////////
/////////// CLIENTS AND SERVERS ///////////
/////////// ///////////
/////////////////////////////////////////////////////////////////////////////////////////
static rmw_ret_t rmw_take_response_request (CddsCS *cs, rmw_request_id_t *request_header, void *ros_data, bool *taken, dds_instance_handle_t srcfilter)
{
RET_NULL (taken);
RET_NULL (ros_data);
RET_NULL (request_header);
cdds_request_wrapper_t wrap;
dds_sample_info_t info;
wrap.data = ros_data;
void *wrap_ptr = static_cast<void *> (&wrap);
while (dds_take (cs->sub->subh, &wrap_ptr, &info, 1, 1) == 1) {
if (info.valid_data) {
memset (request_header, 0, sizeof (wrap.header));
assert (sizeof (wrap.header.guid) <= sizeof (request_header->writer_guid));
memcpy (request_header->writer_guid, &wrap.header.guid, sizeof (wrap.header.guid));
request_header->sequence_number = wrap.header.seq;
if (srcfilter == 0 || srcfilter == wrap.header.guid) {
*taken = true;
return RMW_RET_OK;
}
}
}
*taken = false;
return RMW_RET_OK;
}
extern "C" rmw_ret_t rmw_take_response (const rmw_client_t *client, rmw_request_id_t *request_header, void *ros_response, bool *taken)
{
RET_WRONG_IMPLID (client);
auto info = static_cast<CddsClient *> (client->data);
return rmw_take_response_request (&info->client, request_header, ros_response, taken, info->client.pub->pubiid);
}
extern "C" rmw_ret_t rmw_take_request (const rmw_service_t *service, rmw_request_id_t *request_header, void *ros_request, bool *taken)
{
RET_WRONG_IMPLID (service);
auto info = static_cast<CddsService *> (service->data);
return rmw_take_response_request (&info->service, request_header, ros_request, taken, 0);
}
static rmw_ret_t rmw_send_response_request (CddsCS *cs, const cdds_request_header_t& header, const void *ros_data)
{
const cdds_request_wrapper_t wrap = { header, const_cast<void *> (ros_data) };
if (dds_write (cs->pub->pubh, static_cast<const void *> (&wrap)) >= 0) {
return RMW_RET_OK;
} else {
RMW_SET_ERROR_MSG ("cannot publish data");
return RMW_RET_ERROR;
}
}
extern "C" rmw_ret_t rmw_send_response (const rmw_service_t *service, rmw_request_id_t *request_header, void *ros_response)
{
RET_WRONG_IMPLID (service);
RET_NULL (request_header);
RET_NULL (ros_response);
CddsService *info = static_cast<CddsService *> (service->data);
cdds_request_header_t header;
memcpy (&header.guid, request_header->writer_guid, sizeof (header.guid));
header.seq = request_header->sequence_number;
return rmw_send_response_request (&info->service, header, ros_response);
}
extern "C" rmw_ret_t rmw_send_request (const rmw_client_t *client, const void *ros_request, int64_t *sequence_id)
{
static std::atomic_uint next_request_id;
RET_WRONG_IMPLID (client);
RET_NULL (ros_request);
RET_NULL (sequence_id);
auto info = static_cast<CddsClient *> (client->data);
cdds_request_header_t header;
header.guid = info->client.pub->pubiid;
header.seq = *sequence_id = next_request_id++;
return rmw_send_response_request (&info->client, header, ros_request);
}
static const rosidl_service_type_support_t *get_service_typesupport (const rosidl_service_type_support_t *type_supports)
{
const rosidl_service_type_support_t *ts;
if ((ts = get_service_typesupport_handle (type_supports, rosidl_typesupport_introspection_c__identifier)) != nullptr) {
return ts;
} else if ((ts = get_service_typesupport_handle (type_supports, rosidl_typesupport_introspection_cpp::typesupport_identifier)) != nullptr) {
return ts;
} else {
RMW_SET_ERROR_MSG ("service type support not from this implementation");
return nullptr;
}
}
static rmw_ret_t rmw_init_cs (CddsCS *cs, const rmw_node_t *node, const rosidl_service_type_support_t *type_supports, const char *service_name, const rmw_qos_profile_t *qos_policies, bool is_service)
{
RET_WRONG_IMPLID (node);
RET_NULL_OR_EMPTYSTR (service_name);
RET_NULL (qos_policies);
auto node_impl = static_cast<CddsNode *> (node->data);
RET_NULL (node_impl);
const rosidl_service_type_support_t *type_support = get_service_typesupport (type_supports);
RET_NULL (type_support);
auto pub = new CddsPublisher ();
auto sub = new CddsSubscription ();
std::string subtopic_name, pubtopic_name;
void *pub_type_support, *sub_type_support;
if (is_service) {
sub_type_support = create_request_type_support (type_support->data, type_support->typesupport_identifier);
pub_type_support = create_response_type_support (type_support->data, type_support->typesupport_identifier);
subtopic_name = make_fqtopic (ros_service_requester_prefix, service_name, "Request", qos_policies);
pubtopic_name = make_fqtopic (ros_service_response_prefix, service_name, "Reply", qos_policies);
} else {
pub_type_support = create_request_type_support (type_support->data, type_support->typesupport_identifier);
sub_type_support = create_response_type_support (type_support->data, type_support->typesupport_identifier);
pubtopic_name = make_fqtopic (ros_service_requester_prefix, service_name, "Request", qos_policies);
subtopic_name = make_fqtopic (ros_service_response_prefix, service_name, "Reply", qos_policies);
}
RCUTILS_LOG_DEBUG_NAMED ("rmw_cyclonedds_cpp", "************ %s Details *********", is_service ? "Service" : "Client");
RCUTILS_LOG_DEBUG_NAMED ("rmw_cyclonedds_cpp", "Sub Topic %s", subtopic_name.c_str ());
RCUTILS_LOG_DEBUG_NAMED ("rmw_cyclonedds_cpp", "Pub Topic %s", pubtopic_name.c_str ());
RCUTILS_LOG_DEBUG_NAMED ("rmw_cyclonedds_cpp", "***********");
dds_entity_t pubtopic, subtopic;
auto pub_st = create_sertopic (pubtopic_name.c_str (), type_support->typesupport_identifier, pub_type_support, true);
auto sub_st = create_sertopic (subtopic_name.c_str (), type_support->typesupport_identifier, sub_type_support, true);
dds_qos_t *qos;
if ((pubtopic = dds_create_topic_arbitrary (gcdds.ppant, pub_st, nullptr, nullptr, nullptr)) < 0) {
RMW_SET_ERROR_MSG ("failed to create topic");
goto fail_pubtopic;
}
if ((subtopic = dds_create_topic_arbitrary (gcdds.ppant, sub_st, nullptr, nullptr, nullptr)) < 0) {
RMW_SET_ERROR_MSG ("failed to create topic");
goto fail_subtopic;
}
if ((qos = dds_create_qos ()) == nullptr) {
goto fail_qos;
}
dds_qset_reliability (qos, DDS_RELIABILITY_RELIABLE, DDS_SECS (1));
dds_qset_history (qos, DDS_HISTORY_KEEP_ALL, DDS_LENGTH_UNLIMITED);
if ((pub->pubh = dds_create_writer (node_impl->pub, pubtopic, qos, nullptr)) < 0) {
RMW_SET_ERROR_MSG ("failed to create writer");
goto fail_writer;
}
/* FIXME: not guaranteed that "topic" will refer to "sertopic" because topic might have been
created earlier, but the two are equivalent, so this'll do */
pub->sertopic = pub_st;
if ((sub->subh = dds_create_reader (node_impl->sub, subtopic, qos, nullptr)) < 0) {
RMW_SET_ERROR_MSG ("failed to create reader");
goto fail_reader;
}
/* FIXME: not guaranteed that "topic" will refer to "sertopic" because topic might have been
created earlier, but the two are equivalent, so this'll do */
sub->sertopic = sub_st;
if ((sub->rdcondh = dds_create_readcondition (sub->subh, DDS_ANY_STATE)) < 0) {
RMW_SET_ERROR_MSG ("failed to create readcondition");
goto fail_readcond;
}
if (dds_get_instance_handle (pub->pubh, &pub->pubiid) < 0) {
RMW_SET_ERROR_MSG ("failed to get instance handle for writer");
goto fail_instance_handle;
}
dds_delete_qos (qos);
dds_delete (subtopic);
dds_delete (pubtopic);
cs->pub = pub;
cs->sub = sub;
return RMW_RET_OK;
fail_instance_handle:
dds_delete (sub->rdcondh);
fail_readcond:
dds_delete (sub->subh);
fail_reader:
dds_delete (pub->pubh);
fail_writer:
dds_delete_qos (qos);
fail_qos:
dds_delete (subtopic);
fail_subtopic:
dds_delete (pubtopic);
fail_pubtopic:
return RMW_RET_ERROR;
}
static void rmw_fini_cs (CddsCS *cs)
{
ddsi_sertopic_unref (cs->sub->sertopic);
ddsi_sertopic_unref (cs->pub->sertopic);
dds_delete (cs->sub->rdcondh);
dds_delete (cs->sub->subh);
dds_delete (cs->pub->pubh);
}
extern "C" rmw_client_t *rmw_create_client (const rmw_node_t *node, const rosidl_service_type_support_t *type_supports, const char *service_name, const rmw_qos_profile_t *qos_policies)
{
CddsClient *info = new CddsClient ();
if (rmw_init_cs (&info->client, node, type_supports, service_name, qos_policies, false) != RMW_RET_OK) {
delete (info);
return nullptr;
}
rmw_client_t *rmw_client = rmw_client_allocate ();
RET_NULL_X (rmw_client, goto fail_client);
rmw_client->implementation_identifier = eclipse_cyclonedds_identifier;
rmw_client->data = info;
rmw_client->service_name = reinterpret_cast<const char *> (rmw_allocate (strlen (service_name) + 1));
RET_NULL_X (rmw_client->service_name, goto fail_service_name);
memcpy (const_cast<char *> (rmw_client->service_name), service_name, strlen (service_name) + 1);
return rmw_client;
fail_service_name:
rmw_client_free (rmw_client);
fail_client:
rmw_fini_cs (&info->client);
return nullptr;
}
extern "C" rmw_ret_t rmw_destroy_client (rmw_node_t *node, rmw_client_t *client)
{
RET_WRONG_IMPLID (node);
RET_WRONG_IMPLID (client);
auto info = static_cast<CddsClient *> (client->data);
clean_waitset_caches ();
rmw_fini_cs (&info->client);
rmw_free (const_cast<char *> (client->service_name));
rmw_client_free (client);
return RMW_RET_OK;
}
extern "C" rmw_service_t *rmw_create_service (const rmw_node_t *node, const rosidl_service_type_support_t *type_supports, const char *service_name, const rmw_qos_profile_t *qos_policies)
{
CddsService *info = new CddsService ();
if (rmw_init_cs (&info->service, node, type_supports, service_name, qos_policies, true) != RMW_RET_OK) {
delete (info);
return nullptr;
}
rmw_service_t *rmw_service = rmw_service_allocate ();
RET_NULL_X (rmw_service, goto fail_service);
rmw_service->implementation_identifier = eclipse_cyclonedds_identifier;
rmw_service->data = info;
rmw_service->service_name = reinterpret_cast<const char *> (rmw_allocate (strlen (service_name) + 1));
RET_NULL_X (rmw_service->service_name, goto fail_service_name);
memcpy (const_cast<char *> (rmw_service->service_name), service_name, strlen (service_name) + 1);
return rmw_service;
fail_service_name:
rmw_service_free (rmw_service);
fail_service:
rmw_fini_cs (&info->service);
return nullptr;
}
extern "C" rmw_ret_t rmw_destroy_service (rmw_node_t *node, rmw_service_t *service)
{
RET_WRONG_IMPLID (node);
RET_WRONG_IMPLID (service);
auto info = static_cast<CddsService *> (service->data);
clean_waitset_caches ();
rmw_fini_cs (&info->service);
rmw_free (const_cast<char *> (service->service_name));
rmw_service_free (service);
return RMW_RET_OK;
}
/////////////////////////////////////////////////////////////////////////////////////////
/////////// ///////////
/////////// INTROSPECTION ///////////
/////////// ///////////
/////////////////////////////////////////////////////////////////////////////////////////
static rmw_ret_t do_for_node (std::function<bool (const dds_builtintopic_participant_t& sample)> oper)
{
dds_entity_t rd;
if ((rd = dds_create_reader (ref_ppant (), DDS_BUILTIN_TOPIC_DCPSPARTICIPANT, NULL, NULL)) < 0) {
unref_ppant ();
RMW_SET_ERROR_MSG ("rmw_get_node_names: failed to create reader");
return RMW_RET_ERROR;
}
dds_sample_info_t info;
void *msg = NULL;
int32_t n;
bool cont = true;
while (cont && (n = dds_take (rd, &msg, &info, 1, 1)) == 1) {
if (info.valid_data && info.instance_state == DDS_IST_ALIVE) {
auto sample = static_cast<const dds_builtintopic_participant_t *> (msg);
cont = oper (*sample);
}
dds_return_loan (rd, &msg, n);
}
dds_delete (rd);
unref_ppant ();
if (n < 0) {
RMW_SET_ERROR_MSG ("rmw_get_node_names: error reading participants");
return RMW_RET_ERROR;
}
return RMW_RET_OK;
}
static rmw_ret_t do_for_node_user_data (std::function<bool (const dds_builtintopic_participant_t& sample, const char *user_data)> oper)
{
auto f = [oper](const dds_builtintopic_participant_t& sample) -> bool {
void *ud;
size_t udsz;
if (dds_qget_userdata (sample.qos, &ud, &udsz) && ud != nullptr) {
/* CycloneDDS guarantees a null-terminated user data so we pretend it's a
string */
bool ret = oper (sample, static_cast<char *> (ud));
dds_free (ud);
return ret;
} else {
/* If no user data present treat it as an empty string */
return oper (sample, "");
}
};
return do_for_node (f);
}
extern "C" rmw_ret_t rmw_get_node_names (const rmw_node_t *node, rcutils_string_array_t *node_names, rcutils_string_array_t *node_namespaces)
{
RET_WRONG_IMPLID (node);
if (rmw_check_zero_rmw_string_array(node_names) != RMW_RET_OK ||
rmw_check_zero_rmw_string_array(node_namespaces) != RMW_RET_OK) {
return RMW_RET_ERROR;
}
std::set< std::pair<std::string, std::string> > ns;
const auto re = std::regex ("^name=(.*);namespace=(.*);$", std::regex::extended);
auto oper =
[&ns, re](const dds_builtintopic_participant_t& sample, const char *ud) -> bool {
std::cmatch cm;
static_cast<void>(sample);
if (std::regex_search (ud, cm, re)) {
ns.insert (std::make_pair (std::string (cm[1]), std::string (cm[2])));
}
return true;
};
rmw_ret_t ret;
if ((ret = do_for_node_user_data (oper)) != RMW_RET_OK) {
return ret;
}
rcutils_allocator_t allocator = rcutils_get_default_allocator ();
if (rcutils_string_array_init (node_names, ns.size (), &allocator) != RCUTILS_RET_OK ||
rcutils_string_array_init (node_namespaces, ns.size(), &allocator) != RCUTILS_RET_OK) {
RMW_SET_ERROR_MSG (rcutils_get_error_string ().str);
goto fail_alloc;
}
size_t i;
i = 0;
for (auto&& n : ns) {
node_names->data[i] = rcutils_strdup (n.first.c_str (), allocator);
node_namespaces->data[i] = rcutils_strdup (n.second.c_str (), allocator);
if (!node_names->data[i] || !node_namespaces->data[i]) {
RMW_SET_ERROR_MSG ("rmw_get_node_names for name/namespace");
goto fail_alloc;
}
i++;
}
return RMW_RET_OK;
fail_alloc:
if (node_names) {
if (rcutils_string_array_fini (node_names) != RCUTILS_RET_OK) {
RCUTILS_LOG_ERROR_NAMED (
"rmw_cyclonedds_cpp",
"failed to cleanup during error handling: %s", rcutils_get_error_string ().str);
rcutils_reset_error();
}
}
if (node_namespaces) {
if (rcutils_string_array_fini(node_namespaces) != RCUTILS_RET_OK) {
RCUTILS_LOG_ERROR_NAMED(
"rmw_cyclonedds_cpp",
"failed to cleanup during error handling: %s", rcutils_get_error_string ().str);
rcutils_reset_error();
}
}
return RMW_RET_BAD_ALLOC;
}
static rmw_ret_t rmw_collect_tptyp_for_kind (std::map<std::string, std::set<std::string>>& tt, dds_entity_t builtin_topic, std::function<bool (const dds_builtintopic_endpoint_t& sample, std::string& topic_name, std::string& type_name)> filter_and_map)
{
assert (builtin_topic == DDS_BUILTIN_TOPIC_DCPSSUBSCRIPTION || builtin_topic == DDS_BUILTIN_TOPIC_DCPSPUBLICATION);
dds_entity_t rd;
if ((rd = dds_create_reader (ref_ppant (), builtin_topic, NULL, NULL)) < 0) {
unref_ppant ();
RMW_SET_ERROR_MSG ("rmw_collect_tptyp_for_kind failed to create reader");
return RMW_RET_ERROR;
}
dds_sample_info_t info;
void *msg = NULL;
int32_t n;
while ((n = dds_take (rd, &msg, &info, 1, 1)) == 1) {
if (info.valid_data && info.instance_state == DDS_IST_ALIVE) {
auto sample = static_cast<const dds_builtintopic_endpoint_t *> (msg);
std::string topic_name, type_name;
if (filter_and_map (*sample, topic_name, type_name)) {
tt[topic_name].insert (type_name);
}
}
dds_return_loan (rd, &msg, n);
}
dds_delete (rd);
unref_ppant ();
if (n == 0) {
return RMW_RET_OK;
} else {
RMW_SET_ERROR_MSG ("rmw_collect_tptyp_for_kind dds_take failed");
return RMW_RET_ERROR;
}
}
static rmw_ret_t make_names_and_types (rmw_names_and_types_t *tptyp, const std::map<std::string, std::set<std::string>>& source, rcutils_allocator_t *allocator)
{
if (source.size () == 0) {
return RMW_RET_OK;
}
rmw_ret_t ret;
if ((ret = rmw_names_and_types_init (tptyp, source.size (), allocator)) != RMW_RET_OK) {
return ret;
}
size_t index = 0;
for (const auto& tp : source) {
if ((tptyp->names.data[index] = rcutils_strdup (tp.first.c_str (), *allocator)) == NULL) {
goto fail_mem;
}
if (rcutils_string_array_init (&tptyp->types[index], tp.second.size (), allocator) != RCUTILS_RET_OK) {
goto fail_mem;
}
size_t type_index = 0;
for (const auto& type : tp.second) {
if ((tptyp->types[index].data[type_index] = rcutils_strdup (type.c_str (), *allocator)) == NULL) {
goto fail_mem;
}
type_index++;
}
index++;
}
return RMW_RET_OK;
fail_mem:
if (rmw_names_and_types_fini (tptyp) != RMW_RET_OK) {
RMW_SET_ERROR_MSG ("rmw_collect_tptyp_for_kind: rmw_names_and_types_fini failed");
}
return RMW_RET_BAD_ALLOC;
}
static rmw_ret_t get_node_guids (const char *node_name, const char *node_namespace, std::set<dds_builtintopic_guid_t>& guids)
{
std::string needle = get_node_user_data (node_name, node_namespace);
auto oper = [&guids, needle](const dds_builtintopic_participant_t& sample, const char *ud) -> bool {
if (std::string (ud) == needle) {
guids.insert (sample.key);
}
return true; /* do keep looking - what if there are many? */
};
return do_for_node_user_data (oper);
}
static rmw_ret_t get_endpoint_names_and_types_by_node (const rmw_node_t *node, rcutils_allocator_t *allocator, const char *node_name, const char *node_namespace, bool no_demangle, rmw_names_and_types_t *tptyp, bool subs, bool pubs)
{
RET_WRONG_IMPLID (node);
RET_NULL (allocator);
rmw_ret_t ret = rmw_names_and_types_check_zero (tptyp);
if (ret != RMW_RET_OK) {
return ret;
}
std::set<dds_builtintopic_guid_t> guids;
if (node_name != nullptr && (ret = get_node_guids (node_name, node_namespace, guids)) != RMW_RET_OK) {
return ret;
}
const auto re_tp = std::regex ("^" + std::string (ros_topic_prefix) + "(/.*)", std::regex::extended);
const auto re_typ = std::regex ("^(.*::)dds_::(.*)_$", std::regex::extended);
const auto filter_and_map =
[re_tp, re_typ, guids, node_name](const dds_builtintopic_endpoint_t& sample, std::string& topic_name, std::string& type_name) -> bool {
std::cmatch cm_tp, cm_typ;
if (node_name != nullptr && guids.count (sample.participant_key) == 0) {
return false;
} else if (! std::regex_search (sample.topic_name, cm_tp, re_tp) || ! std::regex_search (sample.type_name, cm_typ, re_typ)) {
return false;
} else {
std::string demangled_type = std::regex_replace (std::string (cm_typ[1]), std::regex ("::"), "/");
topic_name = std::string (cm_tp[1]);
type_name = std::string (demangled_type) + std::string (cm_typ[2]);
return true;
}
};
std::map<std::string, std::set<std::string>> tt;
if (subs && (ret = rmw_collect_tptyp_for_kind (tt, DDS_BUILTIN_TOPIC_DCPSSUBSCRIPTION, filter_and_map)) != RMW_RET_OK) {
return ret;
}
if (pubs && (ret = rmw_collect_tptyp_for_kind (tt, DDS_BUILTIN_TOPIC_DCPSPUBLICATION, filter_and_map)) != RMW_RET_OK) {
return ret;
}
return make_names_and_types (tptyp, tt, allocator);
}
static rmw_ret_t get_service_names_and_types_by_node (const rmw_node_t *node, rcutils_allocator_t *allocator, const char *node_name, const char *node_namespace, rmw_names_and_types_t *sntyp)
{
RET_WRONG_IMPLID (node);
RET_NULL (allocator);
rmw_ret_t ret = rmw_names_and_types_check_zero (sntyp);
if (ret != RMW_RET_OK) {
return ret;
}
std::set<dds_builtintopic_guid_t> guids;
if (node_name != nullptr && (ret = get_node_guids (node_name, node_namespace, guids)) != RMW_RET_OK) {
return ret;
}
const auto re_tp = std::regex ("^(" + std::string (ros_service_requester_prefix) + "|" +
std::string (ros_service_response_prefix) + ")(/.*)(Request|Reply)$",
std::regex::extended);
const auto re_typ = std::regex ("^(.*::)dds_::(.*)_(Reponse|Request)_$", std::regex::extended);
const auto filter_and_map =
[re_tp, re_typ, guids, node_name](const dds_builtintopic_endpoint_t& sample, std::string& topic_name, std::string& type_name) -> bool {
std::cmatch cm_tp, cm_typ;
if (node_name != nullptr && guids.count (sample.participant_key) == 0) {
return false;
} if (! std::regex_search (sample.topic_name, cm_tp, re_tp) || ! std::regex_search (sample.type_name, cm_typ, re_typ)) {
return false;
} else {
std::string demangled_type = std::regex_replace (std::string (cm_typ[1]), std::regex ("::"), "/");
topic_name = std::string (cm_tp[2]);
type_name = std::string (demangled_type) + std::string (cm_typ[2]);
return true;
}
};
std::map<std::string, std::set<std::string>> tt;
if ((ret = rmw_collect_tptyp_for_kind (tt, DDS_BUILTIN_TOPIC_DCPSSUBSCRIPTION, filter_and_map)) != RMW_RET_OK ||
(ret = rmw_collect_tptyp_for_kind (tt, DDS_BUILTIN_TOPIC_DCPSPUBLICATION, filter_and_map)) != RMW_RET_OK) {
return ret;
}
return make_names_and_types (sntyp, tt, allocator);
}
extern "C" rmw_ret_t rmw_get_topic_names_and_types (const rmw_node_t *node, rcutils_allocator_t *allocator, bool no_demangle, rmw_names_and_types_t *tptyp)
{
return get_endpoint_names_and_types_by_node (node, allocator, nullptr, nullptr, no_demangle, tptyp, true, true);
}
extern "C" rmw_ret_t rmw_get_service_names_and_types (const rmw_node_t *node, rcutils_allocator_t *allocator, rmw_names_and_types_t *sntyp)
{
return get_service_names_and_types_by_node (node, allocator, nullptr, nullptr, sntyp);
}
extern "C" rmw_ret_t rmw_service_server_is_available (const rmw_node_t *node, const rmw_client_t *client, bool *is_available)
{
RET_WRONG_IMPLID (node);
RET_WRONG_IMPLID (client);
RET_NULL (is_available);
auto info = static_cast<CddsClient *> (client->data);
dds_publication_matched_status_t ps;
dds_subscription_matched_status_t cs;
if (dds_get_publication_matched_status (info->client.pub->pubh, &ps) < 0 ||
dds_get_subscription_matched_status (info->client.sub->subh, &cs) < 0) {
RMW_SET_ERROR_MSG ("rmw_service_server_is_available: get_..._matched_status failed");
return RMW_RET_ERROR;
}
*is_available = ps.current_count > 0 && cs.current_count > 0;
return RMW_RET_OK;
}
static rmw_ret_t rmw_count_pubs_or_subs (const rmw_node_t *node, dds_entity_t builtin_topic, const char *topic_name, size_t *count)
{
assert (builtin_topic == DDS_BUILTIN_TOPIC_DCPSSUBSCRIPTION || builtin_topic == DDS_BUILTIN_TOPIC_DCPSPUBLICATION);
RET_NULL (topic_name);
RET_NULL (count);
RET_WRONG_IMPLID (node);
std::string fqtopic_name = make_fqtopic (ros_topic_prefix, topic_name, "", false);
dds_entity_t rd;
if ((rd = dds_create_reader (ref_ppant (), builtin_topic, NULL, NULL)) < 0) {
unref_ppant ();
RMW_SET_ERROR_MSG ("rmw_count_pubs_or_subs failed to create reader");
return RMW_RET_ERROR;
}
dds_sample_info_t info;
void *msg = NULL;
int32_t n;
*count = 0;
while ((n = dds_take (rd, &msg, &info, 1, 1)) == 1) {
if (info.valid_data && info.instance_state == DDS_IST_ALIVE) {
auto sample = static_cast<const dds_builtintopic_endpoint_t *> (msg);
if (fqtopic_name == std::string (sample->topic_name)) {
(*count)++;
}
}
dds_return_loan (rd, &msg, n);
}
dds_delete (rd);
unref_ppant ();
return RMW_RET_OK;
}
extern "C" rmw_ret_t rmw_count_publishers (const rmw_node_t *node, const char *topic_name, size_t *count)
{
return rmw_count_pubs_or_subs (node, DDS_BUILTIN_TOPIC_DCPSPUBLICATION, topic_name, count);
}
extern "C" rmw_ret_t rmw_count_subscribers (const rmw_node_t *node, const char *topic_name, size_t *count)
{
return rmw_count_pubs_or_subs (node, DDS_BUILTIN_TOPIC_DCPSSUBSCRIPTION, topic_name, count);
}
extern "C" rmw_ret_t rmw_get_subscriber_names_and_types_by_node (const rmw_node_t *node, rcutils_allocator_t *allocator, const char *node_name, const char *node_namespace, bool no_demangle, rmw_names_and_types_t *tptyp)
{
return get_endpoint_names_and_types_by_node (node, allocator, node_name, node_namespace, no_demangle, tptyp, true, false);
}
extern "C" rmw_ret_t rmw_get_publisher_names_and_types_by_node (const rmw_node_t *node, rcutils_allocator_t *allocator, const char *node_name, const char *node_namespace, bool no_demangle, rmw_names_and_types_t *tptyp)
{
return get_endpoint_names_and_types_by_node (node, allocator, node_name, node_namespace, no_demangle, tptyp, false, true);
}
extern "C" rmw_ret_t rmw_get_service_names_and_types_by_node (const rmw_node_t *node, rcutils_allocator_t *allocator, const char *node_name, const char *node_namespace, rmw_names_and_types_t *sntyp)
{
return get_service_names_and_types_by_node (node, allocator, node_name, node_namespace, sntyp);
}
| 41.478902 | 251 | 0.65423 | [
"vector"
] |
a0b2ff449f0688cac3d97adc64e8540eb5075cec | 1,179 | cpp | C++ | 10815.cpp | mahmudahsan/203-ACM-Problems-Code | 6e8f9698809c649a4c6bbba907d973e20360bc21 | [
"MIT"
] | 31 | 2015-01-10T07:15:41.000Z | 2021-06-17T09:51:07.000Z | 10815.cpp | joycse06/203-ACM-Problems-Code | 78529b45d3caace8f006a6ed6f66390fa3f377fc | [
"Unlicense"
] | null | null | null | 10815.cpp | joycse06/203-ACM-Problems-Code | 78529b45d3caace8f006a6ed6f66390fa3f377fc | [
"Unlicense"
] | 35 | 2015-01-04T18:59:15.000Z | 2021-01-04T08:24:48.000Z | /* Problem: Andy's First Dictionary UVa 10815
Programmer: Md. Mahmud Ahsan
Description: String + Sorting
Compiled: Visual C++ 7.0
Date: 18-02-06
*/
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
#include <cctype>
#include <cstdio>
using namespace std;
void strLwr(char *s){
char str[1000];
int i;
for (i = 0; s[i]; ++i){
str[i] = tolower(s[i]);
}
str[i] = '\0';
strcpy(s, str);
}
int main(){
//freopen("input.txt", "r", stdin);
//freopen("output.txt", "w", stdout);
char input[1000], taken[1000];
vector <string> v;
int i, j, len;
while (cin.getline(input, sizeof(input))){
strLwr(input);
j = 0;
len = strlen(input);
for (i = 0; i <= len; ++i){
if (input[i] >= 'a' && input[i] <= 'z'){
taken[j++] = input[i];
}
else{
taken[j] = '\0';
j = 0;
if (strlen(taken) == 0)
continue;
string sss(taken);
v.push_back(sss);
}
}
}
sort (v.begin(), v.end());
len = v.size();
cout << v[0] << endl;
for (int i = 1; i < len; ++i){
if (v[i] == v[i-1]) continue;
cout << v[i] << endl;
}
return 0;
}
| 17.863636 | 46 | 0.512299 | [
"vector"
] |
a0c25f21c8a647c08a652cd35fe0129554337d33 | 4,082 | cpp | C++ | src/locals/tannolocal.cpp | ShengquanChen/OpenAnnotate | 116a321dbcea6fd5ac27c39186bd030c5d71ce60 | [
"MIT"
] | 1 | 2021-09-16T06:22:27.000Z | 2021-09-16T06:22:27.000Z | src/locals/tannolocal.cpp | ShengquanChen/OpenAnnotate | 116a321dbcea6fd5ac27c39186bd030c5d71ce60 | [
"MIT"
] | 1 | 2021-08-13T09:43:25.000Z | 2021-09-27T04:36:42.000Z | src/locals/tannolocal.cpp | ShengquanChen/OpenAnnotate | 116a321dbcea6fd5ac27c39186bd030c5d71ce60 | [
"MIT"
] | 1 | 2021-04-12T07:49:37.000Z | 2021-04-12T07:49:37.000Z | #include <set>
#include <vector>
#include <string.h>
#include "eutil.h"
#include "tpipe.h"
#include "tannoload.h"
#include "tannosave.h"
#include "tannowork.h"
#include "tannolocal.h"
BEGIN_OPTION_TABLE(TAnnoLocalOpts)
OPTION_ENTRY(annotate, , NONARG, TRUE)
OPTION_ENTRY(species, s, REQARG, human)
OPTION_ENTRY(assembly, a, REQARG, hg19)
OPTION_ENTRY(assay, y, REQARG, dnase)
OPTION_ENTRY(column, c, REQARG, NULL)
OPTION_ENTRY(foreground, f, REQARG, NULL)
OPTION_ENTRY(background, g, REQARG, NULL)
OPTION_ENTRY(narrowpeak, n, REQARG, NULL)
OPTION_ENTRY(broadpeak, b, REQARG, NULL)
OPTION_ENTRY(readopen, r, REQARG, NULL)
OPTION_ENTRY(binary-path, p, REQARG, NULL)
OPTION_ENTRY(head-file, e, REQARG, NULL)
OPTION_ENTRY(input-file, i, REQARG, NULL)
OPTION_ENTRY(option-file, , REQARG, NULL)
OPTION_ENTRY(status-file, , REQARG, NULL)
OPTION_ENTRY(perbasepair, , NONARG, FALSE)
OPTION_ENTRY(system, , REQARG, NULL)
OPTION_ENTRY(target, , REQARG, NULL)
OPTION_ENTRY(organ, , REQARG, NULL)
OPTION_ENTRY(celltype, , REQARG, NULL)
OPTION_ENTRY(experiment, , REQARG, NULL)
OPTION_ENTRY(biosample, , REQARG, NULL)
OPTION_ENTRY(replicate, , REQARG, NULL)
END_OPTION_TABLE(TAnnoOpts)
int TAnnoLocal::LoadOptions(int argc, char * argv[])
{
if((opts=new TAnnoLocalOpts) != NULL) {
opts->LoadOptions(argc, argv);
}
#if 0
{
FILE * fopt = fopen("/tmp/openanno.arg", "wb");
opts->SaveOptions(fopt);
fclose(fopt);
}
#endif
#if 0
{
FILE * fopt = fopen("/tmp/openanno.arg", "rb");
opts->LoadOptions(fopt);
fclose(fopt);
}
#endif
#if 0
((TOpts*)opts)->DumpOptions();
// exit(1);
#endif
return opts ? EXIT_SUCCESS : EXIT_FAILURE;
}
int TAnnoLocal::Main()
{
int nret = EXIT_SUCCESS;
if( strcasecmp((*opts)["option-file"], "NULL")) {
nret = OnLoadIni();
}
if( strcasecmp((*opts)["help"], "TRUE") == 0) {
nret = OnHelp();
} else if( strcasecmp((*opts)["annotate"], "TRUE") == 0) {
if((nret = CheckArgs()) == EXIT_SUCCESS) {
nret = OnAnnotate();
}
}
if( nret != EXIT_SUCCESS) {
nret = OnHelp();
}
return nret;
}
int TAnnoLocal::OnHelp()
{
fprintf(stdout, "Usage: openanno --species=human --assembly=hg19 --assay=dnase --foreground=foreground.txt.gz --input-file=somefile.bed.gz\n");
return EXIT_SUCCESS;
}
int TAnnoLocal::OnLoadIni()
{
fprintf(stdout, "Load ini file [%s].\n", (*opts)["option-file"]);
return EXIT_SUCCESS;
}
int TAnnoLocal::OnAnnotate()
{
vector<IAnno*> anno;
vector<void *> args;
vector<IPipe*> pipe;
anno.push_back(new TAnnoLoad);
anno.push_back(new TAnnoSave);
for(int i = 0, I = atoi((*opts)["thread"]); i < I; i++) {
anno.push_back(new TAnnoWork);
}
for(int i = 0; i < anno.size(); i++) {
args.push_back(NULL);
}
pipe.push_back(new TQueuePipe( 128));
pipe.push_back(new TQueuePipe(32768));
pipe.push_back(new TQueuePipe( 128));
anno[0]->Attach(pipe[0], PIPE_OUT);
anno[1]->Attach(pipe[1], PIPE_IN);
for(int i = 2; i < anno.size(); i++) {
anno[i]->Attach(pipe[0], PIPE_IN);
anno[i]->Attach(pipe[1], PIPE_OUT);
}
// anno[0]->Attach(pipe[2], PIPE_IN);
// anno[1]->Attach(pipe[2], PIPE_OUT);
for(int i = 0, I = anno.size(); i < I; i++) {
anno[i]->Run(opts, args[i]);
}
for(int i = 0, I = anno.size(); i < I; i++) {
anno[i]->Wait(NULL);
}
for(int i = 0, I = anno.size(); i < I; i++) {
delete anno[i];
}
for(int i = 0, I = pipe.size(); i < I; i++) {
delete pipe[i];
}
return EXIT_SUCCESS;
}
int TAnnoLocal::CheckArgs()
{
int nret = EXIT_SUCCESS;
if(strcasecmp((*opts)["input-file"], "NULL") == 0) {
nret = EXIT_FAILURE;
// } else if( strcasecmp((*opts)["species"], "human")) {
// nret = EXIT_FAILURE;
// } else if(strcasecmp((*opts)["assembly"], "hg19") && strcasecmp((*opts)["assembly"], "hg38")) {
// nret = EXIT_FAILURE;
}
return nret;
}
int main(int argc, char * argv[])
{
int nret = EXIT_FAILURE;
try {
nret = AnnoMain<TAnnoLocal>(argc, argv);
} catch(exception & e) {
fprintf(stderr, "Failed! Exception: %s.\n", e.what());
}
return nret;
}
| 25.042945 | 144 | 0.635718 | [
"vector"
] |
a0c5f136aecc2d915718ac8e20c4cb46f5a33726 | 36,709 | hpp | C++ | unit_test/tstLocalMesh.hpp | kwitaechong/Cajita | f2c44ef5cc03d83f9ce1534b8481bad95a0e089d | [
"BSD-3-Clause"
] | null | null | null | unit_test/tstLocalMesh.hpp | kwitaechong/Cajita | f2c44ef5cc03d83f9ce1534b8481bad95a0e089d | [
"BSD-3-Clause"
] | null | null | null | unit_test/tstLocalMesh.hpp | kwitaechong/Cajita | f2c44ef5cc03d83f9ce1534b8481bad95a0e089d | [
"BSD-3-Clause"
] | null | null | null | /****************************************************************************
* Copyright (c) 2019 by the Cajita authors *
* All rights reserved. *
* *
* This file is part of the Cajita library. Cajita is distributed under a *
* BSD 3-clause license. For the licensing terms see the LICENSE file in *
* the top-level directory. *
* *
* SPDX-License-Identifier: BSD-3-Clause *
****************************************************************************/
#include <Kokkos_Core.hpp>
#include <Cajita_Types.hpp>
#include <Cajita_GlobalMesh.hpp>
#include <Cajita_GlobalGrid.hpp>
#include <Cajita_ManualPartitioner.hpp>
#include <Cajita_LocalGrid.hpp>
#include <Cajita_LocalMesh.hpp>
#include <gtest/gtest.h>
#include <mpi.h>
#include <array>
#include <vector>
#include <cmath>
using namespace Cajita;
namespace Test
{
//---------------------------------------------------------------------------//
template<class LocalMeshType, class LocalGridType>
void uniformLocalMeshTest( const LocalMeshType& local_mesh,
const LocalGridType& local_grid,
const std::array<double,3>& low_corner,
const double cell_size,
const int halo_width )
{
// Get the global grid.
const auto& global_grid = local_grid.globalGrid();
// Check the low and high corners.
Kokkos::View<double[3],TEST_DEVICE> own_lc( "own_lc" );
Kokkos::View<double[3],TEST_DEVICE> own_hc( "own_hc" );
Kokkos::View<double[3],TEST_DEVICE> ghost_lc( "ghost_lc" );
Kokkos::View<double[3],TEST_DEVICE> ghost_hc( "ghost_hc" );
Kokkos::parallel_for(
"get_corners",
Kokkos::RangePolicy<TEST_EXECSPACE>(0,3),
KOKKOS_LAMBDA( const int d ){
own_lc(d) = local_mesh.lowCorner( Own(), d );
own_hc(d) = local_mesh.highCorner( Own(), d );
ghost_lc(d) = local_mesh.lowCorner( Ghost(), d );
ghost_hc(d) = local_mesh.highCorner( Ghost(), d );
});
auto own_lc_m = Kokkos::create_mirror_view_and_copy(
Kokkos::HostSpace(), own_lc );
auto own_hc_m = Kokkos::create_mirror_view_and_copy(
Kokkos::HostSpace(), own_hc );
auto ghost_lc_m = Kokkos::create_mirror_view_and_copy(
Kokkos::HostSpace(), ghost_lc );
auto ghost_hc_m = Kokkos::create_mirror_view_and_copy(
Kokkos::HostSpace(), ghost_hc );
for ( int d = 0; d < 3; ++d )
EXPECT_FLOAT_EQ(
own_lc_m(d), low_corner[d] + cell_size * global_grid.globalOffset(d) );
for ( int d = 0; d < 3; ++d )
EXPECT_FLOAT_EQ(
own_hc_m(d), low_corner[d] + cell_size * (
global_grid.globalOffset(d) + global_grid.ownedNumCell(d) ) );
for ( int d = 0; d < 3; ++d )
{
int ghost_lc_offset =
( global_grid.isPeriodic( d ) || global_grid.dimBlockId( d ) > 0 )
? halo_width : 0;
EXPECT_FLOAT_EQ(
ghost_lc_m(d), low_corner[d] + cell_size *
( global_grid.globalOffset(d) - ghost_lc_offset ) );
}
for ( int d = 0; d < 3; ++d )
{
int ghost_hc_offset =
( global_grid.isPeriodic( d ) ||
global_grid.dimBlockId( d ) < global_grid.dimNumBlock( d ) - 1 )
? local_grid.haloCellWidth() : 0;
EXPECT_FLOAT_EQ(
ghost_hc_m(d), low_corner[d] + cell_size *
( global_grid.globalOffset(d) + ghost_hc_offset +
global_grid.ownedNumCell(d) ) );
}
// Check the cell locations and measures.
auto cell_space = local_grid.indexSpace( Ghost(), Cell(), Local() );
{
auto measure = createView<double,TEST_DEVICE>( "measure", cell_space );
auto loc_x = createView<double,TEST_DEVICE>( "loc_x", cell_space );
auto loc_y = createView<double,TEST_DEVICE>( "loc_y", cell_space );
auto loc_z = createView<double,TEST_DEVICE>( "loc_z", cell_space );
Kokkos::parallel_for(
"get_cell_coord",
createExecutionPolicy( cell_space, TEST_EXECSPACE() ),
KOKKOS_LAMBDA( const int i, const int j, const int k ){
double loc[3];
int idx[3] = {i,j,k};
local_mesh.coordinates( Cell(), idx, loc );
loc_x(i,j,k) = loc[Dim::I];
loc_y(i,j,k) = loc[Dim::J];
loc_z(i,j,k) = loc[Dim::K];
measure(i,j,k) = local_mesh.measure( Cell(), idx );
});
auto measure_m = Kokkos::create_mirror_view_and_copy(
Kokkos::HostSpace(), measure );
auto loc_x_m = Kokkos::create_mirror_view_and_copy(
Kokkos::HostSpace(), loc_x );
auto loc_y_m = Kokkos::create_mirror_view_and_copy(
Kokkos::HostSpace(), loc_y );
auto loc_z_m = Kokkos::create_mirror_view_and_copy(
Kokkos::HostSpace(), loc_z );
for ( int i = 0; i < cell_space.extent(Dim::I); ++i )
for ( int j = 0; j < cell_space.extent(Dim::J); ++j )
for ( int k = 0; k < cell_space.extent(Dim::K); ++k )
{
EXPECT_FLOAT_EQ( loc_x_m(i,j,k),
ghost_lc_m(Dim::I) + cell_size * (i+0.5) );
EXPECT_FLOAT_EQ( loc_y_m(i,j,k),
ghost_lc_m(Dim::J) + cell_size * (j+0.5) );
EXPECT_FLOAT_EQ( loc_z_m(i,j,k),
ghost_lc_m(Dim::K) + cell_size * (k+0.5) );
EXPECT_FLOAT_EQ( measure_m(i,j,k),
cell_size*cell_size*cell_size );
}
}
// Check the node locations and measures.
auto node_space = local_grid.indexSpace( Ghost(), Node(), Local() );
{
auto measure = createView<double,TEST_DEVICE>( "measure", node_space );
auto loc_x = createView<double,TEST_DEVICE>( "loc_x", node_space );
auto loc_y = createView<double,TEST_DEVICE>( "loc_y", node_space );
auto loc_z = createView<double,TEST_DEVICE>( "loc_z", node_space );
Kokkos::parallel_for(
"get_node_coord",
createExecutionPolicy( node_space, TEST_EXECSPACE() ),
KOKKOS_LAMBDA( const int i, const int j, const int k ){
double loc[3];
int idx[3] = {i,j,k};
local_mesh.coordinates( Node(), idx, loc );
loc_x(i,j,k) = loc[Dim::I];
loc_y(i,j,k) = loc[Dim::J];
loc_z(i,j,k) = loc[Dim::K];
measure(i,j,k) = local_mesh.measure( Node(), idx );
});
auto measure_m = Kokkos::create_mirror_view_and_copy(
Kokkos::HostSpace(), measure );
auto loc_x_m = Kokkos::create_mirror_view_and_copy(
Kokkos::HostSpace(), loc_x );
auto loc_y_m = Kokkos::create_mirror_view_and_copy(
Kokkos::HostSpace(), loc_y );
auto loc_z_m = Kokkos::create_mirror_view_and_copy(
Kokkos::HostSpace(), loc_z );
for ( int i = 0; i < node_space.extent(Dim::I); ++i )
for ( int j = 0; j < node_space.extent(Dim::J); ++j )
for ( int k = 0; k < node_space.extent(Dim::K); ++k )
{
EXPECT_FLOAT_EQ( loc_x_m(i,j,k),
ghost_lc_m(Dim::I) + cell_size * i );
EXPECT_FLOAT_EQ( loc_y_m(i,j,k),
ghost_lc_m(Dim::J) + cell_size * j );
EXPECT_FLOAT_EQ( loc_z_m(i,j,k),
ghost_lc_m(Dim::K) + cell_size * k );
EXPECT_FLOAT_EQ( measure_m(i,j,k), 0.0 );
}
}
// Check the I-face locations and measures
auto face_i_space = local_grid.indexSpace( Ghost(), Face<Dim::I>(), Local() );
{
auto measure = createView<double,TEST_DEVICE>( "measure", face_i_space );
auto loc_x = createView<double,TEST_DEVICE>( "loc_x", face_i_space );
auto loc_y = createView<double,TEST_DEVICE>( "loc_y", face_i_space );
auto loc_z = createView<double,TEST_DEVICE>( "loc_z", face_i_space );
Kokkos::parallel_for(
"get_face_i_coord",
createExecutionPolicy( face_i_space, TEST_EXECSPACE() ),
KOKKOS_LAMBDA( const int i, const int j, const int k ){
double loc[3];
int idx[3] = {i,j,k};
local_mesh.coordinates( Face<Dim::I>(), idx, loc );
loc_x(i,j,k) = loc[Dim::I];
loc_y(i,j,k) = loc[Dim::J];
loc_z(i,j,k) = loc[Dim::K];
measure(i,j,k) = local_mesh.measure( Face<Dim::I>(), idx );
});
auto measure_m = Kokkos::create_mirror_view_and_copy(
Kokkos::HostSpace(), measure );
auto loc_x_m = Kokkos::create_mirror_view_and_copy(
Kokkos::HostSpace(), loc_x );
auto loc_y_m = Kokkos::create_mirror_view_and_copy(
Kokkos::HostSpace(), loc_y );
auto loc_z_m = Kokkos::create_mirror_view_and_copy(
Kokkos::HostSpace(), loc_z );
for ( int i = 0; i < face_i_space.extent(Dim::I); ++i )
for ( int j = 0; j < face_i_space.extent(Dim::J); ++j )
for ( int k = 0; k < face_i_space.extent(Dim::K); ++k )
{
EXPECT_FLOAT_EQ( loc_x_m(i,j,k),
ghost_lc_m(Dim::I) + cell_size * i );
EXPECT_FLOAT_EQ( loc_y_m(i,j,k),
ghost_lc_m(Dim::J) + cell_size * (j+0.5) );
EXPECT_FLOAT_EQ( loc_z_m(i,j,k),
ghost_lc_m(Dim::K) + cell_size * (k+0.5) );
EXPECT_FLOAT_EQ( measure_m(i,j,k),
cell_size*cell_size );
}
}
// Check the J-face locations and measures.
auto face_j_space = local_grid.indexSpace( Ghost(), Face<Dim::J>(), Local() );
{
auto measure = createView<double,TEST_DEVICE>( "measure", face_j_space );
auto loc_x = createView<double,TEST_DEVICE>( "loc_x", face_j_space );
auto loc_y = createView<double,TEST_DEVICE>( "loc_y", face_j_space );
auto loc_z = createView<double,TEST_DEVICE>( "loc_z", face_j_space );
Kokkos::parallel_for(
"get_face_j_coord",
createExecutionPolicy( face_j_space, TEST_EXECSPACE() ),
KOKKOS_LAMBDA( const int i, const int j, const int k ){
double loc[3];
int idx[3] = {i,j,k};
local_mesh.coordinates( Face<Dim::J>(), idx, loc );
loc_x(i,j,k) = loc[Dim::I];
loc_y(i,j,k) = loc[Dim::J];
loc_z(i,j,k) = loc[Dim::K];
measure(i,j,k) = local_mesh.measure( Face<Dim::J>(), idx );
});
auto measure_m = Kokkos::create_mirror_view_and_copy(
Kokkos::HostSpace(), measure );
auto loc_x_m = Kokkos::create_mirror_view_and_copy(
Kokkos::HostSpace(), loc_x );
auto loc_y_m = Kokkos::create_mirror_view_and_copy(
Kokkos::HostSpace(), loc_y );
auto loc_z_m = Kokkos::create_mirror_view_and_copy(
Kokkos::HostSpace(), loc_z );
for ( int i = 0; i < face_j_space.extent(Dim::I); ++i )
for ( int j = 0; j < face_j_space.extent(Dim::J); ++j )
for ( int k = 0; k < face_j_space.extent(Dim::K); ++k )
{
EXPECT_FLOAT_EQ( loc_x_m(i,j,k),
ghost_lc_m(Dim::I) + cell_size * (i+0.5) );
EXPECT_FLOAT_EQ( loc_y_m(i,j,k),
ghost_lc_m(Dim::J) + cell_size * j );
EXPECT_FLOAT_EQ( loc_z_m(i,j,k),
ghost_lc_m(Dim::K) + cell_size * (k+0.5) );
EXPECT_FLOAT_EQ( measure_m(i,j,k),
cell_size*cell_size );
}
}
// Check the K-face locations and measures.
auto face_k_space = local_grid.indexSpace( Ghost(), Face<Dim::K>(), Local() );
{
auto measure = createView<double,TEST_DEVICE>( "measure", face_k_space );
auto loc_x = createView<double,TEST_DEVICE>( "loc_x", face_k_space );
auto loc_y = createView<double,TEST_DEVICE>( "loc_y", face_k_space );
auto loc_z = createView<double,TEST_DEVICE>( "loc_z", face_k_space );
Kokkos::parallel_for(
"get_face_k_coord",
createExecutionPolicy( face_k_space, TEST_EXECSPACE() ),
KOKKOS_LAMBDA( const int i, const int j, const int k ){
double loc[3];
int idx[3] = {i,j,k};
local_mesh.coordinates( Face<Dim::K>(), idx, loc );
loc_x(i,j,k) = loc[Dim::I];
loc_y(i,j,k) = loc[Dim::J];
loc_z(i,j,k) = loc[Dim::K];
measure(i,j,k) = local_mesh.measure( Face<Dim::K>(), idx );
});
auto measure_m = Kokkos::create_mirror_view_and_copy(
Kokkos::HostSpace(), measure );
auto loc_x_m = Kokkos::create_mirror_view_and_copy(
Kokkos::HostSpace(), loc_x );
auto loc_y_m = Kokkos::create_mirror_view_and_copy(
Kokkos::HostSpace(), loc_y );
auto loc_z_m = Kokkos::create_mirror_view_and_copy(
Kokkos::HostSpace(), loc_z );
for ( int i = 0; i < face_k_space.extent(Dim::I); ++i )
for ( int j = 0; j < face_k_space.extent(Dim::J); ++j )
for ( int k = 0; k < face_k_space.extent(Dim::K); ++k )
{
EXPECT_FLOAT_EQ( loc_x_m(i,j,k),
ghost_lc_m(Dim::I) + cell_size * (i+0.5) );
EXPECT_FLOAT_EQ( loc_y_m(i,j,k),
ghost_lc_m(Dim::J) + cell_size * (j+0.5) );
EXPECT_FLOAT_EQ( loc_z_m(i,j,k),
ghost_lc_m(Dim::K) + cell_size * k );
EXPECT_FLOAT_EQ( measure_m(i,j,k),
cell_size*cell_size );
}
}
// Check the I-edge locations and measures.
auto edge_i_space = local_grid.indexSpace( Ghost(), Edge<Dim::I>(), Local() );
{
auto measure = createView<double,TEST_DEVICE>( "measure", edge_i_space );
auto loc_x = createView<double,TEST_DEVICE>( "loc_x", edge_i_space );
auto loc_y = createView<double,TEST_DEVICE>( "loc_y", edge_i_space );
auto loc_z = createView<double,TEST_DEVICE>( "loc_z", edge_i_space );
Kokkos::parallel_for(
"get_edge_i_coord",
createExecutionPolicy( edge_i_space, TEST_EXECSPACE() ),
KOKKOS_LAMBDA( const int i, const int j, const int k ){
double loc[3];
int idx[3] = {i,j,k};
local_mesh.coordinates( Edge<Dim::I>(), idx, loc );
loc_x(i,j,k) = loc[Dim::I];
loc_y(i,j,k) = loc[Dim::J];
loc_z(i,j,k) = loc[Dim::K];
measure(i,j,k) = local_mesh.measure( Edge<Dim::I>(), idx );
});
auto measure_m = Kokkos::create_mirror_view_and_copy(
Kokkos::HostSpace(), measure );
auto loc_x_m = Kokkos::create_mirror_view_and_copy(
Kokkos::HostSpace(), loc_x );
auto loc_y_m = Kokkos::create_mirror_view_and_copy(
Kokkos::HostSpace(), loc_y );
auto loc_z_m = Kokkos::create_mirror_view_and_copy(
Kokkos::HostSpace(), loc_z );
for ( int i = 0; i < edge_i_space.extent(Dim::I); ++i )
for ( int j = 0; j < edge_i_space.extent(Dim::J); ++j )
for ( int k = 0; k < edge_i_space.extent(Dim::K); ++k )
{
EXPECT_FLOAT_EQ( loc_x_m(i,j,k),
ghost_lc_m(Dim::I) + cell_size * (i+0.5) );
EXPECT_FLOAT_EQ( loc_y_m(i,j,k),
ghost_lc_m(Dim::J) + cell_size * j );
EXPECT_FLOAT_EQ( loc_z_m(i,j,k),
ghost_lc_m(Dim::K) + cell_size * k );
EXPECT_FLOAT_EQ( measure_m(i,j,k),
cell_size );
}
}
// Check the J-edge locations and measures.
auto edge_j_space = local_grid.indexSpace( Ghost(), Edge<Dim::J>(), Local() );
{
auto measure = createView<double,TEST_DEVICE>( "measure", edge_j_space );
auto loc_x = createView<double,TEST_DEVICE>( "loc_x", edge_j_space );
auto loc_y = createView<double,TEST_DEVICE>( "loc_y", edge_j_space );
auto loc_z = createView<double,TEST_DEVICE>( "loc_z", edge_j_space );
Kokkos::parallel_for(
"get_edge_j_coord",
createExecutionPolicy( edge_j_space, TEST_EXECSPACE() ),
KOKKOS_LAMBDA( const int i, const int j, const int k ){
double loc[3];
int idx[3] = {i,j,k};
local_mesh.coordinates( Edge<Dim::J>(), idx, loc );
loc_x(i,j,k) = loc[Dim::I];
loc_y(i,j,k) = loc[Dim::J];
loc_z(i,j,k) = loc[Dim::K];
measure(i,j,k) = local_mesh.measure( Edge<Dim::J>(), idx );
});
auto measure_m = Kokkos::create_mirror_view_and_copy(
Kokkos::HostSpace(), measure );
auto loc_x_m = Kokkos::create_mirror_view_and_copy(
Kokkos::HostSpace(), loc_x );
auto loc_y_m = Kokkos::create_mirror_view_and_copy(
Kokkos::HostSpace(), loc_y );
auto loc_z_m = Kokkos::create_mirror_view_and_copy(
Kokkos::HostSpace(), loc_z );
for ( int i = 0; i < edge_j_space.extent(Dim::I); ++i )
for ( int j = 0; j < edge_j_space.extent(Dim::J); ++j )
for ( int k = 0; k < edge_j_space.extent(Dim::K); ++k )
{
EXPECT_FLOAT_EQ( loc_x_m(i,j,k),
ghost_lc_m(Dim::I) + cell_size * i );
EXPECT_FLOAT_EQ( loc_y_m(i,j,k),
ghost_lc_m(Dim::J) + cell_size * (j+0.5) );
EXPECT_FLOAT_EQ( loc_z_m(i,j,k),
ghost_lc_m(Dim::K) + cell_size * k );
EXPECT_FLOAT_EQ( measure_m(i,j,k),
cell_size );
}
}
// Check the K-edge locations and measures.
auto edge_k_space = local_grid.indexSpace( Ghost(), Edge<Dim::K>(), Local() );
{
auto measure = createView<double,TEST_DEVICE>( "measure", edge_k_space );
auto loc_x = createView<double,TEST_DEVICE>( "loc_x", edge_k_space );
auto loc_y = createView<double,TEST_DEVICE>( "loc_y", edge_k_space );
auto loc_z = createView<double,TEST_DEVICE>( "loc_z", edge_k_space );
Kokkos::parallel_for(
"get_edge_k_coord",
createExecutionPolicy( edge_k_space, TEST_EXECSPACE() ),
KOKKOS_LAMBDA( const int i, const int j, const int k ){
double loc[3];
int idx[3] = {i,j,k};
local_mesh.coordinates( Edge<Dim::K>(), idx, loc );
loc_x(i,j,k) = loc[Dim::I];
loc_y(i,j,k) = loc[Dim::J];
loc_z(i,j,k) = loc[Dim::K];
measure(i,j,k) = local_mesh.measure( Edge<Dim::K>(), idx );
});
auto measure_m = Kokkos::create_mirror_view_and_copy(
Kokkos::HostSpace(), measure );
auto loc_x_m = Kokkos::create_mirror_view_and_copy(
Kokkos::HostSpace(), loc_x );
auto loc_y_m = Kokkos::create_mirror_view_and_copy(
Kokkos::HostSpace(), loc_y );
auto loc_z_m = Kokkos::create_mirror_view_and_copy(
Kokkos::HostSpace(), loc_z );
for ( int i = 0; i < edge_k_space.extent(Dim::I); ++i )
for ( int j = 0; j < edge_k_space.extent(Dim::J); ++j )
for ( int k = 0; k < edge_k_space.extent(Dim::K); ++k )
{
EXPECT_FLOAT_EQ( loc_x_m(i,j,k),
ghost_lc_m(Dim::I) + cell_size * i );
EXPECT_FLOAT_EQ( loc_y_m(i,j,k),
ghost_lc_m(Dim::J) + cell_size * j );
EXPECT_FLOAT_EQ( loc_z_m(i,j,k),
ghost_lc_m(Dim::K) + cell_size * (k+0.5) );
EXPECT_FLOAT_EQ( measure_m(i,j,k),
cell_size );
}
}
}
//---------------------------------------------------------------------------//
void uniformTest( const std::array<int,3>& ranks_per_dim,
const std::array<bool,3>& is_dim_periodic )
{
// Create the global mesh.
std::array<double,3> low_corner = { -1.2, 0.1, 1.1 };
std::array<double,3> high_corner = { -0.3, 9.5, 2.3 };
double cell_size = 0.05;
auto global_mesh = createUniformGlobalMesh(
low_corner, high_corner, cell_size );
// Create the global grid.
ManualPartitioner partitioner( ranks_per_dim );
auto global_grid = createGlobalGrid( MPI_COMM_WORLD,
global_mesh,
is_dim_periodic,
partitioner );
// Create a local grid
int halo_width = 1;
auto local_grid = createLocalGrid( global_grid, halo_width );
// Create the local mesh.
auto local_mesh = createLocalMesh<TEST_DEVICE>( *local_grid );
// Test the local mesh.
uniformLocalMeshTest( local_mesh, *local_grid, low_corner,
cell_size, halo_width );
}
//---------------------------------------------------------------------------//
void nonUniformTest( const std::array<int,3>& ranks_per_dim,
const std::array<bool,3>& is_dim_periodic )
{
// Create the global mesh.
std::array<double,3> low_corner = { -1.2, 0.1, 1.1 };
double cell_size = 0.05;
std::array<int,3> num_cell = { 18, 188, 24 };
std::array<std::vector<double>,3> edges;
for ( int d = 0; d < 3; ++d )
for ( int n = 0; n < num_cell[d] + 1; ++n )
edges[d].push_back( low_corner[d] + n * cell_size );
auto global_mesh = createNonUniformGlobalMesh(
edges[Dim::I], edges[Dim::J], edges[Dim::K] );
// Create the global grid.
ManualPartitioner partitioner( ranks_per_dim );
auto global_grid = createGlobalGrid( MPI_COMM_WORLD,
global_mesh,
is_dim_periodic,
partitioner );
// Create a local grid.
int halo_width = 1;
auto local_grid = createLocalGrid( global_grid, halo_width );
// Create the local mesh.
auto local_mesh = createLocalMesh<TEST_DEVICE>( *local_grid );
// Test the local mesh.
uniformLocalMeshTest( local_mesh, *local_grid, low_corner,
cell_size, halo_width );
}
//---------------------------------------------------------------------------//
void irregularTest( const std::array<int,3>& ranks_per_dim )
{
// Create the global mesh using functions to build the edges. Use a cyclic
// pattern for the cell sizes so we can easily compute cell sizes from
// periodic wrap-around.
std::array<double,3> low_corner = { 3.1, 4.1, -2.8 };
int ncell = 20;
double ref_cell_size = 8.0 * std::atan(1.0) / ncell;
std::array<int,3> num_cell = { ncell, ncell, ncell };
auto i_func = [=]( const int i )
{ return 0.5*std::cos(i*ref_cell_size)+low_corner[Dim::I]; };
auto j_func = [=]( const int j )
{ return 2.0*std::cos(j*ref_cell_size)+low_corner[Dim::J]; };
auto k_func = [=]( const int k )
{ return 1.5*std::cos(k*ref_cell_size)+low_corner[Dim::K]; };
std::array<std::vector<double>,3> edges;
for ( int n = 0; n < num_cell[Dim::I] + 1; ++n )
edges[Dim::I].push_back( i_func(n) );
for ( int n = 0; n < num_cell[Dim::J] + 1; ++n )
edges[Dim::J].push_back( j_func(n) );
for ( int n = 0; n < num_cell[Dim::K] + 1; ++n )
edges[Dim::K].push_back( k_func(n) );
auto global_mesh = createNonUniformGlobalMesh(
edges[Dim::I], edges[Dim::J], edges[Dim::K] );
// Create the global grid.
std::array<bool,3> periodic = {true,true,true};
ManualPartitioner partitioner( ranks_per_dim );
auto global_grid = createGlobalGrid( MPI_COMM_WORLD,
global_mesh,
periodic,
partitioner );
// Create a local grid.
int halo_width = 1;
auto local_grid = createLocalGrid( global_grid, halo_width );
// Create the local mesh.
auto local_mesh = createLocalMesh<TEST_DEVICE>( *local_grid );
// Get index spaces
auto ghost_cell_local_space = local_grid->indexSpace( Ghost(), Cell(), Local() );
auto own_cell_global_space = local_grid->indexSpace( Own(), Cell(), Global() );
auto ghost_cell_global_space = local_grid->indexSpace( Ghost(), Cell(), Global() );
auto own_cell_local_space = local_grid->indexSpace( Own(), Cell(), Local() );
// Check the low and high corners.
Kokkos::View<double[3],TEST_DEVICE> own_lc( "own_lc" );
Kokkos::View<double[3],TEST_DEVICE> own_hc( "own_hc" );
Kokkos::View<double[3],TEST_DEVICE> ghost_lc( "ghost_lc" );
Kokkos::View<double[3],TEST_DEVICE> ghost_hc( "ghost_hc" );
Kokkos::parallel_for(
"get_corners",
Kokkos::RangePolicy<TEST_EXECSPACE>(0,3),
KOKKOS_LAMBDA( const int d ){
own_lc(d) = local_mesh.lowCorner( Own(), d );
own_hc(d) = local_mesh.highCorner( Own(), d );
ghost_lc(d) = local_mesh.lowCorner( Ghost(), d );
ghost_hc(d) = local_mesh.highCorner( Ghost(), d );
});
auto own_lc_m = Kokkos::create_mirror_view_and_copy(
Kokkos::HostSpace(), own_lc );
auto own_hc_m = Kokkos::create_mirror_view_and_copy(
Kokkos::HostSpace(), own_hc );
auto ghost_lc_m = Kokkos::create_mirror_view_and_copy(
Kokkos::HostSpace(), ghost_lc );
auto ghost_hc_m = Kokkos::create_mirror_view_and_copy(
Kokkos::HostSpace(), ghost_hc );
EXPECT_FLOAT_EQ( own_lc_m(Dim::I), i_func(own_cell_global_space.min(Dim::I)) );
EXPECT_FLOAT_EQ( own_lc_m(Dim::J), j_func(own_cell_global_space.min(Dim::J)) );
EXPECT_FLOAT_EQ( own_lc_m(Dim::K), k_func(own_cell_global_space.min(Dim::K)) );
EXPECT_FLOAT_EQ( own_hc_m(Dim::I), i_func(own_cell_global_space.max(Dim::I)) );
EXPECT_FLOAT_EQ( own_hc_m(Dim::J), j_func(own_cell_global_space.max(Dim::J)) );
EXPECT_FLOAT_EQ( own_hc_m(Dim::K), k_func(own_cell_global_space.max(Dim::K)) );
EXPECT_FLOAT_EQ( ghost_lc_m(Dim::I),
i_func(ghost_cell_global_space.min(Dim::I)) );
EXPECT_FLOAT_EQ( ghost_lc_m(Dim::J),
j_func(ghost_cell_global_space.min(Dim::J)) );
EXPECT_FLOAT_EQ( ghost_lc_m(Dim::K),
k_func(ghost_cell_global_space.min(Dim::K)) );
EXPECT_FLOAT_EQ( ghost_hc_m(Dim::I),
i_func(ghost_cell_global_space.max(Dim::I)) );
EXPECT_FLOAT_EQ( ghost_hc_m(Dim::J),
j_func(ghost_cell_global_space.max(Dim::J)) );
EXPECT_FLOAT_EQ( ghost_hc_m(Dim::K),
k_func(ghost_cell_global_space.max(Dim::K)) );
// Check the cell locations and measures.
auto cell_measure = createView<double,TEST_DEVICE>(
"cell_measures", ghost_cell_local_space );
auto cell_location_x = createView<double,TEST_DEVICE>(
"cell_locations_x", ghost_cell_local_space );
auto cell_location_y = createView<double,TEST_DEVICE>(
"cell_locations_y", ghost_cell_local_space );
auto cell_location_z = createView<double,TEST_DEVICE>(
"cell_locations_z", ghost_cell_local_space );
Kokkos::parallel_for(
"get_cell_data",
createExecutionPolicy( own_cell_local_space, TEST_EXECSPACE() ),
KOKKOS_LAMBDA( const int i, const int j, const int k ){
int idx[3] = {i,j,k};
double loc[3];
local_mesh.coordinates( Cell(), idx, loc );
cell_location_x(i,j,k) = loc[Dim::I];
cell_location_y(i,j,k) = loc[Dim::J];
cell_location_z(i,j,k) = loc[Dim::K];
cell_measure(i,j,k) =
local_mesh.measure( Cell(), idx );
});
auto cell_measure_h = Kokkos::create_mirror_view_and_copy(
Kokkos::HostSpace(), cell_measure );
auto cell_location_x_h = Kokkos::create_mirror_view_and_copy(
Kokkos::HostSpace(), cell_location_x );
auto cell_location_y_h = Kokkos::create_mirror_view_and_copy(
Kokkos::HostSpace(), cell_location_y );
auto cell_location_z_h = Kokkos::create_mirror_view_and_copy(
Kokkos::HostSpace(), cell_location_z );
for ( int i = own_cell_global_space.min(Dim::I);
i < own_cell_global_space.max(Dim::I); ++i )
for ( int j = own_cell_global_space.min(Dim::J);
j < own_cell_global_space.max(Dim::J); ++j )
for ( int k = own_cell_global_space.min(Dim::K);
k < own_cell_global_space.max(Dim::K); ++k )
{
double measure = ( i_func(i+1) - i_func(i) ) *
( j_func(j+1) - j_func(j) ) *
( k_func(k+1) - k_func(k) );
double compute_m = cell_measure_h(
i - ghost_cell_global_space.min(Dim::I),
j - ghost_cell_global_space.min(Dim::J),
k - ghost_cell_global_space.min(Dim::K) );
EXPECT_FLOAT_EQ( measure, compute_m );
double x_loc = ( i_func(i+1) + i_func(i) ) / 2.0;
double compute_x = cell_location_x_h(
i - ghost_cell_global_space.min(Dim::I),
j - ghost_cell_global_space.min(Dim::J),
k - ghost_cell_global_space.min(Dim::K) );
EXPECT_FLOAT_EQ( x_loc, compute_x );
double y_loc = ( j_func(j+1) + j_func(j) ) / 2.0;
double compute_y = cell_location_y_h(
i - ghost_cell_global_space.min(Dim::I),
j - ghost_cell_global_space.min(Dim::J),
k - ghost_cell_global_space.min(Dim::K) );
EXPECT_FLOAT_EQ( y_loc, compute_y );
double z_loc = ( k_func(k+1) + k_func(k) ) / 2.0;
double compute_z = cell_location_z_h(
i - ghost_cell_global_space.min(Dim::I),
j - ghost_cell_global_space.min(Dim::J),
k - ghost_cell_global_space.min(Dim::K) );
EXPECT_FLOAT_EQ( z_loc, compute_z );
}
}
//---------------------------------------------------------------------------//
// RUN TESTS
//---------------------------------------------------------------------------//
TEST( mesh, periodic_uniform_test )
{
std::array<bool,3> is_dim_periodic = {true,true,true};
// Let MPI compute the partitioning for this test.
int comm_size;
MPI_Comm_size( MPI_COMM_WORLD, &comm_size );
std::array<int,3> ranks_per_dim = {0,0,0};
MPI_Dims_create( comm_size, 3, ranks_per_dim.data() );
// Test with different block configurations to make sure all the
// dimensions get partitioned even at small numbers of ranks.
uniformTest( ranks_per_dim, is_dim_periodic );
std::swap( ranks_per_dim[0], ranks_per_dim[1] );
uniformTest( ranks_per_dim, is_dim_periodic );
std::swap( ranks_per_dim[0], ranks_per_dim[2] );
uniformTest( ranks_per_dim, is_dim_periodic );
std::swap( ranks_per_dim[1], ranks_per_dim[2] );
uniformTest( ranks_per_dim, is_dim_periodic );
std::swap( ranks_per_dim[0], ranks_per_dim[1] );
uniformTest( ranks_per_dim, is_dim_periodic );
}
//---------------------------------------------------------------------------//
TEST( mesh, periodic_non_uniform_test )
{
std::array<bool,3> is_dim_periodic = {true,true,true};
// Let MPI compute the partitioning for this test.
int comm_size;
MPI_Comm_size( MPI_COMM_WORLD, &comm_size );
std::array<int,3> ranks_per_dim = {0,0,0};
MPI_Dims_create( comm_size, 3, ranks_per_dim.data() );
// Test with different block configurations to make sure all the
// dimensions get partitioned even at small numbers of ranks.
nonUniformTest( ranks_per_dim, is_dim_periodic );
std::swap( ranks_per_dim[0], ranks_per_dim[1] );
nonUniformTest( ranks_per_dim, is_dim_periodic );
std::swap( ranks_per_dim[0], ranks_per_dim[2] );
nonUniformTest( ranks_per_dim, is_dim_periodic );
std::swap( ranks_per_dim[1], ranks_per_dim[2] );
nonUniformTest( ranks_per_dim, is_dim_periodic );
std::swap( ranks_per_dim[0], ranks_per_dim[1] );
nonUniformTest( ranks_per_dim, is_dim_periodic );
}
//---------------------------------------------------------------------------//
TEST( mesh, non_periodic_uniform_test )
{
std::array<bool,3> is_dim_periodic = {false,false,false};
// Let MPI compute the partitioning for this test.
int comm_size;
MPI_Comm_size( MPI_COMM_WORLD, &comm_size );
std::array<int,3> ranks_per_dim = {0,0,0};
MPI_Dims_create( comm_size, 3, ranks_per_dim.data() );
// Test with different block configurations to make sure all the
// dimensions get partitioned even at small numbers of ranks.
uniformTest( ranks_per_dim, is_dim_periodic );
std::swap( ranks_per_dim[0], ranks_per_dim[1] );
uniformTest( ranks_per_dim, is_dim_periodic );
std::swap( ranks_per_dim[0], ranks_per_dim[2] );
uniformTest( ranks_per_dim, is_dim_periodic );
std::swap( ranks_per_dim[1], ranks_per_dim[2] );
uniformTest( ranks_per_dim, is_dim_periodic );
std::swap( ranks_per_dim[0], ranks_per_dim[1] );
uniformTest( ranks_per_dim, is_dim_periodic );
}
//---------------------------------------------------------------------------//
TEST( mesh, non_periodic_non_uniform_test )
{
std::array<bool,3> is_dim_periodic = {false,false,false};
// Let MPI compute the partitioning for this test.
int comm_size;
MPI_Comm_size( MPI_COMM_WORLD, &comm_size );
std::array<int,3> ranks_per_dim = {0,0,0};
MPI_Dims_create( comm_size, 3, ranks_per_dim.data() );
// Test with different block configurations to make sure all the
// dimensions get partitioned even at small numbers of ranks.
nonUniformTest( ranks_per_dim, is_dim_periodic );
std::swap( ranks_per_dim[0], ranks_per_dim[1] );
nonUniformTest( ranks_per_dim, is_dim_periodic );
std::swap( ranks_per_dim[0], ranks_per_dim[2] );
nonUniformTest( ranks_per_dim, is_dim_periodic );
std::swap( ranks_per_dim[1], ranks_per_dim[2] );
nonUniformTest( ranks_per_dim, is_dim_periodic );
std::swap( ranks_per_dim[0], ranks_per_dim[1] );
nonUniformTest( ranks_per_dim, is_dim_periodic );
}
//---------------------------------------------------------------------------//
TEST( mesh, irregular_non_uniform_test )
{
// Let MPI compute the partitioning for this test.
int comm_size;
MPI_Comm_size( MPI_COMM_WORLD, &comm_size );
std::array<int,3> ranks_per_dim = {0,0,0};
MPI_Dims_create( comm_size, 3, ranks_per_dim.data() );
// Test with different block configurations to make sure all the
// dimensions get partitioned even at small numbers of ranks.
irregularTest( ranks_per_dim );
std::swap( ranks_per_dim[0], ranks_per_dim[1] );
irregularTest( ranks_per_dim );
std::swap( ranks_per_dim[0], ranks_per_dim[2] );
irregularTest( ranks_per_dim );
std::swap( ranks_per_dim[1], ranks_per_dim[2] );
irregularTest( ranks_per_dim );
std::swap( ranks_per_dim[0], ranks_per_dim[1] );
irregularTest( ranks_per_dim );
}
//---------------------------------------------------------------------------//
} // end namespace Test
| 46.467089 | 87 | 0.546978 | [
"mesh",
"vector"
] |
a0c96c51237f2eed64bd496aa32ba998ea1c7697 | 23,963 | cpp | C++ | src/library.cpp | th0rex/binaryninja_zydis | 6c7fe6beac58634457ba3adfc69b55f343128e43 | [
"MIT"
] | null | null | null | src/library.cpp | th0rex/binaryninja_zydis | 6c7fe6beac58634457ba3adfc69b55f343128e43 | [
"MIT"
] | null | null | null | src/library.cpp | th0rex/binaryninja_zydis | 6c7fe6beac58634457ba3adfc69b55f343128e43 | [
"MIT"
] | null | null | null | #include <array>
#include <cinttypes>
#include "Zydis/Zydis.h"
#include "binaryninjaapi.h"
using namespace BinaryNinja;
#define CHECK_RESULT(r) \
do { \
if ((r) != ZYDIS_STATUS_SUCCESS) { \
return false; \
} \
} while (0);
#define CHECK_RESULT2(r) \
do { \
if (auto a = (r); a != ZYDIS_STATUS_SUCCESS) { \
return a; \
} \
} while (0);
template <size_t address_size>
struct address_traits;
template <>
struct address_traits<4> {
constexpr static const char* arch_name = "Zydis x86";
constexpr static const char* bn_arch_name = "x86";
constexpr static ZydisAddressWidth address_width = ZYDIS_ADDRESS_WIDTH_32;
constexpr static ZydisMachineMode machine_mode = ZYDIS_MACHINE_MODE_LEGACY_32;
};
template <>
struct address_traits<8> {
constexpr static const char* arch_name = "Zydis x64";
constexpr static const char* bn_arch_name = "x86_64";
constexpr static ZydisAddressWidth address_width = ZYDIS_ADDRESS_WIDTH_64;
constexpr static ZydisMachineMode machine_mode = ZYDIS_MACHINE_MODE_LONG_64;
};
static bool is_branch(const ZydisDecodedInstruction& insn) {
const auto c = insn.meta.category;
return c == ZYDIS_CATEGORY_COND_BR || c == ZYDIS_CATEGORY_CALL ||
c == ZYDIS_CATEGORY_RET || c == ZYDIS_CATEGORY_SYSCALL ||
c == ZYDIS_CATEGORY_UNCOND_BR;
}
static void add_branch(BNBranchType type, BNBranchType fall_back,
const ZydisDecodedInstruction& insn,
InstructionInfo& result) {
const auto& op = insn.operands[0];
if (op.type == ZYDIS_OPERAND_TYPE_IMMEDIATE) {
uint64_t value = 0;
ZydisCalcAbsoluteAddress(&insn, &op, &value);
result.AddBranch(type, value);
} else if (op.type == ZYDIS_OPERAND_TYPE_REGISTER) {
result.AddBranch(fall_back);
} else {
assert(0);
}
}
static void add_cond_branch(const ZydisDecodedInstruction& insn,
InstructionInfo& result) {
switch (insn.mnemonic) {
// jb, jbe, jcxz, jecxz, jkzd, jl, jle, jo, jp, jrcxz, js, jz, loop, loope
case ZYDIS_MNEMONIC_JB:
case ZYDIS_MNEMONIC_JBE:
case ZYDIS_MNEMONIC_JCXZ:
case ZYDIS_MNEMONIC_JECXZ:
case ZYDIS_MNEMONIC_JKZD:
case ZYDIS_MNEMONIC_JL:
case ZYDIS_MNEMONIC_JLE:
case ZYDIS_MNEMONIC_JO:
case ZYDIS_MNEMONIC_JP:
case ZYDIS_MNEMONIC_JRCXZ:
case ZYDIS_MNEMONIC_JS:
case ZYDIS_MNEMONIC_JZ:
case ZYDIS_MNEMONIC_LOOP:
case ZYDIS_MNEMONIC_LOOPE:
// jknzd, jnb, jnbe, jnl, jnle, jno, jnp, jns, jnz, loopne
case ZYDIS_MNEMONIC_JKNZD:
case ZYDIS_MNEMONIC_JNB:
case ZYDIS_MNEMONIC_JNBE:
case ZYDIS_MNEMONIC_JNL:
case ZYDIS_MNEMONIC_JNLE:
case ZYDIS_MNEMONIC_JNO:
case ZYDIS_MNEMONIC_JNP:
case ZYDIS_MNEMONIC_JNS:
case ZYDIS_MNEMONIC_JNZ:
case ZYDIS_MNEMONIC_LOOPNE:
add_branch(BNBranchType::TrueBranch, BNBranchType::IndirectBranch, insn,
result);
result.AddBranch(BNBranchType::FalseBranch,
insn.instrAddress + insn.length);
break;
default:
assert(0);
}
}
static void add_branches(const ZydisDecodedInstruction& insn,
InstructionInfo& result) {
const auto c = insn.meta.category;
if (c == ZYDIS_CATEGORY_CALL) {
assert(insn.operandCount > 0);
add_branch(BNBranchType::CallDestination, BNBranchType::CallDestination,
insn, result);
} else if (c == ZYDIS_CATEGORY_COND_BR) {
assert(insn.operandCount > 0);
add_cond_branch(insn, result);
} else if (c == ZYDIS_CATEGORY_RET) {
result.AddBranch(BNBranchType::FunctionReturn);
} else if (c == ZYDIS_CATEGORY_SYSCALL) {
result.AddBranch(BNBranchType::SystemCall);
} else if (c == ZYDIS_CATEGORY_UNCOND_BR) {
assert(insn.operandCount > 0);
add_branch(BNBranchType::UnconditionalBranch, BNBranchType::IndirectBranch,
insn, result);
} else {
assert(false &&
"add_branches shouldn't be called with an instruction that isn't a "
"branch");
}
}
template <size_t address_size>
class zydis_architecture : public Architecture {
using address_traits = address_traits<address_size>;
ZydisDecoder _decoder;
ZydisFormatter _formatter;
ZydisFormatterFormatFunc _orig_print_prefixes = nullptr;
ZydisFormatterFormatFunc _orig_print_mnemonic = nullptr;
ZydisFormatterFormatOperandFunc _orig_format_operand_reg = nullptr;
ZydisFormatterFormatOperandFunc _orig_format_operand_mem = nullptr;
ZydisFormatterFormatOperandFunc _orig_format_operand_ptr = nullptr;
ZydisFormatterFormatOperandFunc _orig_format_operand_imm = nullptr;
ZydisFormatterFormatOperandFunc _orig_print_operand_size = nullptr;
ZydisFormatterFormatOperandFunc _orig_print_segment = nullptr;
ZydisFormatterFormatOperandFunc _orig_print_displacement = nullptr;
ZydisFormatterFormatOperandFunc _orig_print_immediate = nullptr;
ZydisFormatterFormatAddressFunc _orig_print_address = nullptr;
ZydisFormatterFormatDecoratorFunc _orig_print_decorator = nullptr;
ZydisFormatterPrintOperandSeperatorFunc _orig_print_operand_seperator =
nullptr;
std::array<char, 512> _buffer;
Architecture* _arch;
struct hook_data {
hook_data(zydis_architecture<address_size>& arch,
std::vector<InstructionTextToken>& instruction_text_tokens)
: arch(arch), tokens(instruction_text_tokens) {}
zydis_architecture<address_size>& arch;
std::vector<InstructionTextToken>& tokens;
};
#define TRANSLATE_STRING(n, ...) \
auto* data = static_cast<hook_data*>(user_data); \
auto* before = *buffer; \
CHECK_RESULT2(data->arch._orig_##n(__VA_ARGS__)); \
auto* end = *buffer; \
std::string str{before, end};
#define TRANSLATE_VALUE(n, t, v, ...) \
TRANSLATE_STRING(n, __VA_ARGS__); \
data->tokens.push_back(InstructionTextToken{(t), str, v}); \
return ZYDIS_STATUS_SUCCESS;
#define TRANSLATE(n, t, ...) TRANSLATE_VALUE(n, t, 0, __VA_ARGS__)
static ZydisStatus print_prefixes(const ZydisFormatter* f, char** buffer,
ZydisUSize buffer_len,
const ZydisDecodedInstruction* insn,
void* user_data) {
TRANSLATE(print_prefixes, TextToken, f, buffer, buffer_len, insn,
user_data);
}
static ZydisStatus print_mnemonic(const ZydisFormatter* f, char** buffer,
ZydisUSize buffer_len,
const ZydisDecodedInstruction* insn,
void* user_data) {
TRANSLATE(print_mnemonic, InstructionToken, f, buffer, buffer_len, insn,
user_data);
}
static ZydisStatus format_operand_reg(const ZydisFormatter* f, char** buffer,
ZydisUSize buffer_len,
const ZydisDecodedInstruction* insn,
const ZydisDecodedOperand* operand,
void* user_data) {
TRANSLATE(format_operand_reg, RegisterToken, f, buffer, buffer_len, insn,
operand, user_data);
}
static ZydisStatus format_operand_mem(const ZydisFormatter* f, char** buffer,
ZydisUSize buffer_len,
const ZydisDecodedInstruction* insn,
const ZydisDecodedOperand* operand,
void* user_data) {
auto* data = static_cast<hook_data*>(user_data);
data->tokens.push_back(InstructionTextToken{BeginMemoryOperandToken, "["});
// Adapted from zydis code
const char* buf_end = *buffer + buffer_len;
if (operand->mem.disp.hasDisplacement &&
((operand->mem.base == ZYDIS_REGISTER_NONE) ||
(operand->mem.base == ZYDIS_REGISTER_EIP) ||
(operand->mem.base == ZYDIS_REGISTER_RIP)) &&
(operand->mem.index == ZYDIS_REGISTER_NONE) &&
(operand->mem.scale == 0)) {
CHECK_RESULT2(data->arch._orig_format_operand_mem(
f, buffer, buffer_len, insn, operand, user_data));
} else {
if (operand->mem.base != ZYDIS_REGISTER_NONE) {
const char* reg = ZydisRegisterGetString(operand->mem.base);
if (reg == nullptr) {
return ZYDIS_STATUS_INVALID_PARAMETER;
}
data->tokens.push_back(InstructionTextToken{RegisterToken, reg});
}
if ((operand->mem.index != ZYDIS_REGISTER_NONE) &&
(operand->mem.type != ZYDIS_MEMOP_TYPE_MIB)) {
const char* reg = ZydisRegisterGetString(operand->mem.index);
if (reg == nullptr) {
return ZYDIS_STATUS_INVALID_PARAMETER;
}
if (operand->mem.base != ZYDIS_REGISTER_NONE) {
data->tokens.push_back(InstructionTextToken{TextToken, " + "});
}
data->tokens.push_back(InstructionTextToken{RegisterToken, reg});
if (operand->mem.scale != 0) {
char b[32] = {'\0'};
snprintf(b, 32, "%d", operand->mem.scale);
data->tokens.push_back(InstructionTextToken{TextToken, " * "});
data->tokens.push_back(
InstructionTextToken{IntegerToken, b, operand->mem.scale});
}
}
CHECK_RESULT2(print_displacement(f, buffer, buf_end - *buffer, insn,
operand, user_data));
}
data->tokens.push_back(InstructionTextToken{EndMemoryOperandToken, "]"});
return ZYDIS_STATUS_SUCCESS;
}
static ZydisStatus format_operand_ptr(const ZydisFormatter* f, char** buffer,
ZydisUSize buffer_len,
const ZydisDecodedInstruction* insn,
const ZydisDecodedOperand* operand,
void* user_data) {
TRANSLATE(format_operand_ptr, TextToken, f, buffer, buffer_len, insn,
operand, user_data);
}
static ZydisStatus format_operand_imm(const ZydisFormatter* f, char** buffer,
ZydisUSize buffer_len,
const ZydisDecodedInstruction* insn,
const ZydisDecodedOperand* operand,
void* user_data) {
auto* data = static_cast<hook_data*>(user_data);
CHECK_RESULT2(data->arch._orig_format_operand_imm(
f, buffer, buffer_len, insn, operand, user_data));
return ZYDIS_STATUS_SUCCESS;
}
static ZydisStatus print_operand_size(const ZydisFormatter* f, char** buffer,
ZydisUSize buffer_len,
const ZydisDecodedInstruction* insn,
const ZydisDecodedOperand* operand,
void* user_data) {
TRANSLATE(print_operand_size, TextToken, f, buffer, buffer_len, insn,
operand, user_data);
}
static ZydisStatus print_segment(const ZydisFormatter* f, char** buffer,
ZydisUSize buffer_len,
const ZydisDecodedInstruction* insn,
const ZydisDecodedOperand* operand,
void* user_data) {
TRANSLATE(print_segment, TextToken, f, buffer, buffer_len, insn, operand,
user_data);
}
static ZydisStatus print_displacement(const ZydisFormatter* f, char** buffer,
ZydisUSize buffer_len,
const ZydisDecodedInstruction* insn,
const ZydisDecodedOperand* operand,
void* user_data) {
auto* data = static_cast<hook_data*>(user_data);
auto* before = *buffer;
CHECK_RESULT2(data->arch._orig_print_displacement(
f, buffer, buffer_len, insn, operand, user_data));
auto* after = *buffer;
auto start = 0;
if (before[0] == '+') {
data->tokens.push_back(InstructionTextToken{TextToken, " + "});
++start;
}
data->tokens.push_back(
InstructionTextToken{IntegerToken, std::string{before + start, after}});
return ZYDIS_STATUS_SUCCESS;
}
static ZydisStatus print_immediate(const ZydisFormatter* f, char** buffer,
ZydisUSize buffer_len,
const ZydisDecodedInstruction* insn,
const ZydisDecodedOperand* operand,
void* user_data) {
TRANSLATE_VALUE(print_immediate, IntegerToken, operand->imm.value.u, f,
buffer, buffer_len, insn, operand, user_data);
}
static ZydisStatus print_address(const ZydisFormatter* f, char** buffer,
ZydisUSize buffer_len,
const ZydisDecodedInstruction* insn,
const ZydisDecodedOperand* operand,
ZydisU64 address, void* user_data) {
TRANSLATE_VALUE(print_address, PossibleAddressToken, address, f, buffer,
buffer_len, insn, operand, address, user_data);
}
static ZydisStatus print_decorator(const ZydisFormatter* f, char** buffer,
ZydisUSize buffer_len,
const ZydisDecodedInstruction* insn,
const ZydisDecodedOperand* operand,
ZydisDecoratorType type, void* user_data) {
TRANSLATE_STRING(print_decorator, f, buffer, buffer_len, insn, operand,
type, user_data);
size_t pos = 0;
for (pos = str.find(" {", pos); pos != std::string::npos;
pos = str.find(" {", pos)) {
data->tokens.push_back(InstructionTextToken{TextToken, " {"});
const auto end_pos = str.find('}', pos);
assert(end_pos != std::string::npos);
assert(pos + 2 != end_pos);
data->tokens.push_back(InstructionTextToken{
RegisterToken,
std::string{str.begin() + pos + 2, str.begin() + end_pos}});
data->tokens.push_back(InstructionTextToken{TextToken, "}"});
pos = end_pos;
}
return ZYDIS_STATUS_SUCCESS;
}
static ZydisStatus print_operand_seperator(const ZydisFormatter* f,
char** buffer,
ZydisUSize buffer_len,
ZydisU8 index, void* user_data) {
auto* d2 = static_cast<hook_data*>(user_data);
if (d2->tokens.size() >= 2 &&
d2->tokens[d2->tokens.size() - 2].type == OperandSeparatorToken &&
d2->tokens[d2->tokens.size() - 2].text == ", ") {
return ZYDIS_STATUS_SUCCESS;
}
TRANSLATE(print_operand_seperator, OperandSeparatorToken, f, buffer,
buffer_len, index, user_data);
}
#undef TRANSLATE
#undef TRANSLATE_VALUE
#undef TRANSLATE_STRING
bool set_formatter_hooks() {
const void* c = nullptr;
#define SET_HOOK(h, f) \
c = (const void*)(&(f)); \
CHECK_RESULT(ZydisFormatterSetHook(&_formatter, h, &c)); \
_orig_##f = (decltype(_orig_##f))(c);
SET_HOOK(ZYDIS_FORMATTER_HOOK_PRINT_PREFIXES, print_prefixes);
SET_HOOK(ZYDIS_FORMATTER_HOOK_PRINT_MNEMONIC, print_mnemonic);
SET_HOOK(ZYDIS_FORMATTER_HOOK_FORMAT_OPERAND_REG, format_operand_reg);
SET_HOOK(ZYDIS_FORMATTER_HOOK_FORMAT_OPERAND_MEM, format_operand_mem);
SET_HOOK(ZYDIS_FORMATTER_HOOK_FORMAT_OPERAND_PTR, format_operand_ptr);
SET_HOOK(ZYDIS_FORMATTER_HOOK_FORMAT_OPERAND_IMM, format_operand_imm);
SET_HOOK(ZYDIS_FORMATTER_HOOK_PRINT_OPERANDSIZE, print_operand_size);
SET_HOOK(ZYDIS_FORMATTER_HOOK_PRINT_SEGMENT, print_segment);
SET_HOOK(ZYDIS_FORMATTER_HOOK_PRINT_DISPLACEMENT, print_displacement);
SET_HOOK(ZYDIS_FORMATTER_HOOK_PRINT_IMMEDIATE, print_immediate);
SET_HOOK(ZYDIS_FORMATTER_HOOK_PRINT_ADDRESS, print_address);
SET_HOOK(ZYDIS_FORMATTER_HOOK_PRINT_DECORATOR, print_decorator);
SET_HOOK(ZYDIS_FORMATTER_HOOK_PRINT_OPERAND_SEPERATOR,
print_operand_seperator);
#undef SET_HOOK
return true;
}
public:
zydis_architecture()
: Architecture(address_traits::arch_name),
_arch{new CoreArchitecture(
BNGetArchitectureByName(address_traits::bn_arch_name))},
_decoder{},
_formatter{},
_buffer{} {
if (ZydisDecoderInit(&_decoder, address_traits::machine_mode,
address_traits::address_width) !=
ZYDIS_STATUS_SUCCESS) {
throw std::runtime_error("Could not initialize the zydis decoder");
}
if (ZydisFormatterInit(&_formatter, ZYDIS_FORMATTER_STYLE_INTEL) !=
ZYDIS_STATUS_SUCCESS) {
throw std::runtime_error("Could not initialize the zydis formatter");
}
if (!set_formatter_hooks()) {
throw std::runtime_error("Could not set formatter hooks");
}
if (ZydisFormatterSetProperty(&_formatter,
ZYDIS_FORMATTER_PROP_HEX_UPPERCASE,
0) != ZYDIS_STATUS_SUCCESS) {
throw std::runtime_error("Could not set formatter property");
}
if (ZydisFormatterSetProperty(&_formatter,
ZYDIS_FORMATTER_PROP_FORCE_OPERANDSIZE,
1) != ZYDIS_STATUS_SUCCESS) {
throw std::runtime_error("Could not force operand size");
}
}
size_t GetAddressSize() const override { return address_size; }
size_t GetDefaultIntegerSize() const override { return GetAddressSize(); }
bool GetInstructionInfo(const uint8_t* data, uint64_t addr, size_t max_len,
InstructionInfo& result) override {
ZydisDecodedInstruction insn{};
CHECK_RESULT(
ZydisDecoderDecodeBuffer(&_decoder, data, max_len, addr, &insn));
result.length = insn.length;
if (is_branch(insn)) {
add_branches(insn, result);
}
return true;
}
bool GetInstructionText(const uint8_t* data, uint64_t addr, size_t& len,
std::vector<InstructionTextToken>& result) override {
ZydisDecodedInstruction insn{};
hook_data hd{*this, result};
CHECK_RESULT(ZydisDecoderDecodeBuffer(&_decoder, data, len, addr, &insn));
CHECK_RESULT(ZydisFormatterFormatInstructionEx(
&_formatter, &insn, _buffer.data(), _buffer.size(), &hd));
len = insn.length;
return true;
}
BNEndianness GetEndianness() const override { return LittleEndian; }
bool GetInstructionLowLevelIL(const uint8_t* data, uint64_t addr, size_t& len,
LowLevelILFunction& il) override {
return _arch->GetInstructionLowLevelIL(data, addr, len, il);
}
size_t GetFlagWriteLowLevelIL(BNLowLevelILOperation op, size_t size,
uint32_t flag_write_type, uint32_t flag,
BNRegisterOrConstant* operands,
size_t operand_count,
LowLevelILFunction& il) override {
return _arch->GetFlagWriteLowLevelIL(op, size, flag_write_type, flag,
operands, operand_count, il);
}
std::string GetRegisterName(uint32_t reg) override {
return _arch->GetRegisterName(reg);
}
std::string GetFlagName(uint32_t flag) override {
return _arch->GetFlagName(flag);
}
std::vector<uint32_t> GetAllFlags() override { return _arch->GetAllFlags(); }
std::string GetFlagWriteTypeName(uint32_t flags) override {
return _arch->GetFlagWriteTypeName(flags);
}
std::vector<uint32_t> GetAllFlagWriteTypes() override {
return _arch->GetAllFlagWriteTypes();
}
BNFlagRole GetFlagRole(uint32_t flag) override {
return _arch->GetFlagRole(flag);
}
std::vector<uint32_t> GetFlagsRequiredForFlagCondition(
BNLowLevelILFlagCondition cond) override {
return _arch->GetFlagsRequiredForFlagCondition(cond);
}
std::vector<uint32_t> GetFlagsWrittenByFlagWriteType(
uint32_t write_type) override {
return _arch->GetFlagsWrittenByFlagWriteType(write_type);
}
bool IsNeverBranchPatchAvailable(const uint8_t* data, uint64_t addr,
size_t len) override {
return _arch->IsNeverBranchPatchAvailable(data, addr, len);
}
bool IsAlwaysBranchPatchAvailable(const uint8_t* data, uint64_t addr,
size_t len) override {
return _arch->IsAlwaysBranchPatchAvailable(data, addr, len);
}
bool IsInvertBranchPatchAvailable(const uint8_t* data, uint64_t addr,
size_t len) override {
return _arch->IsInvertBranchPatchAvailable(data, addr, len);
}
bool IsSkipAndReturnZeroPatchAvailable(const uint8_t* data, uint64_t addr,
size_t len) override {
return _arch->IsSkipAndReturnZeroPatchAvailable(data, addr, len);
}
bool IsSkipAndReturnValuePatchAvailable(const uint8_t* data, uint64_t addr,
size_t len) override {
return _arch->IsSkipAndReturnValuePatchAvailable(data, addr, len);
}
bool ConvertToNop(uint8_t* data, uint64_t addr, size_t len) override {
return _arch->ConvertToNop(data, addr, len);
}
bool AlwaysBranch(uint8_t* data, uint64_t addr, size_t len) override {
return _arch->AlwaysBranch(data, addr, len);
}
bool InvertBranch(uint8_t* data, uint64_t addr, size_t len) override {
return _arch->InvertBranch(data, addr, len);
}
bool SkipAndReturnValue(uint8_t* data, uint64_t addr, size_t len,
uint64_t value) override {
return _arch->SkipAndReturnValue(data, addr, len, value);
}
std::vector<uint32_t> GetFullWidthRegisters() override {
return _arch->GetFullWidthRegisters();
}
std::vector<uint32_t> GetGlobalRegisters() override {
return _arch->GetGlobalRegisters();
}
std::vector<uint32_t> GetAllRegisters() override {
return _arch->GetAllRegisters();
}
BNRegisterInfo GetRegisterInfo(uint32_t reg) override {
return _arch->GetRegisterInfo(reg);
}
uint32_t GetStackPointerRegister() override {
return _arch->GetStackPointerRegister();
}
bool Assemble(const std::string& code, uint64_t addr, DataBuffer& result,
std::string& errors) override {
return _arch->Assemble(code, addr, result, errors);
}
};
extern "C" {
BINARYNINJAPLUGIN void CorePluginDependencies() {
SetCurrentPluginLoadOrder(LatePluginLoadOrder);
}
BINARYNINJAPLUGIN bool CorePluginInit() {
auto* zydis_arch = new zydis_architecture<4>();
Architecture::Register(zydis_arch);
auto* zydis_x64_arch = new zydis_architecture<8>();
Architecture::Register(zydis_x64_arch);
BinaryViewType::RegisterArchitecture("ELF", 3, LittleEndian, zydis_arch);
BinaryViewType::RegisterArchitecture("PE", 0x14c, LittleEndian, zydis_arch);
BinaryViewType::RegisterArchitecture("Mach-O", 0x7, LittleEndian, zydis_arch);
BinaryViewType::RegisterArchitecture("ELF", 0x3E, LittleEndian,
zydis_x64_arch);
BinaryViewType::RegisterArchitecture("PE", 0x8664, LittleEndian,
zydis_x64_arch);
// PE: 0x8664
// ELF: 0x3E
// no idea about Mach-o
return true;
}
};
| 38.036508 | 80 | 0.627008 | [
"vector"
] |
a0ce8be0955839c51eb444c606a38fe5f6ef79b3 | 3,981 | cpp | C++ | dphGui/src/settingsdialog.cpp | ivzhuravlev/dining_philosophers | 2124dc73fa06490686de75a38e45a3b78f8855ac | [
"MIT"
] | 5 | 2018-12-27T11:02:05.000Z | 2021-12-20T03:39:47.000Z | dphGui/src/settingsdialog.cpp | ivzhuravlev/dining_philosophers | 2124dc73fa06490686de75a38e45a3b78f8855ac | [
"MIT"
] | null | null | null | dphGui/src/settingsdialog.cpp | ivzhuravlev/dining_philosophers | 2124dc73fa06490686de75a38e45a3b78f8855ac | [
"MIT"
] | 2 | 2021-12-16T06:50:59.000Z | 2021-12-18T14:51:18.000Z | #include "settingsdialog.h"
#include "settings.h"
#include "dphCore/dinnersettings.h"
#include "dinnersettingswidget.h"
#include "scenesettingswidget.h"
#include "visualsettingswidget.h"
#include <QPushButton>
#include <QListWidget>
#include <QStackedWidget>
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QDebug>
SettingsDialog::SettingsDialog(dph::DinnerSettings dinSet, SceneSettings sceneSet,
VisualSettings visSet, QWidget* parent) :
QDialog(parent)
{
setMinimumSize(355, 320);
_listWidget = new QListWidget(this);
_listWidget->setViewMode(QListView::IconMode);
_listWidget->setIconSize(QSize(48, 48));
_listWidget->setMovement(QListView::Static);
_listWidget->setFlow(QListView::LeftToRight);
_listWidget->setSpacing(20);
_listWidget->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
_listWidget->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
_listWidget->setFixedSize(332, 110);
createIcons();
_listWidget->setCurrentRow(0);
connect(_listWidget, &QListWidget::currentItemChanged, this, &SettingsDialog::changePage);
_stackWidget = new QStackedWidget(this);
_dinSetWidget = new DinnerSettingsWidget(dinSet, _stackWidget);
_sceneSetWidget = new SceneSettingsWidget(sceneSet, _stackWidget);
_visSetWidget = new VisualSettingsWidget(visSet, _stackWidget);
_stackWidget->addWidget(_dinSetWidget);
_stackWidget->addWidget(_sceneSetWidget);
_stackWidget->addWidget(_visSetWidget);
_stackWidget->setCurrentIndex(0);
QVBoxLayout* widgLay = new QVBoxLayout();
widgLay->addWidget(_listWidget);
widgLay->addWidget(_stackWidget);
QPushButton* okBtn = new QPushButton(tr("OK"), this);
okBtn->setDefault(true);
connect(okBtn, &QPushButton::clicked, this, &QDialog::accept);
QPushButton* cancelBtn = new QPushButton(tr("Cancel"), this);
connect(cancelBtn, &QPushButton::clicked, this, &QDialog::reject);
QPushButton* defBtn = new QPushButton(tr("Default"), this);
connect(defBtn, &QPushButton::clicked, this, &SettingsDialog::setDefault);
QHBoxLayout* butLay = new QHBoxLayout();
butLay->addWidget(defBtn);
butLay->addStretch(1);
butLay->addWidget(okBtn);
butLay->addWidget(cancelBtn);
QVBoxLayout* mainLay = new QVBoxLayout();
mainLay->addLayout(widgLay);
mainLay->addStretch(1);
mainLay->addLayout(butLay);
setLayout(mainLay);
setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
setWindowTitle(tr("Settings"));
}
DinnerSettings SettingsDialog::dinnerSettings() const
{
return _dinSetWidget->dinnerSettings();
}
SceneSettings SettingsDialog::sceneSettings() const
{
return _sceneSetWidget->sceneSettings();
}
VisualSettings SettingsDialog::visualSettings() const
{
return _visSetWidget->visualSettings();
}
void SettingsDialog::setDefault()
{
switch (_stackWidget->currentIndex())
{
case 0:
_dinSetWidget->setDefault();
break;
case 1:
_sceneSetWidget->setDefault();
break;
case 2:
_visSetWidget->setDefault();
break;
default:
break;
}
}
void SettingsDialog::createIcons()
{
QListWidgetItem *dinnerBtn = new QListWidgetItem(_listWidget);
dinnerBtn->setIcon(QIcon(":/resources/spaghetti.png"));
dinnerBtn->setText(tr("Dinner settings"));
dinnerBtn->setTextAlignment(Qt::AlignHCenter);
dinnerBtn->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled);
QListWidgetItem *sceneBtn = new QListWidgetItem(_listWidget);
sceneBtn->setIcon(QIcon(":/resources/geometry.png"));
sceneBtn->setText(tr("Scene settings"));
sceneBtn->setTextAlignment(Qt::AlignHCenter);
sceneBtn->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled);
QListWidgetItem *visBtn = new QListWidgetItem(_listWidget);
visBtn->setIcon(QIcon(":/resources/palette.png"));
visBtn->setText(tr("Visual settings"));
visBtn->setTextAlignment(Qt::AlignHCenter);
visBtn->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled);
}
void SettingsDialog::changePage(QListWidgetItem* current, QListWidgetItem* previous)
{
if (!current)
current = previous;
_stackWidget->setCurrentIndex(_listWidget->row(current));
}
| 29.488889 | 91 | 0.770912 | [
"geometry"
] |
a0ce9020a7d17d1f6b15b47225bc20c74bec0cde | 12,075 | cpp | C++ | map/booking_availability_filter.cpp | vicpopov/omim | 664b458998fb0f2405f68ae830c2798e027b2dcc | [
"Apache-2.0"
] | 4,879 | 2015-09-30T10:56:36.000Z | 2022-03-31T18:43:03.000Z | map/booking_availability_filter.cpp | mbrukman/omim | d22fe2b6e0beee697f096e931df97a64f9db9dc1 | [
"Apache-2.0"
] | 7,549 | 2015-09-30T10:52:53.000Z | 2022-03-31T22:04:22.000Z | map/booking_availability_filter.cpp | mbrukman/omim | d22fe2b6e0beee697f096e931df97a64f9db9dc1 | [
"Apache-2.0"
] | 1,493 | 2015-09-30T10:43:06.000Z | 2022-03-21T09:16:49.000Z | #include "map/booking_availability_filter.hpp"
#include "search/result.hpp"
#include "partners_api/booking_api.hpp"
#include "editor/editable_data_source.hpp"
#include "indexer/data_source.hpp"
#include "indexer/feature_decl.hpp"
#include "indexer/ftypes_sponsored.hpp"
#include "platform/platform.hpp"
#include "base/macros.hpp"
#include <algorithm>
#include <memory>
#include <utility>
#include <vector>
using namespace booking::filter;
namespace
{
auto constexpr kMaxCountInRequest = booking::RawApi::GetMaxHotelsInAvailabilityRequest();
template <typename T>
class HotelInfo
{
public:
explicit HotelInfo(T const & requestedVia) : m_mappedValue(requestedVia) {}
HotelInfo(std::string const & hotelId, availability::Cache::Info && info, T const & mappedValue)
: m_hotelId(hotelId), m_info(std::move(info)), m_mappedValue(mappedValue)
{
}
void SetHotelId(std::string const & hotelId) { m_hotelId = hotelId; }
void SetInfo(availability::Cache::Info && info) { m_info = std::move(info); }
std::string const & GetHotelId() const { return m_hotelId; }
availability::Cache::HotelStatus GetStatus() const { return m_info.m_status; }
std::optional<booking::Extras> const & GetExtras() const { return m_info.m_extras; }
std::optional<booking::Extras> & GetExtras() { return m_info.m_extras; }
T const & GetMappedValue() const { return m_mappedValue; }
T & GetMappedValue() { return m_mappedValue; }
private:
std::string m_hotelId;
availability::Cache::Info m_info;
T m_mappedValue;
};
template <typename T>
using HotelsMapping = std::vector<HotelInfo<T>>;
using HotelToResult = HotelInfo<search::Result>;
using HotelToFeatureId = HotelInfo<FeatureID>;
using HotelToResults = HotelsMapping<search::Result>;
using HotelToFeatureIds = HotelsMapping<FeatureID>;
bool IsConformToFilter(search::Result const & r)
{
return r.m_details.m_isSponsoredHotel && r.GetResultType() == search::Result::Type::Feature;
}
template <typename T>
void UpdateCache(HotelsMapping<T> const & hotelsMapping, booking::HotelsWithExtras const & hotels,
availability::Cache & cache)
{
using availability::Cache;
cache.ReserveAdditional(hotelsMapping.size());
for (auto & hotel : hotelsMapping)
{
if (hotel.GetStatus() != Cache::HotelStatus::Absent)
continue;
auto const it = hotels.find(hotel.GetHotelId());
if (it != hotels.cend())
cache.InsertAvailable(hotel.GetHotelId(), {it->second.m_price, it->second.m_currency});
else
cache.InsertUnavailable(hotel.GetHotelId());
}
}
template <typename T, typename PassedInserter, typename FilteredOutInserter>
void FillResults(HotelsMapping<T> && hotelsMapping, booking::HotelsWithExtras && hotels,
availability::Cache & cache, PassedInserter const & passedInserter,
FilteredOutInserter const & filteredOutInserter)
{
using availability::Cache;
for (auto & hotel : hotelsMapping)
{
switch (hotel.GetStatus())
{
case Cache::HotelStatus::Unavailable:
{
filteredOutInserter(std::move(hotel.GetMappedValue()));
continue;
}
case Cache::HotelStatus::Available:
{
passedInserter(std::move(hotel.GetMappedValue()), std::move(*hotel.GetExtras()));
continue;
}
case Cache::HotelStatus::NotReady:
{
auto info = cache.Get(hotel.GetHotelId());
if (info.m_status == Cache::HotelStatus::Available)
passedInserter(std::move(hotel.GetMappedValue()), std::move(*info.m_extras));
else if (info.m_status == Cache::HotelStatus::Unavailable)
filteredOutInserter(std::move(hotel.GetMappedValue()));
continue;
}
case Cache::HotelStatus::Absent:
{
auto const it = hotels.find(hotel.GetHotelId());
if (it != hotels.cend())
passedInserter(std::move(hotel.GetMappedValue()), std::move(it->second));
else
filteredOutInserter(std::move(hotel.GetMappedValue()));
continue;
}
}
}
}
void FillResults(HotelToResults && hotelToResults, booking::HotelsWithExtras && hotels,
availability::Cache & cache, ResultInternal<search::Results> & results)
{
auto const passedInserter = [&results](search::Result && passed, booking::Extras && extra)
{
results.m_passedFilter.AddResultNoChecks(std::move(passed));
results.m_extras.emplace_back(std::move(extra));
};
auto const filteredOutInserter = [&results](search::Result && filteredOut)
{
results.m_filteredOut.AddResultNoChecks(std::move(filteredOut));
};
FillResults(std::move(hotelToResults), std::move(hotels), cache, passedInserter, filteredOutInserter);
}
void FillResults(HotelToFeatureIds && hotelToFeatureIds, booking::HotelsWithExtras && hotels,
availability::Cache & cache, ResultInternal<std::vector<FeatureID>> & results)
{
auto const passedInserter = [&results](FeatureID && passed, booking::Extras && extra)
{
results.m_passedFilter.emplace_back(std::move(passed));
results.m_extras.emplace_back(std::move(extra));
};
auto const filteredOutInserter = [&results](FeatureID && filteredOut)
{
results.m_filteredOut.emplace_back(std::move(filteredOut));
};
FillResults(std::move(hotelToFeatureIds), std::move(hotels), cache, passedInserter, filteredOutInserter);
}
void PrepareData(DataSource const & dataSource, search::Results const & results,
HotelToResults & hotelToResults, availability::Cache & cache,
booking::AvailabilityParams & p)
{
std::vector<FeatureID> features;
for (auto const & r : results)
{
if (!IsConformToFilter(r))
continue;
features.push_back(r.GetFeatureID());
hotelToResults.emplace_back(r);
}
std::sort(features.begin(), features.end());
MwmSet::MwmId mwmId;
std::unique_ptr<FeaturesLoaderGuard> guard;
for (auto const & featureId : features)
{
if (mwmId != featureId.m_mwmId)
{
guard = std::make_unique<FeaturesLoaderGuard>(dataSource, featureId.m_mwmId);
mwmId = featureId.m_mwmId;
}
auto it = std::find_if(hotelToResults.begin(), hotelToResults.end(),
[&featureId](HotelToResult const & item)
{
return item.GetMappedValue().GetFeatureID() == featureId;
});
ASSERT(it != hotelToResults.cend(), ());
auto ft = guard->GetFeatureByIndex(featureId.m_index);
if (!ft)
{
hotelToResults.erase(it);
LOG(LERROR, ("Feature can't be loaded:", featureId));
continue;
}
if (!ftypes::IsBookingChecker::Instance()(*ft))
continue;
auto hotelId = ft->GetMetadata(feature::Metadata::FMD_SPONSORED_ID);
auto info = cache.Get(hotelId);
auto const status = info.m_status;
it->SetHotelId(hotelId);
it->SetInfo(std::move(info));
if (status != availability::Cache::HotelStatus::Absent)
continue;
cache.InsertNotReady(hotelId);
p.m_hotelIds.push_back(std::move(hotelId));
}
}
void PrepareData(DataSource const & dataSource, std::vector<FeatureID> const & featureIds,
HotelToFeatureIds & hotelToFeatures, availability::Cache & cache,
booking::AvailabilityParams & p)
{
ASSERT(std::is_sorted(featureIds.begin(), featureIds.end()), ());
MwmSet::MwmId mwmId;
std::unique_ptr<FeaturesLoaderGuard> guard;
for (auto const & featureId : featureIds)
{
if (mwmId != featureId.m_mwmId)
{
guard = std::make_unique<FeaturesLoaderGuard>(dataSource, featureId.m_mwmId);
mwmId = featureId.m_mwmId;
}
auto ft = guard->GetFeatureByIndex(featureId.m_index);
if (!ft)
{
LOG(LERROR, ("Feature can't be loaded:", featureId));
continue;
}
if (!ftypes::IsBookingChecker::Instance()(*ft))
continue;
auto const hotelId = ft->GetMetadata(feature::Metadata::FMD_SPONSORED_ID);
auto info = cache.Get(hotelId);
auto const status = info.m_status;
hotelToFeatures.emplace_back(hotelId, std::move(info), featureId);
if (status != availability::Cache::HotelStatus::Absent)
continue;
cache.InsertNotReady(hotelId);
p.m_hotelIds.push_back(std::move(hotelId));
}
}
} // namespace
namespace booking
{
namespace filter
{
AvailabilityFilter::AvailabilityFilter(Delegate const & d) : FilterBase(d) {}
void AvailabilityFilter::ApplyFilter(search::Results const & results,
ParamsInternal const & filterParams)
{
ApplyFilterInternal<search::Result>(results, filterParams);
}
void AvailabilityFilter::ApplyFilter(std::vector<FeatureID> const & featureIds,
ParamsRawInternal const & filterParams)
{
ASSERT(std::is_sorted(featureIds.cbegin(), featureIds.cend()), ());
ApplyFilterInternal<FeatureID>(featureIds, filterParams);
}
void AvailabilityFilter::UpdateParams(ParamsBase const & apiParams)
{
if (m_apiParams.Equals(apiParams))
return;
m_apiParams.Set(apiParams);
m_cache = std::make_shared<availability::Cache>();
}
template <typename SourceValue, typename Source, typename Parameters>
void AvailabilityFilter::ApplyFilterInternal(Source const & source, Parameters const & filterParams)
{
ASSERT(filterParams.m_apiParams, ());
auto const & cb = filterParams.m_callback;
UpdateParams(*filterParams.m_apiParams);
m_apiParams.m_hotelIds.clear();
HotelsMapping<SourceValue> hotelsToSourceValue;
PrepareData(GetDelegate().GetDataSource(), source, hotelsToSourceValue, *m_cache, m_apiParams);
UNUSED_VALUE(kMaxCountInRequest);
ASSERT_LESS_OR_EQUAL(m_apiParams.m_hotelIds.size(), kMaxCountInRequest, ());
if (m_apiParams.m_hotelIds.empty())
{
booking::filter::ResultInternal<Source> result;
FillResults(std::move(hotelsToSourceValue), {} /* hotelIds */, *m_cache, result);
cb(std::move(result));
return;
}
auto const apiCallback =
[cb, cache = m_cache, hotelToValue = std::move(hotelsToSourceValue)] (booking::HotelsWithExtras hotels) mutable
{
GetPlatform().RunTask(
Platform::Thread::File,
[cb, cache, hotelToValue = std::move(hotelToValue), hotels = std::move(hotels)]() mutable
{
UpdateCache(hotelToValue, hotels, *cache);
booking::filter::ResultInternal<Source> updatedResult;
FillResults(std::move(hotelToValue), std::move(hotels), *cache, updatedResult);
cb(std::move(updatedResult));
});
};
GetDelegate().GetApi().GetHotelAvailability(m_apiParams, apiCallback);
m_cache->RemoveOutdated();
}
void AvailabilityFilter::GetFeaturesFromCache(search::Results const & results,
std::vector<FeatureID> & sortedResults,
std::vector<Extras> & extras,
std::vector<FeatureID> & filteredOut)
{
sortedResults.clear();
std::vector<FeatureID> features;
for (auto const & r : results)
{
if (!IsConformToFilter(r))
continue;
features.push_back(r.GetFeatureID());
}
std::sort(features.begin(), features.end());
MwmSet::MwmId mwmId;
std::unique_ptr<FeaturesLoaderGuard> guard;
for (auto const & featureId : features)
{
if (mwmId != featureId.m_mwmId)
{
guard = std::make_unique<FeaturesLoaderGuard>(GetDelegate().GetDataSource(), featureId.m_mwmId);
mwmId = featureId.m_mwmId;
}
auto ft = guard->GetFeatureByIndex(featureId.m_index);
if (!ft)
{
LOG(LERROR, ("Feature can't be loaded:", featureId));
continue;
}
auto const & hotelId = ft->GetMetadata(feature::Metadata::FMD_SPONSORED_ID);
auto info = m_cache->Get(hotelId);
if (info.m_status == availability::Cache::HotelStatus::Available)
{
sortedResults.push_back(featureId);
extras.emplace_back(std::move(*info.m_extras));
}
else if (info.m_status == availability::Cache::HotelStatus::Unavailable)
{
filteredOut.push_back(featureId);
}
}
}
} // namespace booking
} // namespace filter
| 30.492424 | 115 | 0.679337 | [
"vector"
] |
a0d654c139fe9f550d8d2ff67cc7918825fe896e | 5,753 | cpp | C++ | SugarboxBenchmarks/benchmark.cpp | Tom1975/CPCCore | 8a898d80533d5f955898893fbe09be024a64e861 | [
"MIT"
] | 5 | 2020-01-24T17:48:40.000Z | 2021-01-29T10:48:31.000Z | SugarboxBenchmarks/benchmark.cpp | Tom1975/CPCCore | 8a898d80533d5f955898893fbe09be024a64e861 | [
"MIT"
] | null | null | null | SugarboxBenchmarks/benchmark.cpp | Tom1975/CPCCore | 8a898d80533d5f955898893fbe09be024a64e861 | [
"MIT"
] | 1 | 2021-09-16T08:45:22.000Z | 2021-09-16T08:45:22.000Z | #include "../benchmark/include/benchmark/benchmark.h"
#include <set>
#include <vector>
#include "TestUtils.h"
void BenchmarkOpcode (Motherboard *motherboard_emulation, unsigned char opcode)
{
motherboard_emulation->SetPlus(true);
motherboard_emulation->OnOff();
motherboard_emulation->GetMem()->InitMemory();
motherboard_emulation->GetMem()->SetRam(1);
motherboard_emulation->GetCRTC()->DefinirTypeCRTC(CRTC::AMS40226);
motherboard_emulation->GetVGA()->SetPAL(true);
// Set Memory (0x04 = INC B)
for (int i = 0; i < 4; i++)
{
memset(motherboard_emulation->GetMem()->GetRamRead(i), opcode, sizeof(Memory::RamBank));
}
// Empty cartridge
for (int i = 0; i < 32; i++)
{
unsigned char* rom = motherboard_emulation->GetCartridge(i);
memset(rom, opcode, sizeof(Memory::RamBank));
}
motherboard_emulation->GetPSG()->Reset();
motherboard_emulation->GetSig()->Reset();
motherboard_emulation->InitStartOptimizedPlus();
motherboard_emulation->OnOff();
}
// Main Sugarbox benchmark
static void BM_z80full(benchmark::State &state) {
for (auto _ : state) {
InitBinary("6128", ".\\TestConf.ini", ".\\res\\z80\\z80full.bin", 0x807A, 0x8065);
}
}
BENCHMARK(BM_z80full)->Unit(benchmark::kMillisecond);
static void BM_NOP(benchmark::State &state)
{
SoundMixer sound_mixer;
Motherboard *motherboard_emulation;
CDisplay display;
KeyboardForTest keyboard;
#ifdef _DEBUG
display.Init(true);
display.Show(true);
#else
display.Init(false);
display.Show(false);
#endif
motherboard_emulation = new Motherboard(&sound_mixer, &keyboard);
motherboard_emulation->InitMotherbard(nullptr, nullptr, &display, nullptr, nullptr, nullptr);
BenchmarkOpcode(motherboard_emulation, 0);
for (auto _ : state)
{
motherboard_emulation->StartOptimizedPlus<false, false, false>(4000 * 1000 * 20);
//motherboard_emulation->Start(0, 4000 * 50 * 20);
}
delete motherboard_emulation;
}
BENCHMARK(BM_NOP)->Unit(benchmark::kMillisecond);
static void BM_INC_B(benchmark::State &state)
{
SoundMixer sound_mixer;
Motherboard *motherboard_emulation;
CDisplay display;
KeyboardForTest keyboard;
#ifdef _DEBUG
display.Init(true);
display.Show(true);
#else
display.Init(false);
display.Show(false);
#endif
motherboard_emulation = new Motherboard(&sound_mixer, &keyboard);
motherboard_emulation->InitMotherbard(nullptr, nullptr, &display, nullptr, nullptr, nullptr);
BenchmarkOpcode(motherboard_emulation, 0x4);
for (auto _ : state)
{
//motherboard_emulation->Start(0, 4000 * 50 * 20);
motherboard_emulation->StartOptimizedPlus<false, false, false>(4000 * 50 * 20);
}
delete motherboard_emulation;
}
BENCHMARK(BM_INC_B)->Unit(benchmark::kMillisecond);
static void BM_INC_BC(benchmark::State &state)
{
SoundMixer sound_mixer;
Motherboard *motherboard_emulation;
CDisplay display;
KeyboardForTest keyboard;
#ifdef _DEBUG
display.Init(true);
display.Show(true);
#else
display.Init(false);
display.Show(false);
#endif
motherboard_emulation = new Motherboard(&sound_mixer, &keyboard);
motherboard_emulation->InitMotherbard(nullptr, nullptr, &display, nullptr, nullptr, nullptr);
BenchmarkOpcode(motherboard_emulation, 0x3);
for (auto _ : state)
{
motherboard_emulation->StartOptimizedPlus<false, false, false>( 4000 * 50 * 20);
}
delete motherboard_emulation;
}
BENCHMARK(BM_INC_BC)->Unit(benchmark::kMillisecond);
static void BM_RLCA(benchmark::State &state)
{
SoundMixer sound_mixer;
Motherboard *motherboard_emulation;
CDisplay display;
KeyboardForTest keyboard;
#ifdef _DEBUG
display.Init(true);
display.Show(true);
#else
display.Init(false);
display.Show(false);
#endif
motherboard_emulation = new Motherboard(&sound_mixer, &keyboard);
motherboard_emulation->InitMotherbard(nullptr, nullptr, &display, nullptr, nullptr, nullptr);
BenchmarkOpcode(motherboard_emulation, 0x7);
for (auto _ : state)
{
motherboard_emulation->StartOptimizedPlus<false, false, false>(4000 * 50 * 20);
}
delete motherboard_emulation;
}
BENCHMARK(BM_RLCA)->Unit(benchmark::kMillisecond);
// Eerie forest GX4000 benchmark
static void BM_EerieForest(benchmark::State &state) {
TestDump test_dump;
CommandList cmd_list;
cmd_list.AddCommand(new CommandRunCycles(15000));
for (auto _ : state) {
test_dump.TestCardridge("GX4000", ".\\TestConf.ini", ".\\res\\CART\\Eerie_Forest_(Logon_System_2017).cpr", &cmd_list);
}
}
BENCHMARK(BM_EerieForest)->Unit(benchmark::kMillisecond);
// Mod 2 PLUS benchmark
static void BM_Mode2plus(benchmark::State &state) {
TestDump test_dump;
CommandList cmd_list;
cmd_list.AddCommand(new CommandRunCycles(100));
cmd_list.AddCommand(new CommandKeyboard("mode 2"));
cmd_list.AddCommand(new CommandRunCycles(80));
cmd_list.AddCommand(new CommandKeyboard("\r"));
cmd_list.AddCommand(new CommandRunCycles(15000));
for (auto _ : state) {
test_dump.TestCardridge("GX4000", ".\\TestConf.ini", ".\\res\\CART\\AmstradPlus.f4 (Parados 1.0) (unofficial).cpr", &cmd_list);
}
}
BENCHMARK(BM_Mode2plus)->Unit(benchmark::kMillisecond);
// Eerie forest GX4000 benchmark
static void BM_CRTC3(benchmark::State &state) {
TestDump test_dump;
CommandList cmd_list;
cmd_list.AddCommand(new CommandRunCycles(15000));
for (auto _ : state) {
test_dump.TestCardridge("GX4000", ".\\TestConf.ini", ".\\res\\CART\\crtc3_projo.cpr", &cmd_list);
}
}
BENCHMARK(BM_CRTC3)->Unit(benchmark::kMillisecond);
BENCHMARK_MAIN();
| 26.883178 | 133 | 0.705197 | [
"vector"
] |
a0e506016a33ec2a9fd9ffcc98dd39919e5b64d8 | 3,252 | cc | C++ | HiggsAnalysis/Skimming/src/HiggsToZZ4LeptonsSkim.cc | SWuchterl/cmssw | 769b4a7ef81796579af7d626da6039dfa0347b8e | [
"Apache-2.0"
] | 6 | 2017-09-08T14:12:56.000Z | 2022-03-09T23:57:01.000Z | HiggsAnalysis/Skimming/src/HiggsToZZ4LeptonsSkim.cc | SWuchterl/cmssw | 769b4a7ef81796579af7d626da6039dfa0347b8e | [
"Apache-2.0"
] | 545 | 2017-09-19T17:10:19.000Z | 2022-03-07T16:55:27.000Z | HiggsAnalysis/Skimming/src/HiggsToZZ4LeptonsSkim.cc | SWuchterl/cmssw | 769b4a7ef81796579af7d626da6039dfa0347b8e | [
"Apache-2.0"
] | 14 | 2017-10-04T09:47:21.000Z | 2019-10-23T18:04:45.000Z |
/* \class HiggsTo4LeptonsSkim
*
* Consult header file for description
*
* author: Dominique Fortin - UC Riverside
*
*/
// system include files
#include <HiggsAnalysis/Skimming/interface/HiggsToZZ4LeptonsSkim.h>
// User include files
#include <FWCore/ParameterSet/interface/ParameterSet.h>
// Muons:
#include <DataFormats/TrackReco/interface/Track.h>
// Electrons
#include "DataFormats/EgammaCandidates/interface/GsfElectron.h"
// C++
#include <iostream>
#include <vector>
using namespace std;
using namespace edm;
using namespace reco;
// Constructor
HiggsToZZ4LeptonsSkim::HiggsToZZ4LeptonsSkim(const edm::ParameterSet& pset) {
// Local Debug flag
debug = pset.getParameter<bool>("DebugHiggsToZZ4LeptonsSkim");
// Reconstructed objects
theGLBMuonToken = consumes<reco::TrackCollection>(pset.getParameter<edm::InputTag>("GlobalMuonCollectionLabel"));
theGsfEToken = consumes<reco::GsfElectronCollection>(pset.getParameter<edm::InputTag>("ElectronCollectionLabel"));
// Minimum Pt for leptons for skimming
stiffMinPt = pset.getParameter<double>("stiffMinimumPt");
softMinPt = pset.getParameter<double>("softMinimumPt");
nStiffLeptonMin = pset.getParameter<int>("nStiffLeptonMinimum");
nLeptonMin = pset.getParameter<int>("nLeptonMinimum");
nEvents = 0;
nSelectedEvents = 0;
}
// Destructor
HiggsToZZ4LeptonsSkim::~HiggsToZZ4LeptonsSkim() {
edm::LogVerbatim("HiggsToZZ4LeptonsSkim")
<< " Number_events_read " << nEvents << " Number_events_kept " << nSelectedEvents << " Efficiency "
<< ((double)nSelectedEvents) / ((double)nEvents + 0.01) << std::endl;
}
// Filter event
bool HiggsToZZ4LeptonsSkim::filter(edm::Event& event, const edm::EventSetup& setup) {
nEvents++;
using reco::TrackCollection;
bool keepEvent = false;
int nStiffLeptons = 0;
int nLeptons = 0;
// First look at muons:
// Get the muon track collection from the event
edm::Handle<reco::TrackCollection> muTracks;
event.getByToken(theGLBMuonToken, muTracks);
if (muTracks.isValid()) {
reco::TrackCollection::const_iterator muons;
// Loop over muon collections and count how many muons there are,
// and how many are above threshold
for (muons = muTracks->begin(); muons != muTracks->end(); ++muons) {
if (muons->pt() > stiffMinPt)
nStiffLeptons++;
if (muons->pt() > softMinPt)
nLeptons++;
}
}
// Now look at electrons:
// Get the electron track collection from the event
edm::Handle<reco::GsfElectronCollection> pTracks;
event.getByToken(theGsfEToken, pTracks);
if (pTracks.isValid()) {
const reco::GsfElectronCollection* eTracks = pTracks.product();
reco::GsfElectronCollection::const_iterator electrons;
// Loop over electron collections and count how many muons there are,
// and how many are above threshold
for (electrons = eTracks->begin(); electrons != eTracks->end(); ++electrons) {
float pt_e = electrons->pt();
if (pt_e > stiffMinPt)
nStiffLeptons++;
if (pt_e > softMinPt)
nLeptons++;
}
}
// Make decision:
if (nStiffLeptons >= nStiffLeptonMin && nLeptons >= nLeptonMin)
keepEvent = true;
if (keepEvent)
nSelectedEvents++;
return keepEvent;
}
| 28.034483 | 116 | 0.705412 | [
"vector"
] |
a0e5d217bb920f48b6459527e6fd2b7263acf8e1 | 8,895 | cpp | C++ | Serverko/Srvk/Srvk/sqlmanager/sqlhelper.cpp | qframework/QFramework | 9cef9261553e4486b535e07fdd16d51acc9ecd4a | [
"Apache-2.0"
] | 2 | 2017-05-11T03:42:08.000Z | 2022-01-11T02:26:50.000Z | Serverko/Srvk/Srvk/sqlmanager/sqlhelper.cpp | qframework/QFramework | 9cef9261553e4486b535e07fdd16d51acc9ecd4a | [
"Apache-2.0"
] | null | null | null | Serverko/Srvk/Srvk/sqlmanager/sqlhelper.cpp | qframework/QFramework | 9cef9261553e4486b535e07fdd16d51acc9ecd4a | [
"Apache-2.0"
] | null | null | null | #include "SQLHelper.h"
//#include "../servermanager/HandlerSQLL.h"
#include <stdio.h>
#include <stdarg.h>
ServerOutCallback SQLHelper::mpFunc = NULL;
bool SQLHelper::get(std::vector<std::string>& retVals,
const char* pTable,
const char* pField,
const char* pFilter,
const char* pFilterVal)
{
if (pTable == NULL || pField == NULL)
{
return false;
}
// SELECT pField FROM pTable WHERE pFilter = pFilterVal;
//HandlerSQLL hsql;
std::string sqlstr;
sqlstr = "SELECT ";
sqlstr += pField;
sqlstr += " FROM ";
sqlstr += pTable;
if (pFilter && pFilterVal)
{
sqlstr +=" WHERE ";
sqlstr += pFilter;
sqlstr +=" = '";
sqlstr += pFilterVal;
sqlstr +="';";
}
else
{
sqlstr += ";";
}
return false; //hsql.execSQL( sqlstr, &retVals );;
}
bool SQLHelper::get(std::string& retVal,
const char* pTable,
const char* pField,
const char* pFilter,
const char* pFilterVal)
{
if (pTable == NULL || pField == NULL)
{
return false;
}
// SELECT pField FROM pTable WHERE pFilter = pFilterVal;
std::vector<std::string> in;
//HandlerSQLL hsql;
std::string sqlstr;
sqlstr = "SELECT ";
sqlstr += pField;
sqlstr += " FROM ";
sqlstr += pTable;
if (pFilter && pFilterVal)
{
sqlstr +=" WHERE ";
sqlstr += pFilter;
sqlstr +=" = '";
sqlstr += pFilterVal;
sqlstr +="';";
}
else
{
sqlstr += ";";
}
bool res = false;//hsql.execSQL( sqlstr, &in );
if (res && in.size() )
{
retVal = in[0];
}
else
{
trace("SQLError: %s", sqlstr.c_str() );
if (in.size() )
{
trace("SQLError: %s", in[0].c_str() );
}
return false;
}
return true;
}
bool SQLHelper::update(const char* pTable,
const std::string& data,
const char* pFilter,
const char* pFilterVal)
{
std::string sqlstr;
sqlstr = "UPDATE " + std::string(pTable);
sqlstr += " SET ";
sqlstr += data;
if (pFilter && pFilterVal)
{
sqlstr +=" WHERE ";
sqlstr += pFilter;
sqlstr +=" = '";
sqlstr += pFilterVal;
sqlstr +="';";
}
else
{
sqlstr += ";";
}
//HandlerSQLL hsql;
std::vector<std::string> res;
bool rez = false;//hsql.execSQL( sqlstr, &res );
// TODO fix - there is no error
if (rez == false || (res.size() && res[0] == "ERROR") )
{
trace("SQLError: %s", sqlstr.c_str() );
if (res.size() )
{
trace("SQLError: %s", res[0].c_str() );
}
return false;
}
else
{
return true;
}
}
bool SQLHelper::insert(const char* pTable,
const std::string& data)
{
std::string sqlstr;
sqlstr = "INSERT INTO " + std::string(pTable);
sqlstr += " VALUES (";
sqlstr += data;
sqlstr += ");";
//HandlerSQLL hsql;
std::vector<std::string> res;
bool rez = false;//hsql.execSQL( sqlstr, &res );
if (rez == false || (res.size() && res[0] == "ERROR") )
{
// TRACE OUT TO CONSOLE
trace("SQLError: %s", sqlstr.c_str() );
if (res.size() )
{
trace("SQLError: %s", res[0].c_str() );
}
return false;
}
else
{
return true;
}
}
/*
void SQLHelper::format(bool newvalue, std::string& out, const char* pVal, const tdBBox& bbox)
{
if (newvalue)
{
out += " '";
}
else
{
out += std::string(pVal);
out += " = '";
}
char buff[512];
sprintf(buff, "%f, %f, %f, %f, %f, %f",
bbox.mMin.mX, bbox.mMin.mY, bbox.mMin.mZ,
bbox.mMax.mX, bbox.mMax.mY, bbox.mMax.mZ);
out += buff;
out += "' ";
}
*/
/*
void SQLHelper::format(bool newvalue, std::string& out, const char* pVal, const tdVector& pos)
{
if (newvalue)
{
out += " '";
}
else
{
out += std::string(pVal);
out += " = '";
}
char buff[512];
sprintf(buff, "%f, %f, %f",
pos.mX, pos.mY, pos.mZ);
out += buff;
out += "' ";
}
*/
void SQLHelper::format(bool newvalue,std::string& out, const char* pVal, long val)
{
if (newvalue)
{
out += " '";
}
else
{
out += std::string(pVal);
out += " = '";
}
char buff[512];
sprintf(buff, "%d",val);
out += buff;
out += "' ";
}
void SQLHelper::format(bool newvalue,std::string& out, const char* pVal, float val)
{
if (newvalue)
{
out += " '";
}
else
{
out += std::string(pVal);
out += " = '";
}
char buff[512];
sprintf(buff, "%f",val);
out += buff;
out += "' ";
}
void SQLHelper::format(bool newvalue,std::string& out, const char* pVal, const std::string& val)
{
if (newvalue)
{
out += " '";
}
else
{
out += std::string(pVal);
out += " = '";
}
out += val;
out += "' ";
}
void SQLHelper::format(bool newvalue,std::string& out, const char* pVal, long* vals, int num)
{
if (newvalue)
{
out += " '";
}
else
{
out += std::string(pVal);
out += " = '";
}
char buff[16];
for (int a=0; a<num; a++)
{
sprintf(buff, "%d",vals[a]);
out += buff;
if ( a < num-1)
{
out += ",";
}
}
out += "' ";
}
SQLDataTkn SQLHelper::getToken(const std::string& str, unsigned int& pos)
{
int a = (int)str.find('\t');
if (a < 1 || a >= (int)str.size())
{
return SQL_TKN_UNKN;
}
pos = a;
std::string strtkn;
strtkn = str.substr( 0 , a);
if (strtkn == "ID")return SQL_TKN_ID;
if (strtkn == "SIZE")return SQL_TKN_SIZE;
if (strtkn == "MAXIDLETIME")return SQL_TKN_MAXIDLETIME;
if (strtkn == "NAME")return SQL_TKN_NAME;
if (strtkn == "UPDATETIME")return SQL_TKN_UPDATETIME;
if (strtkn == "MESSAGE")return SQL_TKN_MESSAGE;
if (strtkn == "FLAGS")return SQL_TKN_FLAGS;
if (strtkn == "LOGIN")return SQL_TKN_LOGIN;
if (strtkn == "POSITION") return SQL_TKN_POSITION;
if (strtkn == "OBJECTS") return SQL_TKN_OBJECTS;
return SQL_TKN_UNKN;
}
/*
void SQLHelper::parse(const std::string& str, unsigned int pos, tdBBox& value)
{
value.mMin.mX = getFloat( str, pos);
value.mMin.mY = getFloat( str, pos);
value.mMin.mZ = getFloat( str, pos);
value.mMax.mX = getFloat( str, pos);
value.mMax.mY = getFloat( str, pos);
value.mMax.mZ = getFloat( str, pos);
}
*/
/*
void SQLHelper::parse(const std::string& str, unsigned int pos, tdVector& value)
{
value.mX = getFloat( str, pos);
value.mY = getFloat( str, pos);
value.mZ = getFloat( str, pos);
}
*/
void SQLHelper::parse(const std::string& str, unsigned int pos, long& value)
{
value = getLong( str, pos);
}
void SQLHelper::parse(const std::string& str, unsigned int pos, float& value)
{
value = getFloat( str, pos);
}
void SQLHelper::parse(const std::string& str, unsigned int pos, std::string& value)
{
unsigned int len = (int)str.length();
while ( str[pos] == '\t')
{
pos++;
}
std::string tmp = str.substr( pos , len - pos);
value = tmp;
}
void SQLHelper::parse(const std::string& str, unsigned int pos, long* pVal, unsigned int len)
{
for (unsigned int a=0; a< len; a++)
{
pVal[a] = getLong( str, pos);
}
}
float SQLHelper::getFloat(const std::string& in, unsigned int& pos)
{
unsigned int start = pos;
while ( in[pos] != ',' && in[pos] != ';' && pos < in.length() )
{
pos ++;
}
std::string ret = in.substr( start, pos - start);
pos ++;
return (float)atof( ret.c_str() );
}
long SQLHelper::getLong(const std::string& in, unsigned int& pos)
{
unsigned int start = pos;
while ( in[pos] != ',' && in[pos] != ';' && pos < in.length() )
{
pos ++;
}
std::string ret = in.substr( start, pos - start);
return atol( ret.c_str() );
}
int SQLHelper::getToken(const std::string& str, unsigned int& pos,
const std::vector<WorldDOMVar*>& vars)
{
int a = (int)str.find('\t');
if (a < 1 || a >= (int)str.size() )
{
return SQL_TKN_UNKN;
}
pos = a;
std::string strtkn;
strtkn = str.substr( 0 , a);
for (unsigned int b=0; b < vars.size() ; b++)
{
//if (vars[b] && vars[b]->equalsSQLname( str.c_str(), pos ) )
{
return b;
}
}
return -1;
}
void SQLHelper::setOutFunc(ServerOutCallback pFunc)
{
mpFunc = pFunc;
}
// TODO - move trace in separate facility
void SQLHelper::trace(const char* pFormat, ... )
{
static char tracebuff[16384];
va_list list;
va_start(list, pFormat);
int len = vsprintf( tracebuff ,pFormat,list); // two for CRLF and one for 0
va_end(list);
if (len && mpFunc)
{
mpFunc( tracebuff );
}
}
// postaviti osnovne resourse
// povecavati kolicinu osnovnih resoursa
// postavljanje na mapi raznih podrucja za resourse.....
// hexagone koriste - gradjevine - reljef - likovi idu - kontinuirano
// napraviti XML format reljefa
// postavljanje prve jedinice
// za sada sve hardcoded -razmisliti za poslije da to dizu "skripte"..
| 20.261959 | 96 | 0.555818 | [
"vector"
] |
a0e7cc3f3b708611b3a1d21902719db3b9431573 | 8,928 | cpp | C++ | Chapter4/GL01_Camera/src/main.cpp | adoug/3D-Graphics-Rendering-Cookbook | dabffed670b8be5a619f0f62b10e0cc8ccdd5a36 | [
"MIT"
] | 399 | 2021-06-03T02:42:20.000Z | 2022-03-27T23:23:15.000Z | Chapter4/GL01_Camera/src/main.cpp | adoug/3D-Graphics-Rendering-Cookbook | dabffed670b8be5a619f0f62b10e0cc8ccdd5a36 | [
"MIT"
] | 7 | 2021-07-13T02:36:01.000Z | 2022-03-26T03:46:37.000Z | Chapter4/GL01_Camera/src/main.cpp | adoug/3D-Graphics-Rendering-Cookbook | dabffed670b8be5a619f0f62b10e0cc8ccdd5a36 | [
"MIT"
] | 53 | 2021-06-02T20:02:24.000Z | 2022-03-29T15:36:30.000Z | #include <stdio.h>
#include <stdlib.h>
#include <vector>
#include "shared/glFramework/GLShader.h"
#include "shared/UtilsMath.h"
#include "shared/Bitmap.h"
#include "shared/debug.h"
#include "shared/UtilsCubemap.h"
#include "shared/Camera.h"
#include <glad/gl.h>
#include <GLFW/glfw3.h>
#include <glm/glm.hpp>
#include <glm/ext.hpp>
#include <assimp/scene.h>
#include <assimp/postprocess.h>
#include <assimp/cimport.h>
#include <assimp/version.h>
#define STB_IMAGE_IMPLEMENTATION
#include <stb/stb_image.h>
using glm::mat4;
using glm::vec2;
using glm::vec3;
using glm::vec4;
using glm::ivec2;
struct PerFrameData
{
mat4 view;
mat4 proj;
vec4 cameraPos;
};
struct MouseState
{
glm::vec2 pos = glm::vec2(0.0f);
bool pressedLeft = false;
} mouseState;
CameraPositioner_FirstPerson positioner( vec3(0.0f), vec3(0.0f, 0.0f, -1.0f), vec3(0.0f, 1.0f, 0.0f));
//positioner.setPosition(vec3(0.0f, 0.0f, 0.0f));
Camera camera(positioner);
int main(void)
{
glfwSetErrorCallback(
[](int error, const char* description)
{
fprintf(stderr, "Error: %s\n", description);
}
);
if (!glfwInit())
exit(EXIT_FAILURE);
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 6);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, GLFW_TRUE);
GLFWwindow* window = glfwCreateWindow(1024, 768, "Simple example", nullptr, nullptr);
if (!window)
{
glfwTerminate();
exit(EXIT_FAILURE);
}
glfwMakeContextCurrent(window);
gladLoadGL(glfwGetProcAddress);
glfwSwapInterval(1);
initDebug();
GLShader shdModelVertex("data/shaders/chapter04/GL01_duck.vert");
GLShader shdModelFragment("data/shaders/chapter04/GL01_duck.frag");
GLProgram progModel(shdModelVertex, shdModelFragment);
GLShader shdCubeVertex("data/shaders/chapter04/GL01_cube.vert");
GLShader shdCubeFragment("data/shaders/chapter04/GL01_cube.frag");
GLProgram progCube(shdCubeVertex, shdCubeFragment);
const GLsizeiptr kUniformBufferSize = sizeof(PerFrameData);
GLuint perFrameDataBuffer;
glCreateBuffers(1, &perFrameDataBuffer);
glNamedBufferStorage(perFrameDataBuffer, kUniformBufferSize, nullptr, GL_DYNAMIC_STORAGE_BIT);
glBindBufferRange(GL_UNIFORM_BUFFER, 0, perFrameDataBuffer, 0, kUniformBufferSize);
glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
glEnable(GL_DEPTH_TEST);
const aiScene* scene = aiImportFile("data/rubber_duck/scene.gltf", aiProcess_Triangulate);
if (!scene || !scene->HasMeshes())
{
printf("Unable to load data/rubber_duck/scene.gltf\n");
exit(255);
}
struct VertexData
{
vec3 pos;
vec3 n;
vec2 tc;
};
const aiMesh* mesh = scene->mMeshes[0];
std::vector<VertexData> vertices;
for (unsigned i = 0; i != mesh->mNumVertices; i++)
{
const aiVector3D v = mesh->mVertices[i];
const aiVector3D n = mesh->mNormals[i];
const aiVector3D t = mesh->mTextureCoords[0][i];
vertices.push_back({ .pos = vec3(v.x, v.z, v.y), .n = vec3(n.x, n.y, n.z), .tc = vec2(t.x, t.y) });
}
std::vector<unsigned int> indices;
for (unsigned i = 0; i != mesh->mNumFaces; i++)
{
for (unsigned j = 0; j != 3; j++)
indices.push_back(mesh->mFaces[i].mIndices[j]);
}
aiReleaseImport(scene);
const size_t kSizeIndices = sizeof(unsigned int) * indices.size();
const size_t kSizeVertices = sizeof(VertexData) * vertices.size();
// indices
GLuint dataIndices;
glCreateBuffers(1, &dataIndices);
glNamedBufferStorage(dataIndices, kSizeIndices, indices.data(), 0);
GLuint vao;
glCreateVertexArrays(1, &vao);
glBindVertexArray(vao);
glVertexArrayElementBuffer(vao, dataIndices);
// vertices
GLuint dataVertices;
glCreateBuffers(1, &dataVertices);
glNamedBufferStorage(dataVertices, kSizeVertices, vertices.data(), 0);
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 1, dataVertices);
// model matrices
GLuint modelMatrices;
glCreateBuffers(1, &modelMatrices);
glNamedBufferStorage(modelMatrices, sizeof(mat4) * 2, nullptr, GL_DYNAMIC_STORAGE_BIT);
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 2, modelMatrices);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
// texture
GLuint texture;
{
int w, h, comp;
const uint8_t* img = stbi_load("data/rubber_duck/textures/Duck_baseColor.png", &w, &h, &comp, 3);
glCreateTextures(GL_TEXTURE_2D, 1, &texture);
glTextureParameteri(texture, GL_TEXTURE_MAX_LEVEL, 0);
glTextureParameteri(texture, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTextureParameteri(texture, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTextureStorage2D(texture, 1, GL_RGB8, w, h);
glTextureSubImage2D(texture, 0, 0, 0, w, h, GL_RGB, GL_UNSIGNED_BYTE, img);
glBindTextures(0, 1, &texture);
stbi_image_free((void*)img);
}
// cube map
GLuint cubemapTex;
{
int w, h, comp;
const float* img = stbi_loadf("data/piazza_bologni_1k.hdr", &w, &h, &comp, 3);
Bitmap in(w, h, comp, eBitmapFormat_Float, img);
Bitmap out = convertEquirectangularMapToVerticalCross(in);
stbi_image_free((void*)img);
Bitmap cubemap = convertVerticalCrossToCubeMapFaces(out);
glCreateTextures(GL_TEXTURE_CUBE_MAP, 1, &cubemapTex);
glTextureParameteri(cubemapTex, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTextureParameteri(cubemapTex, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTextureParameteri(cubemapTex, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
glTextureParameteri(cubemapTex, GL_TEXTURE_BASE_LEVEL, 0);
glTextureParameteri(cubemapTex, GL_TEXTURE_MAX_LEVEL, 0);
glTextureParameteri(cubemapTex, GL_TEXTURE_MAX_LEVEL, 0);
glTextureParameteri(cubemapTex, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTextureParameteri(cubemapTex, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTextureStorage2D(cubemapTex, 1, GL_RGB32F, cubemap.w_, cubemap.h_);
const uint8_t* data = cubemap.data_.data();
for (unsigned i = 0; i != 6; ++i)
{
glTextureSubImage3D(cubemapTex, 0, 0, 0, i, cubemap.w_, cubemap.h_, 1, GL_RGB, GL_FLOAT, data);
data += cubemap.w_ * cubemap.h_ * cubemap.comp_ * Bitmap::getBytesPerComponent(cubemap.fmt_);
}
glBindTextures(1, 1, &cubemapTex);
}
glfwSetCursorPosCallback(
window,
[](auto* window, double x, double y)
{
int width, height;
glfwGetFramebufferSize(window, &width, &height);
mouseState.pos.x = static_cast<float>(x / width);
mouseState.pos.y = static_cast<float>(y / height);
}
);
glfwSetMouseButtonCallback(
window,
[](auto* window, int button, int action, int mods)
{
if (button == GLFW_MOUSE_BUTTON_LEFT)
mouseState.pressedLeft = action == GLFW_PRESS;
}
);
glfwSetKeyCallback(
window,
[](GLFWwindow* window, int key, int scancode, int action, int mods)
{
const bool pressed = action != GLFW_RELEASE;
if (key == GLFW_KEY_ESCAPE && pressed)
glfwSetWindowShouldClose(window, GLFW_TRUE);
if (key == GLFW_KEY_W)
positioner.movement_.forward_ = pressed;
if (key == GLFW_KEY_S)
positioner.movement_.backward_ = pressed;
if (key == GLFW_KEY_A)
positioner.movement_.left_ = pressed;
if (key == GLFW_KEY_D)
positioner.movement_.right_ = pressed;
if (key == GLFW_KEY_1)
positioner.movement_.up_ = pressed;
if (key == GLFW_KEY_2)
positioner.movement_.down_ = pressed;
if (mods & GLFW_MOD_SHIFT)
positioner.movement_.fastSpeed_ = pressed;
if (key == GLFW_KEY_SPACE)
positioner.setUpVector(vec3(0.0f, 1.0f, 0.0f));
}
);
double timeStamp = glfwGetTime();
float deltaSeconds = 0.0f;
while (!glfwWindowShouldClose(window))
{
positioner.update(deltaSeconds, mouseState.pos, mouseState.pressedLeft);
const double newTimeStamp = glfwGetTime();
deltaSeconds = static_cast<float>(newTimeStamp - timeStamp);
timeStamp = newTimeStamp;
int width, height;
glfwGetFramebufferSize(window, &width, &height);
const float ratio = width / (float)height;
glViewport(0, 0, width, height);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
const mat4 p = glm::perspective(45.0f, ratio, 0.1f, 1000.0f);
const mat4 view = camera.getViewMatrix();
const PerFrameData perFrameData = { .view = view, .proj = p, .cameraPos = glm::vec4(camera.getPosition(), 1.0f) };
glNamedBufferSubData(perFrameDataBuffer, 0, kUniformBufferSize, &perFrameData);
const mat4 Matrices[2]
{
glm::rotate(glm::translate(mat4(1.0f), vec3(0.0f, -0.5f, -1.5f)), (float)glfwGetTime(), vec3(0.0f, 1.0f, 0.0f)),
glm::scale(mat4(1.0f), vec3(10.0f))
};
glNamedBufferSubData(modelMatrices, 0, sizeof(mat4) * 2, &Matrices);
progModel.useProgram();
glDrawElementsInstancedBaseVertexBaseInstance(GL_TRIANGLES, static_cast<unsigned>(indices.size()), GL_UNSIGNED_INT, nullptr, 1, 0, 0);
progCube.useProgram();
glDrawArraysInstancedBaseInstance(GL_TRIANGLES, 0, 36, 1, 1);
glfwSwapBuffers(window);
glfwPollEvents();
assert(glGetError() == GL_NO_ERROR);
}
glDeleteBuffers(1, &dataIndices);
glDeleteBuffers(1, &dataVertices);
glDeleteBuffers(1, &perFrameDataBuffer);
glDeleteVertexArrays(1, &vao);
glfwDestroyWindow(window);
glfwTerminate();
return 0;
}
| 29.66113 | 136 | 0.733199 | [
"mesh",
"vector",
"model"
] |
a0e99c249fe0afa354af24610453ad536da96b18 | 2,505 | cpp | C++ | src/NativeScript/LiveEdit/ClearChangedCellsFunctor.cpp | aaayushsingh/ios-runtime | f8714aaf20ba9cdd288fc34e53d181a4d7f8cd6e | [
"Apache-2.0"
] | 1 | 2021-11-14T02:57:26.000Z | 2021-11-14T02:57:26.000Z | src/NativeScript/LiveEdit/ClearChangedCellsFunctor.cpp | aaayushsingh/ios-runtime | f8714aaf20ba9cdd288fc34e53d181a4d7f8cd6e | [
"Apache-2.0"
] | null | null | null | src/NativeScript/LiveEdit/ClearChangedCellsFunctor.cpp | aaayushsingh/ios-runtime | f8714aaf20ba9cdd288fc34e53d181a4d7f8cd6e | [
"Apache-2.0"
] | 1 | 2021-11-14T02:56:06.000Z | 2021-11-14T02:56:06.000Z | #include "ClearChangedCellsFunctor.h"
#include <JavaScriptCore/CodeBlock.h>
#include <JavaScriptCore/ExecutableBase.h>
#include <JavaScriptCore/FunctionCodeBlock.h>
#include <JavaScriptCore/HeapInlines.h>
#include <JavaScriptCore/JSModuleEnvironment.h>
#include <JavaScriptCore/JSModuleRecord.h>
namespace NativeScript {
ClearChangedCellsFunctor::ClearChangedCellsFunctor(JSC::VM& vm, WTF::String url, WTF::Vector<DiffChunk> diff)
: m_vm(vm)
, m_url(url)
, m_diff(diff) {
}
JSC::IterationStatus ClearChangedCellsFunctor::operator()(JSC::HeapCell* cell, JSC::HeapCell::Kind kind) const {
if (kind == JSC::HeapCell::JSCell) {
visit(cell);
}
return JSC::IterationStatus::Continue;
}
void ClearChangedCellsFunctor::visit(JSC::HeapCell* heapCell) const {
JSC::JSCell* cell = static_cast<JSC::JSCell*>(heapCell);
if (!cell->inherits(m_vm, JSC::JSFunction::info()))
return;
JSC::JSFunction* function = JSC::jsCast<JSC::JSFunction*>(cell);
if (function->executable()->isHostFunction() || function->isBuiltinFunction())
return;
JSC::SourceCode* sourceCode = const_cast<JSC::SourceCode*>(function->sourceCode());
if (sourceCode->provider()->url() == m_url) {
bool changed{ false };
for (DiffChunk diff : m_diff) {
if (diff.pos1 + diff.len1 <= sourceCode->startOffset()) {
changed = true;
sourceCode->setStartOffset(sourceCode->startOffset() + diff.len1);
sourceCode->setStartOffset(sourceCode->startOffset() - diff.len2);
sourceCode->setEndOffset(sourceCode->endOffset() + diff.len1);
sourceCode->setEndOffset(sourceCode->endOffset() - diff.len2);
} else if (diff.pos1 >= sourceCode->startOffset() && diff.pos1 <= sourceCode->endOffset()) {
changed = true;
sourceCode->setEndOffset(sourceCode->endOffset() + diff.len1);
sourceCode->setEndOffset(sourceCode->endOffset() - diff.len2);
}
}
if (changed) {
JSC::FunctionExecutable* executable = function->jsExecutable();
if (JSC::FunctionCodeBlock* functionCodeBlock = executable->codeBlockForCall()) {
functionCodeBlock->unlinkIncomingCalls();
}
executable->clearNumParametersForCall();
executable->clearCode();
executable->unlinkedExecutable()->clearCode();
}
}
}
} // namespace NativeScript
| 39.761905 | 112 | 0.644311 | [
"vector"
] |
a0ee3f89269e9da3615cda5e2a52787d4a202583 | 1,792 | cpp | C++ | source/aufgabe_6.cpp | pono2189/programmiersprachen-aufgabenblatt-3 | a84870058ae029ef9c9a55aa2cb9ae42e26099eb | [
"MIT"
] | null | null | null | source/aufgabe_6.cpp | pono2189/programmiersprachen-aufgabenblatt-3 | a84870058ae029ef9c9a55aa2cb9ae42e26099eb | [
"MIT"
] | null | null | null | source/aufgabe_6.cpp | pono2189/programmiersprachen-aufgabenblatt-3 | a84870058ae029ef9c9a55aa2cb9ae42e26099eb | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
#include <list>
#include "stdio.h"
#include <set>
#include <map>
#include <iterator>
#include "circle.hpp"
#include <string>
#include "vec2.hpp"
#include "color.hpp"
#include <algorithm>
#define CATCH_CONFIG_RUNNER
#include <catch.hpp>
//Aufgabe 3.6
TEST_CASE ("aufgabe6","[aufgabe6]") {
std::string name;
Circle c1 = Circle{450.0f,Vec2{200.0f,400.0f},Color{1.0f,0.0f,0.0f},"Circle1"};
Circle c2 = Circle{100.0f,Vec2{600.0f,400.0f},Color{0.0f,1.0f,0.0f},"Circle2"};
Circle c3 = Circle{30.0f,Vec2{200.0f,400.0f},Color{0.0f,0.0f,1.0f},"Circle3"};
Circle c4 = Circle{450.0f,Vec2{200.0f,300.0f},Color{1.0f,1.0f,0.0f},"Circle1"};
std::vector<Circle> sorted_circles;
sorted_circles.push_back(c1);
sorted_circles.push_back(c2);
sorted_circles.push_back(c3);
std::sort(sorted_circles.begin(), sorted_circles.end());
REQUIRE(std::is_sorted(sorted_circles.begin(), sorted_circles.end()));
}
TEST_CASE ("aufgabe7","[aufgabe7]") {
std::vector<Circle> circles_7;
Circle c1 = Circle{450.0f,Vec2{200.0f,400.0f},Color{1.0f,0.0f,0.0f},"Circle1"};
Circle c2 = Circle{100.0f,Vec2{600.0f,400.0f},Color{0.0f,1.0f,0.0f},"Circle2"};
Circle c3 = Circle{30.0f,Vec2{200.0f,400.0f},Color{0.0f,0.0f,1.0f},"Circle3"};
Circle c4 = Circle{450.0f,Vec2{200.0f,300.0f},Color{1.0f,1.0f,0.0f},"Circle1"};
circles_7.push_back(c1);
circles_7.push_back(c2);
circles_7.push_back(c3);
std::sort(circles_7.begin(), circles_7.end(), [] (Circle c1, Circle c2)-> bool {return c1 < c2;});
REQUIRE(std::is_sorted(circles_7.begin(), circles_7.end()));
}
int main(int argc, char *argv[])
{
return Catch::Session().run(argc, argv);
} | 32.581818 | 106 | 0.640625 | [
"vector"
] |
a0f31eabc4af8b77b966c41a8c3b735d596c1342 | 732 | cpp | C++ | cpp/3.longestNonRepSubString/longestNonrepeatsubstring.cpp | LukeALee/algorithms | 34dfe4e7929d35888d3ac3cc6b84c518b1551e4c | [
"MIT"
] | null | null | null | cpp/3.longestNonRepSubString/longestNonrepeatsubstring.cpp | LukeALee/algorithms | 34dfe4e7929d35888d3ac3cc6b84c518b1551e4c | [
"MIT"
] | null | null | null | cpp/3.longestNonRepSubString/longestNonrepeatsubstring.cpp | LukeALee/algorithms | 34dfe4e7929d35888d3ac3cc6b84c518b1551e4c | [
"MIT"
] | null | null | null | /*
* @LukeA.Lee app=leetcode.cn id=3 lang=cpp
*
* [3] 最长无重复子串
*/
#include<iostream>
#include<algorithm>
#include<vector>
#include<algorithm>
using namespace std;
class Solution {
public:
int lengthOfLongestSubstring(string s) {
vector<int> dict(256, -1);
int maxLen = 0, start = -1;
for (int i = 0; i != s.length(); i++) {
if (dict[s[i]] > start)
start = dict[s[i]];
dict[s[i]] = i;
maxLen = max(maxLen, i - start);
}
return maxLen;
}
};
int main(){
string s = "abcabcdb";
Solution sol;
int res;
res= sol.lengthOfLongestSubstring(s);
cout << res << endl;
return 0;
} | 21.529412 | 51 | 0.506831 | [
"vector"
] |
a0f74378fbad757773af24d2169d01c6c2b2a1c3 | 697 | cpp | C++ | orcm/mca/sensor/udsensors/rand_generator/rand_generator.cpp | ctrlsys/sensys | 58221bca169c95c300ecc5526aa00590f0ce5c2f | [
"BSD-3-Clause-Open-MPI"
] | 14 | 2016-09-06T17:02:20.000Z | 2020-03-30T14:34:59.000Z | orcm/mca/sensor/udsensors/rand_generator/rand_generator.cpp | ctrlsys/sensys | 58221bca169c95c300ecc5526aa00590f0ce5c2f | [
"BSD-3-Clause-Open-MPI"
] | 9 | 2017-04-25T20:45:11.000Z | 2017-07-20T14:58:03.000Z | orcm/mca/sensor/udsensors/rand_generator/rand_generator.cpp | ctrlsys/sensys | 58221bca169c95c300ecc5526aa00590f0ce5c2f | [
"BSD-3-Clause-Open-MPI"
] | 5 | 2016-10-11T03:28:26.000Z | 2019-07-31T00:36:02.000Z | /*
* Copyright (c) 2016 Intel Corporation. All rights reserved.
* $COPYRIGHT$
*
* Additional copyrights may follow
*
* $HEADER$
*/
#include "rand_generator.hpp"
#include <iostream>
#include <stdexcept>
#include <cstdlib>
void mySensor::init()
{
std::cout << "On init in plugin" << std::endl;
}
void mySensor::sample(dataContainer &dc)
{
int random;
random = rand() % 100;
std::cout << "On sample, storing random number " << random << std::endl;
// Storing integer data into the dataContainer object
dc.put("intValue_1", random, "ints");
}
void mySensor::finalize()
{
std::cout << "On finalize" << std::endl;
}
export_plugin(mySensor, "RandGenerator");
| 19.914286 | 76 | 0.649928 | [
"object"
] |
9d0748f6aff4b6dee4f71a7cef6908faf632cf26 | 1,310 | hpp | C++ | src/viewport.hpp | ramnasidharta/graphical-recipe | 257d0455b73d2f5b212ebec028ec7b4c7a02db07 | [
"MIT"
] | null | null | null | src/viewport.hpp | ramnasidharta/graphical-recipe | 257d0455b73d2f5b212ebec028ec7b4c7a02db07 | [
"MIT"
] | 32 | 2019-03-22T15:14:10.000Z | 2020-04-01T14:57:33.000Z | src/viewport.hpp | ramnasidharta/graphical-recipe | 257d0455b73d2f5b212ebec028ec7b4c7a02db07 | [
"MIT"
] | null | null | null | #ifndef VIEWPORT_HPP
#define VIEWPORT_HPP
#include "window.hpp"
class ViewPort {
private:
Window *window;
vector<Coordinate*> vpCoord;
public:
ViewPort (vector<Coordinate*> vpCoord, Window *window) {
this->vpCoord = vpCoord;
this->window = window;
}
~ViewPort () {
delete this->vpCoord.front();
delete this->vpCoord.back();
}
vector<Coordinate*> getCoordinates () {
return vpCoord;
}
//! The viewport (coordinates system) transformation
/*!
* Transforms coord into a Coordinate referred to the viewport.
* @param coord The window coordinate to be transformed into a viewport coordinate.
*/
void transformation(Coordinate *coord) {
// Normalized coordinate system
double xnsMax = 1;
double ynsMax = 1;
double xnsMin = -1;
double ynsMin = -1;
double xvpMax = vpCoord.back()->getX();
double yvpMax = vpCoord.back()->getY();
double xvpMin = vpCoord.front()->getX();
double yvpMin = vpCoord.front()->getY();
double x = (( (coord->getXns() - xnsMin) / (xnsMax - xnsMin) ) * (xvpMax - xvpMin)) + xvpMin;
double y = ((1 - (coord->getYns() - ynsMin)/ (ynsMax - ynsMin) ) * (yvpMax - yvpMin)) + yvpMin;
coord->setXvp(x);
coord->setYvp(y);
}
};
#endif
| 25.192308 | 101 | 0.612977 | [
"vector"
] |
9d08d1541685a9350aec714aed047007c6ac4765 | 1,201 | cpp | C++ | createfractaldialog.cpp | khokm/simple-graphics-editor | b5612d75cc66b32db8f5c30f9dec6a01454f9a27 | [
"MIT"
] | null | null | null | createfractaldialog.cpp | khokm/simple-graphics-editor | b5612d75cc66b32db8f5c30f9dec6a01454f9a27 | [
"MIT"
] | null | null | null | createfractaldialog.cpp | khokm/simple-graphics-editor | b5612d75cc66b32db8f5c30f9dec6a01454f9a27 | [
"MIT"
] | null | null | null | #include "createfractaldialog.h"
#include "ui_createfractaldialog.h"
CreateFractalDialog::CreateFractalDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::CreateFractalDialog)
{
ui->setupUi(this);
on_pushButton_2_clicked();
}
CreateFractalDialog::~CreateFractalDialog()
{
delete ui;
}
std::vector<Line2D> *CreateFractalDialog::GetLines()
{
return &ui->openGLWidget->lines;
}
void CreateFractalDialog::RebuildTree()
{
if(antilag)
return;
int deep = ui->treeDeep->value();
int branchCount = ui->branchCount->value();
int total = 0;
ui->openGLWidget->BuildTree(deep, branchCount, ui->firstRight->isChecked(), ui->branchAngle->value(), total);
ui->totalCountLabel->setText(QString("Суммарное количество ветвей: ").append(QString::number(total)));
}
void CreateFractalDialog::on_pushButton_2_clicked()
{
antilag = true;
ui->treeDeep->setValue(3 + rand() % 5);
ui->branchCount->setValue(2 + rand() % 6);
ui->firstRight->setChecked(rand() % 2);
ui->branchAngle->setValue(RandomFloat(10, 30));
antilag = false;
RebuildTree();
}
void CreateFractalDialog::on_createAndExit_clicked()
{
accept();
close();
}
| 22.240741 | 113 | 0.68443 | [
"vector"
] |
9d0d424afbf0b7868bab355cd55afbeb9becb8d2 | 8,423 | cc | C++ | apps/dump_meso_data/get_meso_data.cc | OSADP/Pikalert-Vehicle-Data-Translator- | 295da604408f6f13af0301b55476a81311459386 | [
"Apache-2.0"
] | 2 | 2020-06-03T15:59:50.000Z | 2020-12-21T11:11:57.000Z | apps/dump_meso_data/get_meso_data.cc | OSADP/Pikalert-Vehicle-Data-Translator- | 295da604408f6f13af0301b55476a81311459386 | [
"Apache-2.0"
] | null | null | null | apps/dump_meso_data/get_meso_data.cc | OSADP/Pikalert-Vehicle-Data-Translator- | 295da604408f6f13af0301b55476a81311459386 | [
"Apache-2.0"
] | 2 | 2019-10-02T06:47:23.000Z | 2020-02-02T18:32:23.000Z | // *=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*
// ** Copyright UCAR (c) 1992 - 2015
// ** University Corporation for Atmospheric Research(UCAR)
// ** National Center for Atmospheric Research(NCAR)
// ** Research Applications Laboratory(RAL)
// ** P.O.Box 3000, Boulder, Colorado, 80307-3000, USA
// ** See LICENCE.TXT if applicable for licence details
// ** 2015/02/02 20:21:20
// *=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*
#include <string.h>
#include <fstream>
#include <cstdio>
#include <time.h>
#include <log/log.hh>
#include <nxncf/nxncf.hh>
#include <time.h>
#include "data.h"
extern Log *logfile;
int get_meso_data(int num_files, char *inputFileName, vector<char *> &variables, os *obs_data);
int get_meso_data(int num_files, char *inputFileName, vector<char *> &variables, os *obs_data){
int ret;
int f, i, j, k;
int ind;
NcVar *var;
NcAtt *att;
char varname[80];
int minfld;
char *cvar;
minfld = 8; /* size of minimum field width */
char *inputFile[num_files];
NcFile *nc_inf[num_files];
long num_obs[num_files];
int stnid_len[num_files];
char *station_ids[num_files];
double *obs_times[num_files];
// Loop over files and get critical information
for(f = 0; f < num_files; f++){
inputFile[f] = inputFileName;
logfile->write_time(2, "obs_input_file[%d] = %s\n", f, inputFile[f]);
// Open input file
nc_inf[f] = new NcFile(inputFile[f], NcFile::ReadOnly);
if (!nc_inf[f]->is_valid())
{
logfile->write_time("Warning: Unable to open input file %s\n",inputFile[f]);
continue;
}
// Get dimension for number of reports
strcpy(varname,"recNum");
NcDim *dim = nc_inf[f]->get_dim("recNum");
if (!dim)
{
logfile->write_time("Warning: Unable to get ptr for dim %s,in file %s\n",varname,inputFile[f]);
obs_data[f].is_valid = 1;
continue;
}
num_obs[f] = dim->size();
// Get station IDs
strcpy(varname,"maxStaIdLen");
dim = nc_inf[f]->get_dim(varname);
if (!dim)
{
logfile->write_time("Warning: Unable to get ptr for dim %s, in file %s\n",varname,inputFile[f]);
obs_data[f].is_valid = 1;
continue;
}
stnid_len[f] = dim->size();
strcpy(varname,"stationId");
var = nc_inf[f]->get_var(varname);
if (!var)
{
logfile->write_time("Warning: Unable to get ptr for %s, in file %s\n",varname,inputFile[f]);
obs_data[f].is_valid = 1;
continue;
}
station_ids[f] = new char[num_obs[f]*stnid_len[f]];
ret = var->get(station_ids[f], num_obs[f], stnid_len[f]);
if (ret == 0)
{
logfile->write_time("Warning: Unable to get data for var %s, in file %s\n",varname,inputFile[f]);
obs_data[f].is_valid = 1;
continue;
}
// Get report times
strcpy(varname,"observationTime");
var = nc_inf[f]->get_var(varname);
if (!var)
{
logfile->write_time("Warning: Unable to get ptr for %s, in file %s\n",varname,inputFile[f]);
obs_data[f].is_valid = 1;
continue;
}
obs_times[f] = new double[num_obs[f]];
ret = var->get(obs_times[f], num_obs[f]);
if (ret == 0)
{
logfile->write_time("Warning: Unable to get data for %s, in file %s\n",varname,inputFile[f]);
obs_data[f].is_valid = 1;
continue;
}
}
// Allocate space for data and variable units
float **var_ptrs = new float *[variables.size()*num_files];
char **var_units = new char *[variables.size()*num_files];
int *type = new int[variables.size()*num_files];
int *width = new int[variables.size()*num_files];
long *num_vals = new long[variables.size()*num_files];
int *num_dim = new int[variables.size()*num_files];
// Loop over requested variables and read data
ind = 0;
for (i=0; i<variables.size(); i++)
{
for(f = 0; f<num_files; f++)
{
if(nc_inf[f]->is_valid()){
obs_data[f].is_valid = 0;
obs_data[ind].var_is_valid = 0;
var = nc_inf[f]->get_var(variables[i]);
if (!var)
{
if(strcmp(variables[i], "MissingVar") != 0 && strcmp(variables[i], "roadTemperature") != 0 && strcmp(variables[i], "bridgeTemperature") != 0 && strcmp(variables[i], "roadSubsurfaceTemp") != 0){
logfile->write_time("Info: Unable to get ptr for %s, in file %s\n",variables[i],inputFile[f]);
}
obs_data[ind].var_is_valid = 1;
ind++;
continue;
}
// Get full size of variable and save
long *dim = var->edges();
num_dim[ind] = var->num_dims();
num_vals[ind] = var->num_vals();
var_ptrs[ind] = new float[num_vals[ind]];
// Save field width size
width[ind] = strlen(variables[i]);
if (width[ind] < minfld)
width[ind] = minfld;
// Get variable units
att = var->get_att( "units" );
if (att)
{
var_units[ind] = new char[strlen(att->as_string(0))+1];
strcpy(var_units[ind], att->as_string(0));
}
else
{
var_units[ind] = new char[1];
strcpy(var_units[ind], "");
}
// Get values
type[ind] = var->type();
if (type[ind] == ncFloat)
{
ret = var->get(var_ptrs[ind], dim);
if (ret == 0)
{
logfile->write_time("Warning Unable to get data for %s, in file %s\n",variables[i],inputFile[f]);
obs_data[f].is_valid = 1;
}
}
else if (type[ind] == ncDouble)
{
double *dvar = new double[num_vals[ind]];
ret = var->get(dvar, dim);
if (ret == 0)
{
logfile->write_time("Warning Unable to get data for %s, in file %s\n",variables[i],inputFile[f]);
obs_data[f].is_valid = 1;
}
for (j=0; j<num_vals[ind]; j++)
var_ptrs[ind][j] = (float)dvar[j];
}
else if (type[ind] == ncInt)
{
int *svar = new int[num_vals[ind]];
ret = var->get(svar, dim);
if (ret == 0)
{
logfile->write_time("Warning Unable to get data for %s, in file %s\n",variables[i],inputFile[f]);
obs_data[f].is_valid = 1;
}
for (j=0; j<num_vals[ind]; j++)
var_ptrs[ind][j] = (float)svar[j];
}
else if (type[ind] == ncShort)
{
short *svar = new short[num_vals[ind]];
ret = var->get(svar, dim);
if (ret == 0)
{
logfile->write_time("Warning Unable to get data for %s, in file %s\n",variables[i],inputFile[f]);
obs_data[f].is_valid = 1;
}
for (j=0; j<num_vals[ind]; j++)
var_ptrs[ind][j] = (float)svar[j];
}
else if (type[ind] == ncChar)
{
cvar = new char[num_vals[ind]];
ret = var->get(cvar, dim);
if (ret == 0)
{
logfile->write_time("Warning Unable to get data for %s, in file %s\n",variables[i],inputFile[f]);
obs_data[f].is_valid = 1;
}
for (j=0; j<num_vals[ind]; j++)
var_ptrs[ind][j] = cvar[j];
// Save string length for width if larger than variable name
if(num_dim[ind] > 1){
if(dim[1] > width[ind]){
width[ind] = dim[1];
}
}
}
else
{
logfile->write_time("Warning %s, in file %s is not of type ncFloat, ncShort or ncDouble\n",variables[i],inputFile[f]);
for (j=0; j<num_vals[ind]; j++){
var_ptrs[ind][j] = MISSING;
}
}
if(obs_data[ind].var_is_valid == 0){
logfile->write_time(2,"Read data for %s in file %s\n",variables[i],inputFile[f]);
}
} else{
obs_data[f].is_valid = 1;
obs_data[ind].var_is_valid = 1;
}
ind++;
}
}
// Put data into obs_data struct
for(f = 0; f < num_files; f++){
if(obs_data[f].is_valid == 0){
obs_data[f].num_obs = num_obs[f];
obs_data[f].stnid_len = stnid_len[f];
obs_data[f].station_ids = new char[num_obs[f]*stnid_len[f]];
obs_data[f].obs_times = new double[num_obs[f]];
for(j = 0; j < num_obs[f]*stnid_len[f]; j++){
obs_data[f].station_ids[j] = station_ids[f][j];
}
for(j = 0; j < num_obs[f]; j++){
obs_data[f].obs_times[j] = obs_times[f][j];
}
}
}
ind = 0;
for (i=0; i<variables.size(); i++){
for(f = 0; f < num_files; f++){
if(obs_data[ind].var_is_valid == 0){
obs_data[ind].units = &var_units[ind];
obs_data[ind].var_ptrs = var_ptrs[ind];
}
ind++;
}
}
return(0);
}
| 28.076667 | 196 | 0.562151 | [
"vector"
] |
9d109741a43e919b6f10f66a81574450e477c5e6 | 9,606 | cpp | C++ | MultiQuestensions/src/Hooks/MaxPlayerHooks.cpp | EnderdracheLP/MultiQuestensions | 2d9772570117ff92d933466684f074774285cc94 | [
"MIT"
] | 1 | 2021-08-09T20:06:44.000Z | 2021-08-09T20:06:44.000Z | MultiQuestensions/src/Hooks/MaxPlayerHooks.cpp | EnderdracheLP/MultiQuestensions | 2d9772570117ff92d933466684f074774285cc94 | [
"MIT"
] | null | null | null | MultiQuestensions/src/Hooks/MaxPlayerHooks.cpp | EnderdracheLP/MultiQuestensions | 2d9772570117ff92d933466684f074774285cc94 | [
"MIT"
] | 3 | 2021-09-20T13:21:48.000Z | 2021-09-21T15:58:17.000Z | #include "main.hpp"
#include "Hooks/Hooks.hpp"
using namespace GlobalNamespace;
using namespace System;
using namespace System::Collections::Generic;
using namespace System::Linq;
using namespace UnityEngine;
using namespace UnityEngine::Playables;
using namespace UnityEngine::Timeline;
namespace MultiQuestensions {
int targetIterations = 0;
MAKE_HOOK_MATCH(MultiplayerResultsPyramidPatch, &MultiplayerResultsPyramidView::SetupResults, void, MultiplayerResultsPyramidView* self, IReadOnlyList_1<MultiplayerPlayerResultsData*>* resultsData, UnityEngine::Transform* badgeStartTransform, UnityEngine::Transform* badgeMidTransform) {
try {
static auto* Enumerable_Take_Generic = THROW_UNLESS(il2cpp_utils::FindMethodUnsafe(classof(Enumerable*), "Take", 2));
static auto* Enumerable_Take = THROW_UNLESS(il2cpp_utils::MakeGenericMethod(Enumerable_Take_Generic, { classof(MultiplayerPlayerResultsData*) }));
auto* takeResult = il2cpp_utils::RunMethodThrow<IEnumerable_1<MultiplayerPlayerResultsData*>*, false>(static_cast<Il2CppClass*>(nullptr),
Enumerable_Take, reinterpret_cast<IEnumerable_1<MultiplayerPlayerResultsData*>*>(resultsData), 5);
static auto* Enumerable_ToList_Generic = THROW_UNLESS(il2cpp_utils::FindMethodUnsafe(classof(Enumerable*), "ToList", 1));
static auto* Enumerable_ToList = THROW_UNLESS(il2cpp_utils::MakeGenericMethod(Enumerable_ToList_Generic, { classof(MultiplayerPlayerResultsData*) }));
List<MultiplayerPlayerResultsData*>* newResultsData = il2cpp_utils::RunMethodThrow<List_1<MultiplayerPlayerResultsData*>*, false>(static_cast<Il2CppClass*>(nullptr),
Enumerable_ToList, takeResult);
//List<MultiplayerPlayerResultsData*>* newResultsData = Enumerable::ToList<MultiplayerPlayerResultsData*>(Enumerable::Take<MultiplayerPlayerResultsData*>(reinterpret_cast<IEnumerable_1<MultiplayerPlayerResultsData*>*>(resultsData), 5));
MultiplayerResultsPyramidPatch(self, (IReadOnlyList_1<MultiplayerPlayerResultsData*>*)newResultsData, badgeStartTransform, badgeMidTransform);
}
catch (const std::runtime_error& e) {
getLogger().critical("Hook MultiplayerResultsPyramidPatch File " __FILE__ " at Line %d: %s", __LINE__, e.what());
MultiplayerResultsPyramidPatch(self, resultsData, badgeStartTransform, badgeMidTransform);
}
}
MAKE_HOOK_MATCH(IntroAnimationPatch, &MultiplayerIntroAnimationController::PlayIntroAnimation, void, MultiplayerIntroAnimationController* self, float maxDesiredIntroAnimationDuration, Action* onCompleted) {
targetIterations = ((((IReadOnlyCollection_1<GlobalNamespace::IConnectedPlayer*>*)self->multiplayerPlayersManager->allActiveAtGameStartPlayers)->get_Count() - 1) / 4) + 1;
PlayableDirector* realDirector = self->introPlayableDirector;
try {
// Run animation one time for each set of 4 players
while (targetIterations > 0) {
if (targetIterations != 1) {
// Create duplicated animations
GameObject* newPlayableGameObject = GameObject::New_ctor();
self->introPlayableDirector = newPlayableGameObject->AddComponent<PlayableDirector*>();
using SetPlayableAsset = function_ptr_t<void, Il2CppObject*, PlayableAsset*>;
static SetPlayableAsset setPlayableAsset = reinterpret_cast<SetPlayableAsset>(il2cpp_functions::resolve_icall("UnityEngine.Playables.PlayableDirector::SetPlayableAsset"));
setPlayableAsset(self->introPlayableDirector, realDirector->get_playableAsset());
// Mute duplicated animations except one (otherwise audio is very loud)
TimelineAsset* animationTimeline = reinterpret_cast<TimelineAsset*>(self->introPlayableDirector->get_playableAsset());
List<TrackAsset*>* outputTracks = Enumerable::ToList<TrackAsset*>(animationTimeline->GetOutputTracks());
for (int i = 0; i < outputTracks->get_Count(); i++) {
TrackAsset* currentTrack = outputTracks->get_Item(i);
bool isAudio = il2cpp_utils::AssignableFrom<AudioTrack*>(reinterpret_cast<Il2CppObject*>(currentTrack)->klass);
currentTrack->set_muted(isAudio);
}
}
self->bindingFinished = false;
IntroAnimationPatch(self, maxDesiredIntroAnimationDuration, onCompleted);
self->introPlayableDirector = realDirector;
targetIterations--;
}
// Reset director to real director
self->introPlayableDirector = realDirector;
}
catch (const std::runtime_error& e) {
getLogger().critical("Hook IntroAnimationPatch" __FILE__ " at Line %d: %s", __LINE__, e.what());
IntroAnimationPatch(self, maxDesiredIntroAnimationDuration, onCompleted);
}
}
MAKE_HOOK_MATCH(CalculatePlayerIndexSequencePatch, &MultiplayerIntroAnimationController::CalculatePlayerIndexSequence, Queue_1<int>*, MultiplayerIntroAnimationController* self, IReadOnlyList_1<IConnectedPlayer*>* allActivePlayer) {
getLogger().debug("Start: CalculatePlayerIndexSequencePatch");
try {
// 09-21 14:30:26.025 4647 4672 D QuestHook[UtilsLogger|v2.3.0]: (il2cpp_utils::FindMethod) Method 27:
// 09-21 14:30:26.026 4647 4672 D QuestHook[UtilsLogger|v2.3.0]: (il2cpp_utils::FindMethod) static
// System.Collections.Generic.List<TSource> ToList(System.Collections.Generic.IEnumerable<TSource> source);
static auto* Enumerable_ToList_Generic = THROW_UNLESS(il2cpp_utils::FindMethodUnsafe(classof(Enumerable*), "ToList", 1));
static auto* Enumerable_ToList = THROW_UNLESS(il2cpp_utils::MakeGenericMethod(Enumerable_ToList_Generic, { classof(IConnectedPlayer*) }));
List<IConnectedPlayer*>* listActivePlayers = il2cpp_utils::RunMethodThrow<List_1<IConnectedPlayer*>*, false>(static_cast<Il2CppClass*>(nullptr),
Enumerable_ToList, reinterpret_cast<IEnumerable_1<IConnectedPlayer*>*>(allActivePlayer));
//List<IConnectedPlayer*>* listActivePlayers = Enumerable::ToList<IConnectedPlayer*>(reinterpret_cast<IEnumerable_1<IConnectedPlayer*>*>(allActivePlayer));
IConnectedPlayer* localPlayer = nullptr;
// Check if active players contains local player and remove local player
for (int i = 0; i < listActivePlayers->get_Count(); i++) {
IConnectedPlayer* currentPlayer = listActivePlayers->get_Item(i);
if (currentPlayer->get_isMe()) {
listActivePlayers->RemoveAt(i);
localPlayer = currentPlayer;
}
}
// Skip x amount of players and then take 4
static auto* Enumerable_Skip_Generic = THROW_UNLESS(il2cpp_utils::FindMethodUnsafe(classof(Enumerable*), "Skip", 2));
static auto* Enumerable_Skip = THROW_UNLESS(il2cpp_utils::MakeGenericMethod(Enumerable_Skip_Generic, { classof(IConnectedPlayer*) }));
auto* skipResult = il2cpp_utils::RunMethodThrow<IEnumerable_1<IConnectedPlayer*>*, false>(static_cast<Il2CppClass*>(nullptr),
Enumerable_Skip, reinterpret_cast<IEnumerable_1<IConnectedPlayer*>*>(listActivePlayers), (targetIterations - 1) * 4);
static auto* Enumerable_Take_Generic = THROW_UNLESS(il2cpp_utils::FindMethodUnsafe(classof(Enumerable*), "Take", 2));
static auto* Enumerable_Take = THROW_UNLESS(il2cpp_utils::MakeGenericMethod(Enumerable_Take_Generic, { classof(IConnectedPlayer*) }));
auto* takeResult = il2cpp_utils::RunMethodThrow<IEnumerable_1<IConnectedPlayer*>*, false>(static_cast<Il2CppClass*>(nullptr),
Enumerable_Take, skipResult, 4);
List<IConnectedPlayer*>* selectedActivePlayers = il2cpp_utils::RunMethodThrow<List_1<IConnectedPlayer*>*, false>(static_cast<Il2CppClass*>(nullptr),
Enumerable_ToList, takeResult);
//List<IConnectedPlayer*>* selectedActivePlayers = Enumerable::ToList<IConnectedPlayer*>(Enumerable::Take<IConnectedPlayer*>(Enumerable::Skip<IConnectedPlayer*>(reinterpret_cast<IEnumerable_1<IConnectedPlayer*>*>(listActivePlayers), (targetIterations - 1) * 4), 4));
//List<IConnectedPlayer*>* selectedActivePlayers = Enumerable::ToList<IConnectedPlayer*>(Enumerable::Take<IConnectedPlayer*>(skipResult, 4));
// Add back local player if not null
if (targetIterations == 1 && localPlayer != nullptr) {
selectedActivePlayers->Add(localPlayer);
}
getLogger().debug("Finish: CalculatePlayerIndexSequencePatch");
// Call method with new list of players
return CalculatePlayerIndexSequencePatch(self, reinterpret_cast<IReadOnlyList_1<IConnectedPlayer*>*>(selectedActivePlayers));
}
catch (const std::runtime_error& e) {
getLogger().critical("Hook CalculatePlayerIndexSequencePatch" __FILE__ " at Line %d: %s", __LINE__, e.what());
}
return CalculatePlayerIndexSequencePatch(self, allActivePlayer);
}
void Hooks::MaxPlayerHooks() {
INSTALL_HOOK(getLogger(), MultiplayerResultsPyramidPatch);
INSTALL_HOOK(getLogger(), IntroAnimationPatch);
INSTALL_HOOK(getLogger(), CalculatePlayerIndexSequencePatch);
}
} | 69.608696 | 291 | 0.701957 | [
"transform"
] |
1dd7e8d5aaa07a8e16f8f55a42cf0d5451e5f8f4 | 602 | cpp | C++ | geometry/abc191_c.cpp | Takumi1122/data-structure-algorithm | 6b9f26e4dbba981f034518a972ecfc698b86d837 | [
"MIT"
] | null | null | null | geometry/abc191_c.cpp | Takumi1122/data-structure-algorithm | 6b9f26e4dbba981f034518a972ecfc698b86d837 | [
"MIT"
] | null | null | null | geometry/abc191_c.cpp | Takumi1122/data-structure-algorithm | 6b9f26e4dbba981f034518a972ecfc698b86d837 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
#define rep(i, n) for (int i = 0; i < (n); ++i)
using namespace std;
using ll = long long;
using P = pair<int, int>;
using Graph = vector<vector<int>>;
// 自己交叉のない多角形
// マス目
/*
参考リンク
ABC 191 C - Digital Graffiti
https://atcoder.jp/contests/abc191/tasks/abc191_c
*/
int main() {
int h, w;
cin >> h >> w;
vector<string> f(h);
rep(i, h) cin >> f[i];
int ans = 0;
rep(i, h - 1) rep(j, w - 1) {
int cnt = 0;
rep(di, 2) rep(dj, 2) if (f[i + di][j + dj] == '#') cnt++;
if (cnt == 1 || cnt == 3) ++ans;
}
cout << ans << endl;
return 0;
} | 18.8125 | 62 | 0.521595 | [
"vector"
] |
1dd9d4946cc768bbfca0fce336f7123493bf566b | 2,639 | cc | C++ | c++3/prog02/sub2.cc | Andrew-Slade/cplusplus-projects | e5c5ac610f51d139f5d097ea00ac136c6fe1c365 | [
"MIT"
] | null | null | null | c++3/prog02/sub2.cc | Andrew-Slade/cplusplus-projects | e5c5ac610f51d139f5d097ea00ac136c6fe1c365 | [
"MIT"
] | null | null | null | c++3/prog02/sub2.cc | Andrew-Slade/cplusplus-projects | e5c5ac610f51d139f5d097ea00ac136c6fe1c365 | [
"MIT"
] | null | null | null | /**********************************************
*Student: Andrew Slade
*Program: prog1
*Due Date: Thursday, September 7, 2017
*ZID: Z1818810
*Section: 340-0003
*source file
*Purpose: fills vector with random values
*and then sorts them
********************************************/
//Prepocessors
#include "prog2.h"
using std::vector;
using std::binary_search;
using std::find;
using std::cout;
using std::srand;
using std::rand;
using std::setw;
using std::endl;
using std::setw;
using std::right;
//************
//fill vectors with random values
void Vectors(vector<int>& vector1, vector<int>& vector2, int s1, int s2){
//generates random numbers and fills vectors
srand(s1); //seed rand
for(size_t c = 0; c < ARR_SIZE ; c++){
//fill vector
vector1.at(c) = rand () % (HIGH - LOW + 1) + LOW;
}
srand(s2); //seed second round of generation
for(size_t i = 0; i < TEST_ARR_SIZE; i++){
vector2.at(i) = rand () % (HIGH - LOW + 1) + LOW;
}
return;
}
//use linear search to find a value in the vector
bool linearSearch(const vector<int>& v, int desired){
bool found;
std::vector<int>::const_iterator temp;//temporary constant iterator
//search for value in vector
temp = find(v.begin(), v.end(), desired);
if(temp != v.end()){
found = true;
}
else{
found = false;
}
return found;
}
//print vectors
void printVector(const vector<int>& v){
for(size_t l = 0; l < v.size(); l++){
//prints out vector
cout << setw(ITEM_W) << v.at(l);
if(((l + 1) % NO_ITEMS) == 0){
cout << endl; //inserts new line every 16 numbers
}
}
return;
}
//sorts vectors via stl implementation
void sortVector(vector<int>& v){
sort(v.begin(), v.end()); //sorts vector
return;
}
//searches using pointers to functions
int search(const vector<int>& vec1, const vector<int>& vec2, bool (*p) (const vector<int>&, int))
{
int success = 0;
for(size_t z = 0; z < vec2.size(); z++){
if(p(vec1, vec2.at(z)) == true){
success += 1;
}
}
return success;
}
//prints statistics gathered by searches
void printStat(int totalSucCnt, int vectorSz){
float percentSuccessful;
percentSuccessful = static_cast<float>(totalSucCnt) / static_cast<float>(vectorSz);
percentSuccessful *= 100.00;
cout << "\tPercent of Successful Searches = " << right << std::setprecision(2)
<< std::fixed << percentSuccessful << "%" << endl;
return;
}
bool binarySearch(const vector<int>& v, int x){
bool foundd;
if(binary_search(v.begin(), v.end(), x)){
//search for value
foundd = true;
}
else{
foundd = false;
}
return foundd;
}
| 20.3 | 97 | 0.611595 | [
"vector"
] |
1de03430bf8fea3c942ca2427ef17c66596c7e60 | 5,515 | hpp | C++ | include/np/ndarray/dynamic/NDArrayDynamicCompImpl.hpp | mgorshkov/np | 75c7adff38e7260371135839b547d5340f3ca367 | [
"MIT"
] | null | null | null | include/np/ndarray/dynamic/NDArrayDynamicCompImpl.hpp | mgorshkov/np | 75c7adff38e7260371135839b547d5340f3ca367 | [
"MIT"
] | null | null | null | include/np/ndarray/dynamic/NDArrayDynamicCompImpl.hpp | mgorshkov/np | 75c7adff38e7260371135839b547d5340f3ca367 | [
"MIT"
] | null | null | null | /*
C++ numpy-like template-based array implementation
Copyright (c) 2022 Mikhail Gorshkov (mikhail.gorshkov@gmail.com)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#pragma once
#include <np/ndarray/dynamic/internal/Tools.hpp>
#include <np/ndarray/dynamic/NDArrayDynamicDecl.hpp>
namespace np::ndarray::array_dynamic {
// Elementwise comparison
template <typename DType, typename Storage>
inline NDArrayDynamic<bool_, internal::NDArrayDynamicInternalStorageVector<bool_>>
NDArrayDynamic<DType, Storage>::operator==(const NDArrayDynamic<DType, internal::NDArrayDynamicInternalStorageVector<DType>> &array) const {
NDArrayDynamic<bool_, internal::NDArrayDynamicInternalStorageVector<bool_>> result{shape()};
for (Size i = 0; i < size(); ++i) {
auto equals = get(i) == array.get(i);
result.set(i, equals);
}
return result;
}
template <typename DType, typename Storage>
inline NDArrayDynamic<bool_, internal::NDArrayDynamicInternalStorageVector<bool_>>
NDArrayDynamic<DType, Storage>::operator==(const NDArrayDynamic<DType, internal::NDArrayDynamicInternalStorageSpan<DType>> &array) const {
NDArrayDynamic<bool_, internal::NDArrayDynamicInternalStorageVector<bool_>> result{shape()};
for (Size i = 0; i < size(); ++i) {
auto equals = get(i) == array.get(i);
result.set(i, equals);
}
return result;
}
// Elementwise comparison
template <typename DType, typename Storage>
inline NDArrayDynamic<bool_, internal::NDArrayDynamicInternalStorageVector<bool_>>
NDArrayDynamic<DType, Storage>::operator<(const NDArrayDynamic<DType, internal::NDArrayDynamicInternalStorageVector<DType>> &array) const {
NDArrayDynamic<bool_, internal::NDArrayDynamicInternalStorageVector<bool_>> result{shape()};
for (Size i = 0; i < size(); ++i) {
auto equals = get(i) < array.get(i);
result.set(i, equals);
}
return result;
}
template <typename DType, typename Storage>
inline NDArrayDynamic<bool_, internal::NDArrayDynamicInternalStorageVector<bool_>>
NDArrayDynamic<DType, Storage>::operator<(const NDArrayDynamic<DType, internal::NDArrayDynamicInternalStorageSpan<DType>> &array) const {
NDArrayDynamic<bool_, internal::NDArrayDynamicInternalStorageVector<bool_>> result{shape()};
for (Size i = 0; i < size(); ++i) {
auto equals = get(i) < array.get(i);
result.set(i, equals);
}
return result;
}
// Elementwise comparison
template <typename DType, typename Storage>
inline NDArrayDynamic<bool_, internal::NDArrayDynamicInternalStorageVector<bool_>>
NDArrayDynamic<DType, Storage>::operator>(const NDArrayDynamic<DType, internal::NDArrayDynamicInternalStorageVector<DType>> &array) const {
NDArrayDynamic<bool_, internal::NDArrayDynamicInternalStorageVector<bool_>> result{shape()};
for (Size i = 0; i < size(); ++i) {
auto equals = get(i) > array.get(i);
result.set(i, equals);
}
return result;
}
template <typename DType, typename Storage>
inline NDArrayDynamic<bool_, internal::NDArrayDynamicInternalStorageVector<bool_>>
NDArrayDynamic<DType, Storage>::operator>(const NDArrayDynamic<DType, internal::NDArrayDynamicInternalStorageSpan<DType>> &array) const {
NDArrayDynamic<bool_, internal::NDArrayDynamicInternalStorageVector<bool_>> result{shape()};
for (Size i = 0; i < size(); ++i) {
auto equals = get(i) > array.get(i);
result.set(i, equals);
}
return result;
}
template<typename DType, typename Storage>
inline bool NDArrayDynamic<DType, Storage>::array_equal(const DType& element) const {
if (shape().size() != 1 || shape()[0] != 1)
return false;
return m_ArrayImpl[0] == element;
}
template <typename DType, typename Storage>
inline bool NDArrayDynamic<DType, Storage>::array_equal(const NDArrayDynamic<DType, internal::NDArrayDynamicInternalStorageVector<DType>> &array) const {
return internal::array_equal(m_ArrayImpl, array.m_ArrayImpl);
}
template <typename DType, typename Storage>
inline bool NDArrayDynamic<DType, Storage>::array_equal(const NDArrayDynamic<DType, internal::NDArrayDynamicInternalStorageSpan<DType>> &array) const {
return internal::array_equal(m_ArrayImpl, array.m_ArrayImpl);
}
}
| 47.136752 | 157 | 0.708432 | [
"shape"
] |
1de1f81b04874c62d3ab334cd952bc498d02c7b5 | 9,671 | cpp | C++ | Renderer.cpp | lai001/SoftwareRendering | be90b4838dc847076b87969a19feeb2880e3322c | [
"MIT"
] | null | null | null | Renderer.cpp | lai001/SoftwareRendering | be90b4838dc847076b87969a19feeb2880e3322c | [
"MIT"
] | null | null | null | Renderer.cpp | lai001/SoftwareRendering | be90b4838dc847076b87969a19feeb2880e3322c | [
"MIT"
] | null | null | null | #include "Renderer.hpp"
#include "spdlog/spdlog.h"
#include "Util.hpp"
#include "Line2D.hpp"
Renderer::Renderer(int width, int height)
:frameBuffer(new FrameBuffer(width, height))
{
}
Renderer::~Renderer()
{
delete frameBuffer;
}
FrameBuffer const * const Renderer::getFrameBuffer() const
{
return frameBuffer;
}
void Renderer::flush() const
{
frameBuffer->flush();
}
void Renderer::clear(glm::vec3 color)
{
frameBuffer->clear(color);
}
int Renderer::getWidth() const
{
return frameBuffer->getWidth();
}
int Renderer::getHeight() const
{
return frameBuffer->getHeight();
}
void Renderer::setColor(const glm::vec3 point, const glm::vec3 color, const std::function<bool(double, double)> depthFunc) const
{
if (isAvailable(point, depthFunc))
{
frameBuffer->setPixel(point, color, depthFunc);
}
}
bool Renderer::isAvailable(const glm::vec3 point, const std::function<bool(double, double)> depthFunc) const
{
std::function<bool(double)> check = [](double v) {
return v >= -1.0 && v <= 1.0;
};
if (check(point.x) && check(point.y))
{
double z = frameBuffer->zValueAtNdcPoint(point);
bool isPass = depthFunc(point.z, z);
if (isPass)
{
return true;
}
}
return false;
}
void Renderer::addLine2D(const Line2D line2D, const glm::vec3 color) const
{
addLine2D(line2D.p0, line2D.p1, color);
}
void Renderer::addLine2D(const glm::vec2 p0, const glm::vec2 p1, const glm::vec3 color) const
{
if (p0.x == p1.x)
{
double y = std::min(p0.y, p1.y);
const double e = std::max(p0.y, p1.y);
const double step = 1.0 / (double)getHeight();
while (y < e)
{
const double x = p0.x;
setColor(glm::vec3((double)x, y, 0.0), color, DepthFunc::always);
y = y + step;
}
}
else if (p0.y == p1.y)
{
double x = std::min(p0.x, p1.x);
const double e = std::max(p0.x, p1.x);
const double step = 1.0 / (double)getWidth();
while (x < e)
{
const double y = p0.y;
setColor(glm::vec3((double)x, y, 0.0), color, DepthFunc::always);
x = x + step;
}
}
else
{
const double k = (p1.y - p0.y) / (p1.x - p0.x);
const double b = p0.y - k * p0.x;
if (k > 1.0)
{
double y = std::min(p0.y, p1.y);
const double e = std::max(p0.y, p1.y);
const double step = 1.0 / (double)getHeight();
while (y < e)
{
const double x = (y - b) / k;
setColor(glm::vec3(x, y, 0.0), color, DepthFunc::always);
y = y + step;
}
}
else
{
double x = std::min(p0.x, p1.x);
const double e = std::max(p0.x, p1.x);
const double step = 1.0 / (double)getWidth();
while (x < e)
{
const double y = k * x + b;
setColor(glm::vec3(x, y, 0.0), color, DepthFunc::always);
x = x + step;
}
}
}
}
void Renderer::addTriangle2D(const glm::vec2 a, const glm::vec2 b, const glm::vec2 c,
const glm::vec3 color,
const PolygonModeType polygonModeType) const
{
if (isValidTriangle(a, b, c) == false)
{
return;
}
switch (polygonModeType)
{
case PolygonModeType::line:
addLine2D(a, b, color);
addLine2D(b, c, color);
addLine2D(c, a, color);
break;
case PolygonModeType::fill:
std::vector<glm::vec2> points = { a, b, c };
std::sort(points.begin(), points.end(), [](glm::vec2 lhs, glm::vec2 rhs) {
return lhs.y < rhs.y;
});
std::function<double(double, glm::vec2, glm::vec2)> calcX = [](double y, glm::vec2 p0, glm::vec2 p1) {
if (p0.x == p1.x)
{
return (double)p0.x;
}
else
{
const double k = (p1.y - p0.y) / (p1.x - p0.x);
const double b = p0.y - k * p0.x;
const double x = (y - b) / k;
return x;
}
};
std::function<void(Line2D, Line2D, double, double)> scanline = [this, color, calcX](Line2D l1, Line2D l2, double y0, double y1) {
double step = 1.0 / (double)getHeight();
double xStep = 1.0 / (double)getWidth();
double y = y0;
while (y < y1)
{
double x0 = calcX(y, l1.p0, l1.p1);
double x1 = calcX(y, l2.p0, l2.p1);
double minX = std::min(x0, x1);
double maxX = std::max(x0, x1);
double x = minX;
while (x < maxX)
{
setColor({ (double)x, (double)y, 0.0 }, color, DepthFunc::always);
x = x + xStep;
}
y = y + step;
}
};
scanline(Line2D(points[0], points[1]),
Line2D(points[0], points[2]),
points[0].y,
points[1].y);
scanline(Line2D(points[1], points[2]),
Line2D(points[0], points[2]),
points[1].y,
points[2].y);
break;
}
}
void Renderer::addTriangle2D(const glm::vec2 p0, const glm::vec2 p1, const glm::vec2 p2,
const glm::vec3 c0, const glm::vec3 c1, const glm::vec3 c2) const
{
if (isValidTriangle(p0, p1, p2) == false)
{
return;
}
Rect box = Rect::boundingBox(p0, p1, p2);
for (double y = box.y; y <= box.y + box.height; y += (double)1.0 / (double)getHeight())
{
for (double x = box.x; x <= box.x + box.width; x += (double)1.0 / (double)getWidth())
{
BarycentricTestResult testResult = BarycentricTestResult::test(p0, p1, p2, x, y);
if (testResult.isInsideTriangle)
{
glm::vec2 interpolationP = interpolation(testResult.weight(), p0, p1, p2);
glm::vec3 interpolationC = interpolation(testResult.weight(), c0, c1, c2);
setColor(glm::vec3(interpolationP, 0.0), interpolationC, DepthFunc::always);
}
}
}
}
void Renderer::addTriangle3D(const glm::vec3 p0, const glm::vec3 p1, const glm::vec3 p2,
const glm::vec3 c0, const glm::vec3 c1, const glm::vec3 c2,
const std::function<bool(double, double)> depthFunc) const
{
if (isValidTriangle(p0, p1, p2) == false)
{
return;
}
Rect box = Rect::boundingBox(p0, p1, p2);
for (double y = box.y; y <= box.y + box.height; y += (double)1.0 / (double)getHeight())
{
for (double x = box.x; x <= box.x + box.width; x += (double)1.0 / (double)getWidth())
{
BarycentricTestResult testResult = BarycentricTestResult::test(p0, p1, p2, x, y);
if (testResult.isInsideTriangle)
{
glm::vec3 interpolationP = interpolation(testResult.weight(), p0, p1, p2);
glm::vec3 interpolationC = interpolation(testResult.weight(), c0, c1, c2);
setColor(interpolationP, interpolationC, depthFunc);
}
}
}
}
void Renderer::addTriangle3D(const glm::vec4 p0, const glm::vec4 p1, const glm::vec4 p2,
const glm::vec3 c0, const glm::vec3 c1, const glm::vec3 c2,
const std::function<bool(double, double)> depthFunc) const
{
glm::vec4 a = divideByW(p0);
glm::vec4 b = divideByW(p1);
glm::vec4 c = divideByW(p2);
if (isValidTriangle(a, b, c) == false)
{
return;
}
Rect box = Rect::boundingBox(a, b, c);
for (double y = box.y; y <= box.y + box.height; y += (double)1.0 / (double)getHeight())
{
for (double x = box.x; x <= box.x + box.width; x += (double)1.0 / (double)getWidth())
{
BarycentricTestResult testResult = BarycentricTestResult::test(a, b, c, x, y);
if (testResult.isInsideTriangle)
{
glm::vec3 interpolationP = interpolation(testResult.weight(), glm::vec3(a), glm::vec3(b), glm::vec3(c));
glm::vec3 interpolationC = interpolation(testResult.weight(), c0, c1, c2);
const glm::vec3 cc = vec3Correction(c0, c1, c2, p0.z, p1.z, p2.z, testResult);
const glm::vec3 pp = vec3Correction(a, b, c, p0.z, p1.z, p2.z, testResult);
glm::vec3 point(interpolationP.x, interpolationP.y, pp.z);
setColor(point, cc, depthFunc);
}
}
}
}
void Renderer::pipeline(const RenderPipeline& renderPipeLine)
{
int triangleCount = renderPipeLine.triangleCount;
for (int i = 0; i < triangleCount; i++)
{
const RasterizationData data0 = renderPipeLine.shader->vertexShader(renderPipeLine.vertexBuffer, 3 * i + 0);
const RasterizationData data1 = renderPipeLine.shader->vertexShader(renderPipeLine.vertexBuffer, 3 * i + 1);
const RasterizationData data2 = renderPipeLine.shader->vertexShader(renderPipeLine.vertexBuffer, 3 * i + 2);
assert(data0.extraData.size() == data1.extraData.size() == data2.extraData.size());
glm::vec4 a = divideByW(data0.position);
glm::vec4 b = divideByW(data1.position);
glm::vec4 c = divideByW(data2.position);
if (isValidTriangle(a, b, c) == false)
{
continue;
}
Rect box = Rect::boundingBox(a, b, c);
for (double y = box.y; y <= box.y + box.height; y += (double)1.0 / (double)getHeight())
{
for (double x = box.x; x <= box.x + box.width; x += (double)1.0 / (double)getWidth())
{
BarycentricTestResult testResult = BarycentricTestResult::test(a, b, c, x, y);
if (testResult.isInsideTriangle)
{
glm::vec3 interpolationP = interpolation(testResult.weight(), glm::vec3(a), glm::vec3(b), glm::vec3(c));
const glm::vec3 point = vec3Correction(a, b, c, data0.position.z, data1.position.z, data2.position.z, testResult);
float zAtScreenSapce = zCorrection(a.z, b.z, c.z, data0.position.z, data1.position.z, data2.position.z, testResult);
RasterizationData data;
data.position = glm::vec4(interpolationP, 1.0);
for (int i = 0; i < data0.extraData.size(); i++)
{
glm::vec4 interpolationData = interpolation(testResult.weight(), data0.extraData[i], data1.extraData[i], data2.extraData[i]);
interpolationData = vec4Correction(data0.extraData[i], data1.extraData[i], data2.extraData[i], data0.position.z, data1.position.z, data2.position.z, testResult);
data.extraData.push_back(interpolationData);
}
glm::vec4 color = renderPipeLine.shader->fragmentShader(data);
setColor(glm::vec3(point.x, point.y, zAtScreenSapce), color, renderPipeLine.depthFunc);
}
}
}
}
}
bool Renderer::isValidTriangle(const glm::vec2 a, const glm::vec2 b, const glm::vec2 c) const
{
double d0 = glm::distance(a, b);
double d1 = glm::distance(b, c);
double d2 = glm::distance(c, a);
if (d0 + d1 > d2 && glm::abs(d0 - d1) < d2)
{
return true;
}
return false;
}
| 28.031884 | 167 | 0.638197 | [
"vector"
] |
1de38018c4ffdac78d488e0239c6869c64319929 | 3,624 | cpp | C++ | src/Textdraw/CTextDrawMenu.cpp | maddinat0r/cpp-gamemode-samp | ee36f3f322502f6faa997647d562bf25863e7791 | [
"MIT"
] | 1 | 2021-05-31T11:10:12.000Z | 2021-05-31T11:10:12.000Z | src/Textdraw/CTextDrawMenu.cpp | maddinat0r/cpp-gamemode-samp | ee36f3f322502f6faa997647d562bf25863e7791 | [
"MIT"
] | null | null | null | src/Textdraw/CTextDrawMenu.cpp | maddinat0r/cpp-gamemode-samp | ee36f3f322502f6faa997647d562bf25863e7791 | [
"MIT"
] | 1 | 2020-10-17T18:27:00.000Z | 2020-10-17T18:27:00.000Z | #include <Textdraw/CTextDrawMenu.h>
#include <Textdraw/CTextDraw.h>
#include <Textdraw/CPlayerTextDraw.h>
#include <vector>
using std::vector;
template<class T>
bool CTextDrawMenu::AddTextDraw(T* textdraw, string name)
{
if(textdraw == nullptr)
return false;
if (name.empty())
{
m_Textdraws.push_back(textdraw);
return true;
}
else
{
for (auto &t : m_KeyedTextdraws)
if (boost::get<T *>(t.second) == textdraw)
return false;
return m_KeyedTextdraws.emplace(name, textdraw).second;
}
}
template bool CTextDrawMenu::AddTextDraw(CTextDraw* textdraw, string name);
template bool CTextDrawMenu::AddTextDraw(CPlayerTextDraw* textdraw, string name);
template<class T>
T *CTextDrawMenu::GetTextDraw(const char *name)
{
if(name == nullptr)
return nullptr;
auto it = m_KeyedTextdraws.find(name);
if (it != m_KeyedTextdraws.end())
return boost::get<T *>(it->second);
return nullptr;
}
template CTextDraw *CTextDrawMenu::GetTextDraw(const char *name);
template CPlayerTextDraw *CTextDrawMenu::GetTextDraw(const char *name);
void CTextDrawMenu::Show(unsigned int playerid)
{
for(auto &t : m_KeyedTextdraws)
ShowTextDraw(t.second, playerid);
for (auto &t : m_Textdraws)
ShowTextDraw(t, playerid);
}
void CTextDrawMenu::Hide(unsigned int playerid)
{
for (auto &t : m_KeyedTextdraws)
HideTextDraw(t.second, playerid);
for (auto &t : m_Textdraws)
HideTextDraw(t, playerid);
}
template<class T>
void CTextDrawMenu::DeleteAll(unsigned int playerid)
{
for (auto t = m_KeyedTextdraws.begin(); t != m_KeyedTextdraws.end(); ++t)
{
auto &textdraw = t->second;
if (textdraw.type() == typeid(T *))
{
if (typeid(T *) == typeid(CPlayerTextDraw *))
if (playerid != INVALID_PLAYER_ID && boost::get<CPlayerTextDraw *>(textdraw)->GetPlayerId() != playerid)
continue;
delete boost::get<T *>(textdraw);
t = m_KeyedTextdraws.erase(t);
}
}
for (auto t = m_Textdraws.begin(); t != m_Textdraws.end(); ++t)
{
auto &textdraw = *t;
if (textdraw.type() == typeid(T *))
{
if (typeid(T *) == typeid(CPlayerTextDraw *))
if (playerid != INVALID_PLAYER_ID && boost::get<CPlayerTextDraw *>(textdraw)->GetPlayerId() != playerid)
continue;
delete boost::get<T *>(textdraw);
t = m_Textdraws.erase(t);
}
}
}
template void CTextDrawMenu::DeleteAll<CTextDraw>(unsigned int playerid);
template void CTextDrawMenu::DeleteAll<CPlayerTextDraw>(unsigned int playerid);
void CTextDrawMenu::ShowTextDraw(const Textdraws_t &textdraw, unsigned int playerid)
{
if (playerid != INVALID_PLAYER_ID && textdraw.type() == typeid(CPlayerTextDraw *))
{
auto *td = boost::get<CPlayerTextDraw *>(textdraw);
if (td->GetPlayerId() == playerid)
td->Show();
}
else
{
auto *td = boost::get<CTextDraw *>(textdraw);
if (playerid == INVALID_PLAYER_ID)
td->ShowForAll();
else
td->ShowForPlayer(playerid);
}
}
void CTextDrawMenu::HideTextDraw(const Textdraws_t &textdraw, unsigned int playerid)
{
if (playerid != INVALID_PLAYER_ID && textdraw.type() == typeid(CPlayerTextDraw *))
{
auto *td = boost::get<CPlayerTextDraw *>(textdraw);
if (td->GetPlayerId() == playerid)
td->Hide();
}
else
{
auto *td = boost::get<CTextDraw *>(textdraw);
if (playerid == INVALID_PLAYER_ID)
td->HideForAll();
else
td->HideForPlayer(playerid);
}
}
void CTextDrawMenu::DestroyTextDraw(const Textdraws_t &textdraw)
{
if (textdraw.type() == typeid(CPlayerTextDraw *))
{
auto *td = boost::get<CPlayerTextDraw *>(textdraw);
td->Destroy();
delete td;
}
else
{
auto *td = boost::get<CTextDraw *>(textdraw);
td->Destroy();
delete td;
}
}
| 23.686275 | 108 | 0.690397 | [
"vector"
] |
1de9bf2bfdf7616a5be95c6721a74dc6c4d0edd0 | 3,434 | cpp | C++ | src/Inciter/AMR/util.cpp | franjgonzalez/Quinoa | 411eb8815e92618c563881b784e287e2dd916f89 | [
"RSA-MD"
] | null | null | null | src/Inciter/AMR/util.cpp | franjgonzalez/Quinoa | 411eb8815e92618c563881b784e287e2dd916f89 | [
"RSA-MD"
] | null | null | null | src/Inciter/AMR/util.cpp | franjgonzalez/Quinoa | 411eb8815e92618c563881b784e287e2dd916f89 | [
"RSA-MD"
] | null | null | null | #include <stddef.h>
#include <sstream>
#include "util.hpp"
#include "AMR/AMR_types.hpp"
namespace AMR {
namespace util {
/**
* @brief Split a string based on a given delimiter
*
* @param s The string to split
* @param delim The delimiter to use
* @param elems The vector which will be filled
*/
void split(const std::string &s, char delim,
std::vector<std::string> &elems)
{
std::stringstream ss;
ss.str(s);
std::string item;
while (std::getline(ss, item, delim)) {
elems.push_back(item);
}
}
/**
* @brief Build a vector of split strings based on a delmiter
*
* @param s The string to split
* @param delim The delimiter to use
*
* @return A vector split by delim. Does not handle empty tokens
*/
std::vector<std::string> split(const std::string &s, char delim) {
std::vector<std::string> elems;
split(s, delim, elems);
return elems;
}
/**
* @brief function to find the mid point betwen two points (nodes)
*
* @param edge_node_A First node/point
* @param edge_node_B Second node/point
*
* @return The mid point between the two nodes
*/
coordinate_t find_mid_point(
coordinate_t edge_node_A,
coordinate_t edge_node_B
)
{
coordinate_t mid_point;
for(size_t i = 0; i < DIMENSION; i++)
{
mid_point[i] = (edge_node_A[i]+edge_node_B[i])/2.0;
}
return mid_point;
}
/**
* @brief Function to find the mid point between two points (nodes)
*
* @param x1 x coord of first point
* @param y1 y coord of first point
* @param z1 z coord of first point
* @param x2 x coord of second point
* @param y2 y coord of second point
* @param z2 z coord of second point
*
* @return The mid point between the two nodes
*/
coordinate_t find_mid_point(real_t x1, real_t y1,
real_t z1, real_t x2, real_t y2, real_t z2)
{
coordinate_t mid_point;
mid_point[0] = (x1+x2)/2.0;
mid_point[1] = (y1+y2)/2.0;
mid_point[2] = (z1+z2)/2.0;
return mid_point;
}
/*
real_t jacobian(size_t a, size_t b, size_t c, size_t d)
{
std::cout << "A: x " << m_x[a] << " y " << m_y[a] << " z " << m_z[a] << std::endl;
std::cout << "b: x " << m_x[b] << " y " << m_y[b] << " z " << m_z[b] << std::endl;
std::cout << "c: x " << m_x[c] << " y " << m_y[c] << " z " << m_z[c] << std::endl;
std::cout << "d: x " << m_x[d] << " y " << m_y[d] << " z " << m_z[d] << std::endl;
const std::array< tk::real, 3 > ba = {{ m_x[b]-m_x[a], m_y[b]-m_y[a], m_z[b]-m_z[a] }};
const std::array< tk::real, 3 > ca = {{ m_x[c]-m_x[a], m_y[c]-m_y[a], m_z[c]-m_z[a] }};
const std::array< tk::real, 3 > da = {{ m_x[d]-m_x[a], m_y[d]-m_y[a], m_z[d]-m_z[a] }};
const auto J = tk::triple( ba, ca, da );
return J;
}*/
}
}
| 30.389381 | 98 | 0.474956 | [
"vector"
] |
1dea37a61e745dd4f8c00e9736099ee5f6618c52 | 3,973 | cpp | C++ | sferes/tests/ea/cmaes.cpp | Evolving-AI-Lab/innovation-engine | 58c7fcc3cbe3d6f8f59f87d95bdb5f2302f425ba | [
"MIT"
] | 31 | 2015-09-20T03:03:29.000Z | 2022-01-25T06:50:20.000Z | sferes/tests/ea/cmaes.cpp | Evolving-AI-Lab/innovation-engine | 58c7fcc3cbe3d6f8f59f87d95bdb5f2302f425ba | [
"MIT"
] | 1 | 2016-08-11T07:24:50.000Z | 2016-08-17T01:19:57.000Z | sferes/tests/ea/cmaes.cpp | Evolving-AI-Lab/innovation-engine | 58c7fcc3cbe3d6f8f59f87d95bdb5f2302f425ba | [
"MIT"
] | 10 | 2015-11-15T01:52:25.000Z | 2018-06-11T23:42:58.000Z | //| This file is a part of the sferes2 framework.
//| Copyright 2009, ISIR / Universite Pierre et Marie Curie (UPMC)
//| Main contributor(s): Jean-Baptiste Mouret, mouret@isir.fr
//|
//| This software is a computer program whose purpose is to facilitate
//| experiments in evolutionary computation and evolutionary robotics.
//|
//| This software is governed by the CeCILL license under French law
//| and abiding by the rules of distribution of free software. You
//| can use, modify and/ or redistribute the software under the terms
//| of the CeCILL license as circulated by CEA, CNRS and INRIA at the
//| following URL "http://www.cecill.info".
//|
//| As a counterpart to the access to the source code and rights to
//| copy, modify and redistribute granted by the license, users are
//| provided only with a limited warranty and the software's author,
//| the holder of the economic rights, and the successive licensors
//| have only limited liability.
//|
//| In this respect, the user's attention is drawn to the risks
//| associated with loading, using, modifying and/or developing or
//| reproducing the software by the user in light of its specific
//| status of free software, that may mean that it is complicated to
//| manipulate, and that also therefore means that it is reserved for
//| developers and experienced professionals having in-depth computer
//| knowledge. Users are therefore encouraged to load and test the
//| software's suitability as regards their requirements in conditions
//| enabling the security of their systems and/or data to be ensured
//| and, more generally, to use and operate it in the same conditions
//| as regards security.
//|
//| The fact that you are presently reading this means that you have
//| had knowledge of the CeCILL license and that you accept its terms.
#ifndef NO_PARALLEL
#define NO_PARALLEL
#endif
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE cmaes
#include <boost/test/unit_test.hpp>
#include <cmath>
#include <iostream>
#include <Eigen/Core>
#include <sferes/phen/parameters.hpp>
#include <sferes/gen/float.hpp>
#include <sferes/ea/cmaes.hpp>
#include <sferes/eval/eval.hpp>
#include <sferes/stat/best_fit.hpp>
#include <sferes/eval/parallel.hpp>
#include <sferes/modif/dummy.hpp>
using namespace sferes;
struct Params {
struct pop {
SFERES_CONST size_t size = 1;//not used by CMAES
SFERES_CONST unsigned nb_gen = 650;
SFERES_CONST int dump_period = -1;
};
struct cmaes {
SFERES_CONST float sigma = 0.5f;
SFERES_CONST float max_value = -1e-10;
};
struct parameters {
SFERES_CONST float min = 0.0f;
SFERES_CONST float max = 1.0f;
};
};
float felli(const std::vector<float>& xx) {
Eigen::VectorXf x = Eigen::VectorXf::Zero(xx.size());
for (size_t i = 0; i < xx.size(); ++i)
x[i] = xx[i];
Eigen::VectorXf v = Eigen::VectorXf::Zero(x.size());
for (size_t i = 0; i < v.size(); ++i)
v[i] = powf(1e6, i / (x.size() - 1.0f));
return v.dot((x.array() * x.array()).matrix());
}
SFERES_FITNESS(FitElli, sferes::fit::Fitness) {
public:
FitElli(const FitElli& f) {
assert(0);
BOOST_ERROR("copy constructors should be useless");
}
FitElli& operator=(const FitElli& f) {
BOOST_ERROR("= operator should be useless");
return *this;
}
FitElli() : _this(this) {}
template<typename Indiv>
void eval(Indiv& ind) {
this->_value = -felli(ind.data());
}
FitElli* _this;
};
BOOST_AUTO_TEST_CASE(test_cmaes) {
srand(time(0));
typedef gen::Float<10, Params> gen_t;
typedef phen::Parameters<gen_t, FitElli<Params>, Params> phen_t;
typedef eval::Parallel<Params> eval_t;
typedef boost::fusion::vector<stat::BestFit<phen_t, Params> > stat_t;
typedef modif::Dummy<> modifier_t;
typedef ea::Cmaes<phen_t, eval_t, stat_t, modifier_t, Params> ea_t;
ea_t ea;
ea.run();
float best = ea.stat<0>().best()->fit().value();
std::cout<<"best fit (cmaes):"<<best<<std::endl;
BOOST_CHECK(best > -1e-3);
}
| 32.834711 | 72 | 0.707526 | [
"vector"
] |
1ded5a298a4aa10f4d71f17286535ae6bbfc9d68 | 2,063 | cpp | C++ | modules/cvv/src/view/defaultfilterview.cpp | Nondzu/opencv_contrib | 0b0616a25d4239ee81fda965818b49b721620f56 | [
"BSD-3-Clause"
] | 7,158 | 2016-07-04T22:19:27.000Z | 2022-03-31T07:54:32.000Z | modules/cvv/src/view/defaultfilterview.cpp | Nondzu/opencv_contrib | 0b0616a25d4239ee81fda965818b49b721620f56 | [
"BSD-3-Clause"
] | 2,184 | 2016-07-05T12:04:14.000Z | 2022-03-30T19:10:12.000Z | modules/cvv/src/view/defaultfilterview.cpp | Nondzu/opencv_contrib | 0b0616a25d4239ee81fda965818b49b721620f56 | [
"BSD-3-Clause"
] | 5,535 | 2016-07-06T12:01:10.000Z | 2022-03-31T03:13:24.000Z | #include <QHBoxLayout>
#include <QVBoxLayout>
#include <QGridLayout>
#include <QWidget>
#include "defaultfilterview.hpp"
#include "../qtutil/accordion.hpp"
#include "../qtutil/zoomableimageoptpanel.hpp"
#include "../qtutil/zoomableimage.hpp"
#include "../qtutil/synczoomwidget.hpp"
#include "../qtutil/histogram.hpp"
#include "../qtutil/histogramoptpanel.hpp"
#include "../util/util.hpp"
namespace cvv
{
namespace view
{
DefaultFilterView::DefaultFilterView(const std::vector<cv::Mat> &images,
QWidget *parent)
: FilterView( parent )
{
auto layout = util::make_unique<QHBoxLayout>();
auto accor = util::make_unique<qtutil::Accordion>();
auto imwid = util::make_unique<QWidget>();
auto imageLayout = util::make_unique<QGridLayout>();
accor->setMinimumWidth(250);
accor->setMaximumWidth(250);
std::vector<qtutil::ZoomableImage*> syncVec;
size_t count = 0;
for (auto& image : images)
{
auto zoomIm = util::make_unique<qtutil::ZoomableImage>();
syncVec.push_back(zoomIm.get());
accor->insert(
QString("Image Information: ") + QString::number(count),
util::make_unique<qtutil::ZoomableOptPanel>(*zoomIm));
zoomIm->setMat(image);
auto histogram = util::make_unique<qtutil::Histogram>();
histogram->setMat(image);
histogram->setVisible(false);
connect(zoomIm.get(), SIGNAL(updateArea(QRectF, qreal)), histogram.get(), SLOT(setArea(QRectF, qreal)));
accor->insert(QString("Histogram: ") + QString::number(count), util::make_unique<qtutil::HistogramOptPanel>(*histogram));
imageLayout->addWidget(zoomIm.release(), 0, count);
imageLayout->addWidget(histogram.release(), 1, count);
count++;
}
accor->insert("Zoom synchronization",
util::make_unique<qtutil::SyncZoomWidget>(syncVec), true, 0);
imwid->setLayout(imageLayout.release());
layout->addWidget(accor.release());
layout->addWidget(imwid.release());
setLayout(layout.release());
//images should be seen fully at beginning
for(auto& zoomableImage: syncVec)
{
zoomableImage->showFullImage();
}
}
}
} // namespaces
| 26.448718 | 129 | 0.711585 | [
"vector"
] |
1df7647e5b0c91d2a781194e296be4254a099780 | 10,725 | cpp | C++ | src/acQGanttChartWindow.cpp | nfogh/common-src-AMDTApplicationComponents | 9fc0fa073b8af5d8552eb331fc47ede8becca642 | [
"MIT"
] | 1 | 2017-01-28T14:14:18.000Z | 2017-01-28T14:14:18.000Z | src/acQGanttChartWindow.cpp | nfogh/common-src-AMDTApplicationComponents | 9fc0fa073b8af5d8552eb331fc47ede8becca642 | [
"MIT"
] | null | null | null | src/acQGanttChartWindow.cpp | nfogh/common-src-AMDTApplicationComponents | 9fc0fa073b8af5d8552eb331fc47ede8becca642 | [
"MIT"
] | 2 | 2018-10-26T09:34:00.000Z | 2019-11-01T23:05:53.000Z | //------------------------------ acQGanttChartWindow.cpp ------------------------------
// Ignore compiler warnings:
#include <AMDTBaseTools/Include/gtIgnoreCompilerWarnings.h>
// Qt:
#include <QtGui>
// wxWindows pre compiled header:
#include <AMDTApplicationComponents/Include/acWxWidgetsIncludes.h>
// Infra:
#include <AMDTBaseTools/Include/gtAssert.h>
#include <AMDTBaseTools/Include/gtString.h>
#include <AMDTBaseTools/Include/gtStringTokenizer.h>
// Local:
#include <AMDTApplicationComponents/Include/acQGanttChartWindow.h>
#include <inc/acOpenGLChartWindowResources.h>
// ---------------------------------------------------------------------------
// Name: acQGanttChartWindow::acQGanttChartWindow
// Description: Constructor
// Arguments: QWidget* pParent
// QColor bgColor
// Author: Sigal Algranaty
// Date: 15/12/2011
// ---------------------------------------------------------------------------
acQGanttChartWindow::acQGanttChartWindow(QWidget* pParent, QColor bgColor)
: qcTimeline(pParent)
{
// Set the background color:
_bgColor = bgColor;
// Connect the item clicked signal to its slot:
bool rc = connect(this, SIGNAL(itemClicked(qcTimelineItem*)), this, SLOT(itemClicked(qcTimelineItem*)));
GT_ASSERT(rc);
}
// ---------------------------------------------------------------------------
// Name: acQGanttChartWindow::~acQGanttChartWindow
// Description: Destructor
// Author: Sigal Algranaty
// Date: 15/12/2011
// ---------------------------------------------------------------------------
acQGanttChartWindow::~acQGanttChartWindow()
{
}
// ---------------------------------------------------------------------------
// Name: acQGanttChartWindow::clearAllData
// Description: Clears all the data from the vectors
// Author: Sigal Algranaty
// Date: 15/12/2011
// ---------------------------------------------------------------------------
void acQGanttChartWindow::clearAllData()
{
_backgroundSectionsData.clear();
_barsDataByBranch.deleteElementsAndClear();
updateGanttChart();
}
// ---------------------------------------------------------------------------
// Name: acQGanttChartWindow::updateGanttChart
// Description: Update the gantt chart OpenGL data after loading series and other
// data
// Author: Sigal Algranaty
// Date: 15/12/2011
// ---------------------------------------------------------------------------
void acQGanttChartWindow::updateGanttChart()
{
// Reset the chart:
reset();
// Collect the max and min values:
gtUInt64 minValue = 0, maxValue = 0;
// Add the required branches for the time line:
for (int branchIndex = 0 ; branchIndex < (int)_backgroundSectionsData.size(); branchIndex++)
{
// Get the current branch data:
const acQGanttChartBackgroundSectionData& ganttChartData = _backgroundSectionsData[branchIndex];
// Create new branch:
qcTimelineBranch* pTimelineBranch = new qcTimelineBranch;
GT_ASSERT_ALLOCATION(pTimelineBranch);
// Set the branch text:
pTimelineBranch->setText(ganttChartData._label.asASCIICharArray());
// Add the branch:
addBranch(pTimelineBranch);
// Get the vector of the chart bar data for this branch:
gtVector<acQGanttChartBarData>* pBranchVector = _barsDataByBranch[branchIndex];
GT_IF_WITH_ASSERT(pBranchVector != NULL)
{
// Add each of the branch time lines:
for (int timelineIndex = 0; timelineIndex < (int)pBranchVector->size(); timelineIndex ++)
{
// Get the current command:
acQGanttChartBarData currentTimelineData = (*pBranchVector)[timelineIndex];
// Create new time line:
gtUInt64 barStartInMs = currentTimelineData._barStart;
gtUInt64 barEndInMs = currentTimelineData._barEnd;
qcTimelineItem* pTimeLine = new qcTimelineItem(barStartInMs, barEndInMs);
GT_ASSERT_ALLOCATION(pTimeLine);
// Check if max value should increase:
maxValue = max(currentTimelineData._barEnd, maxValue);
// Set the time line bg color:
pTimeLine->setBackgroundColor(currentTimelineData._barColor);
pTimeLine->setText(currentTimelineData._label.asASCIICharArray());
// Add this time line to the branch:
pTimelineBranch->addTimelineItem(pTimeLine);
}
}
}
}
// ---------------------------------------------------------------------------
// Name: acQGanttChartWindow::setNumberOfBranches
// Description: Sets the number of branches in the chart by assigning that many
// items in the relevant vectors
// Author: Sigal Algranaty
// Date: 15/12/2011
// ---------------------------------------------------------------------------
void acQGanttChartWindow::setNumberOfBranches(int numberOfBranches)
{
// Clear any former data:
_backgroundSectionsData.clear();
_barsDataByBranch.deleteElementsAndClear();
// Items at negative line numbers will always be off screen:
acQGanttChartBackgroundSectionData defaultBackgroundSection(_bgColor);
// Add the data:
for (int i = 0; i < numberOfBranches; i++)
{
// Add a background data:
_backgroundSectionsData.push_back(defaultBackgroundSection);
// Create a new branch data:
gtVector<acQGanttChartBarData>* pCurrentBranchVec = new gtVector<acQGanttChartBarData>;
GT_ASSERT_ALLOCATION(pCurrentBranchVec);
_barsDataByBranch.push_back(pCurrentBranchVec);
}
}
// ---------------------------------------------------------------------------
// Name: acQGanttChartWindow::setSeriesData
// Description: Sets the background color of a series
// Author: Sigal Algranaty
// Date: 15/12/2011
// ---------------------------------------------------------------------------
void acQGanttChartWindow::setBranchData(int seriesIndex, const QColor& bgCol, const gtString& toolTip, const gtString& label)
{
// Sanity check:
int numberOfBackgroundSections = (int)_backgroundSectionsData.size();
GT_IF_WITH_ASSERT((seriesIndex >= 0) && (seriesIndex < numberOfBackgroundSections))
{
// Set the color and tooltip:
acQGanttChartBackgroundSectionData& sectionBackgroundData = _backgroundSectionsData[seriesIndex];
sectionBackgroundData._sectionColor = bgCol;
sectionBackgroundData._toolTip = toolTip;
sectionBackgroundData._label = label;
}
}
// ---------------------------------------------------------------------------
// Name: acQGanttChartWindow::addBarToSeries
// Description: Adds a bar to a series
// Author: Sigal Algranaty
// Date: 15/12/2011
// ---------------------------------------------------------------------------
void acQGanttChartWindow::addTimelineToBranch(int branchIndex, gtUInt64 barStart, gtUInt64 barEnd, const QColor& barColor, int originalIndex, const gtString& label, const gtString& tooltip)
{
// Sanity check index:
int numberOfBranches = (int)_barsDataByBranch.size();
GT_IF_WITH_ASSERT((branchIndex >= 0) && (branchIndex < numberOfBranches))
{
// Sanity check pointer:
gtVector<acQGanttChartBarData>* pBranchVector = _barsDataByBranch[branchIndex];
GT_IF_WITH_ASSERT(pBranchVector != NULL)
{
// Make sure the bar will be visible:
if (barStart < barEnd)
{
// Create and add the item:
acQGanttChartBarData newBarData(barStart, barEnd, barColor, originalIndex, label, tooltip);
pBranchVector->push_back(newBarData);
}
}
}
}
// ---------------------------------------------------------------------------
// Name: acQGanttChartWindow::clearSeriesData
// Description: Clear all the bars from a series
// Author: Sigal Algranaty
// Date: 15/12/2011
// ---------------------------------------------------------------------------
void acQGanttChartWindow::clearBranchData(int seriesIndex)
{
// Sanity check index:
int numberOfSeries = (int)_barsDataByBranch.size();
GT_IF_WITH_ASSERT((seriesIndex >= 0) && (seriesIndex < numberOfSeries))
{
// Sanity check pointer:
gtVector<acQGanttChartBarData>* pSeriesVector = _barsDataByBranch[seriesIndex];
GT_IF_WITH_ASSERT(pSeriesVector != NULL)
{
// Clear the vector:
pSeriesVector->clear();
}
}
}
// ---------------------------------------------------------------------------
// Name: acQGanttChartWindow::chartHasData
// Description: Returns true iff the chart has any data
// Author: Uri Shomroni
// Date: 15/3/2010
// ---------------------------------------------------------------------------
bool acQGanttChartWindow::chartHasData() const
{
bool retVal = false;
// Go over all the series:
int numberOfSeries = (int)_barsDataByBranch.size();
for (int i = 0; i < numberOfSeries; i++)
{
// Pointer sanity check:
const gtVector<acQGanttChartBarData>* pCurrentSeries = _barsDataByBranch[i];
GT_IF_WITH_ASSERT(pCurrentSeries != NULL)
{
// If this series has at least one bar:
if (pCurrentSeries->size() > 0)
{
// There is data in the chart, no need to look further:
retVal = true;
break;
}
}
}
return retVal;
}
// ---------------------------------------------------------------------------
// Name: acQGanttChartWindow::itemClicked
// Description:
// Arguments: qcTimelineItem* pTimelineItem
// Return Val: void
// Author: Sigal Algranaty
// Date: 20/12/2011
// ---------------------------------------------------------------------------
void acQGanttChartWindow::itemClicked(qcTimelineItem* pTimelineItem)
{
// Sanity check:
GT_IF_WITH_ASSERT(pTimelineItem != NULL)
{
// Get the timeline index:
int timelineIndex = pTimelineItem->index();
// Get the parent branch:
qcTimelineBranch* pTimelineBranch = pTimelineItem->parentBranch();
GT_IF_WITH_ASSERT(pTimelineBranch != NULL)
{
// Check what is this timeline item, and which branch / timeline index it represents:
int branchIndex = pTimelineBranch->rowIndex();
// Emit the timeline clicked signal:
emit timelineClicked(branchIndex, timelineIndex);
}
}
}
| 37.764085 | 189 | 0.562611 | [
"vector"
] |
1df87f7053c4f92d81ee092fb918a13866c7b923 | 6,666 | cc | C++ | src/Dataflow/Network/Port.cc | Nahusa/SCIRun | c54e714d4c7e956d053597cf194e07616e28a498 | [
"MIT"
] | 1 | 2019-05-30T06:00:15.000Z | 2019-05-30T06:00:15.000Z | src/Dataflow/Network/Port.cc | manual123/SCIRun | 3816b1dc4ebd0c5bd4539b7e50e08592acdac903 | [
"MIT"
] | null | null | null | src/Dataflow/Network/Port.cc | manual123/SCIRun | 3816b1dc4ebd0c5bd4539b7e50e08592acdac903 | [
"MIT"
] | null | null | null | /*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2015 Scientific Computing and Imaging Institute,
University of Utah.
License for the specific language governing rights and limitations under
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.
*/
/// @todo Documentation Dataflow/Network/Port.cc
#include <Dataflow/Network/Port.h>
#include <Core/Datatypes/Datatype.h>
#include <Core/Utils/Exception.h>
#include <Dataflow/Network/Connection.h>
#include <Dataflow/Network/ModuleInterface.h>
#include <Dataflow/Network/ModuleDescription.h>
#include <Dataflow/Network/DataflowInterfaces.h>
#include <Core/Logging/Log.h>
using namespace SCIRun::Dataflow::Networks;
using namespace SCIRun::Core::Datatypes;
using namespace SCIRun::Core::Logging;
Port::Port(ModuleInterface* module, const ConstructionParams& params)
: module_(module), index_(0), id_(params.id_), typeName_(params.type_name), portName_(params.port_name), colorName_(PortColorLookup::toColor(params.type_name)),
connectionCountIncreasedFlag_(false)
{
ENSURE_NOT_NULL(module_, "port cannot have null module");
if (typeName_.empty() || portName_.empty() || colorName_.empty())
THROW_INVALID_ARGUMENT("port has empty metadata");
}
Port::~Port()
{
}
void Port::attach(Connection* conn)
{
connections_.push_back(conn);
connectionCountIncreasedFlag_ = true;
}
bool Port::hasConnectionCountIncreased() const
{
auto val = connectionCountIncreasedFlag_;
connectionCountIncreasedFlag_ = false;
return val;
}
void Port::detach(Connection* conn)
{
auto pos = std::find(connections_.begin(), connections_.end(), conn);
if (pos == connections_.end())
{
LOG_DEBUG("{} Port::detach: Connection not found", id().toString());
}
connections_.erase(pos);
}
Connection* Port::connection(size_t i) const
{
return connections_[i];
}
boost::optional<ConnectionId> Port::firstConnectionId() const
{
return !connections_.empty() ? connections_[0]->id_ : boost::optional<ConnectionId>();
}
void Port::setIndex(size_t index)
{
index_ = index;
}
size_t Port::nconnections() const
{
return connections_.size();
}
ModuleId Port::getUnderlyingModuleId() const
{
return module_->get_id();
}
size_t Port::getIndex() const
{
return index_;
}
ModuleStateHandle Port::moduleState() const
{
return module_->get_state();
}
InputPort::InputPort(ModuleInterface* module, const ConstructionParams& params, DatatypeSinkInterfaceHandle sink)
: Port(module, params), sink_(sink), isDynamic_(params.isDynamic_)
{
}
InputPort::~InputPort()
{
}
DatatypeSinkInterfaceHandle InputPort::sink() const
{
return sink_;
}
DatatypeHandleOption InputPort::getData() const
{
if (0 == nconnections())
return DatatypeHandleOption();
sink_->waitForData();
return sink_->receive();
}
void InputPort::attach(Connection* conn)
{
if (connections_.size() > 0)
THROW_INVALID_ARGUMENT("static input ports accept at most one connection");
Port::attach(conn);
}
void InputPort::detach(Connection* conn)
{
if (sink_)
sink_->invalidateProvider();
Port::detach(conn);
}
InputPortInterface* InputPort::clone() const
{
DatatypeSinkInterfaceHandle sink(sink_->clone());
if (!isDynamic_)
THROW_INVALID_ARGUMENT("Cannot clone non-dynamic port.");
PortId cloneId(id_.id + 1, id_.name);
return new InputPort(module_, ConstructionParams(cloneId, typeName_, isDynamic_), sink);
}
bool InputPort::hasChanged() const
{
return sink()->hasChanged();
}
boost::signals2::connection InputPort::connectDataOnPortHasChanged(const DataOnPortHasChangedSignalType::slot_type& subscriber)
{
return sink()->connectDataHasChanged([this, subscriber] (DatatypeHandle data)
{
if (this->shouldTriggerDataChange())
{
subscriber(this->id(), data);
}
});
}
bool InputPort::shouldTriggerDataChange() const
{
if (connections_.empty())
return true;
return !(*connections_.begin())->disabled();
}
void InputPort::resendNewDataSignal()
{
sink()->forceFireDataHasChanged();
}
boost::optional<std::string> InputPort::connectedModuleId() const
{
if (connections_.empty())
return boost::none;
return connections_[0]->oport_->getUnderlyingModuleId().id_;
}
ModuleStateHandle InputPort::stateFromConnectedModule() const
{
if (connections_.empty())
return nullptr;
return connections_[0]->oport_->moduleState();
}
OutputPort::OutputPort(ModuleInterface* module, const ConstructionParams& params, DatatypeSourceInterfaceHandle source)
: Port(module, params), source_(source)
{
}
OutputPort::~OutputPort()
{
}
void OutputPort::sendData(DatatypeHandle data)
{
source_->cacheData(data);
if (0 == nconnections())
return;
for (auto c : connections_)
{
if (c && c->iport_)
{
source_->send(c->iport_->sink());
}
}
connectionCountIncreasedFlag_ = false;
}
bool OutputPort::hasData() const
{
if (!source_)
return false;
auto ret = source_->hasData();
LOG_TRACE("{} OutputPort::hasData returns {}", id().toString(), ret);
return ret;
}
void OutputPort::attach(Connection* conn)
{
if (hasData() && conn && conn->iport_ && get_typename() != "Geometry")
{
source_->send(conn->iport_->sink());
}
Port::attach(conn);
}
PortDataDescriber OutputPort::getPortDataDescriber() const
{
return [this]() { return source_->describeData(); };
}
boost::signals2::connection OutputPort::connectConnectionFeedbackListener(const ConnectionFeedbackSignalType::slot_type& subscriber)
{
return cxnFeedback_.connect(subscriber);
}
void OutputPort::sendConnectionFeedback(const ModuleFeedback& info)
{
cxnFeedback_(info);
}
| 25.06015 | 162 | 0.734923 | [
"geometry"
] |
1dfb3ae2f4fdede6a489934642bc8de43e1d4674 | 5,879 | hpp | C++ | include/natalie/vector.hpp | tekknolagi/natalie | 0e31cb0b0357fed20ecfdb71f24f9bc94195e1d1 | [
"MIT"
] | null | null | null | include/natalie/vector.hpp | tekknolagi/natalie | 0e31cb0b0357fed20ecfdb71f24f9bc94195e1d1 | [
"MIT"
] | null | null | null | include/natalie/vector.hpp | tekknolagi/natalie | 0e31cb0b0357fed20ecfdb71f24f9bc94195e1d1 | [
"MIT"
] | null | null | null | #pragma once
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include "natalie/gc.hpp"
#define NAT_VECTOR_GROW_FACTOR 2
namespace Natalie {
template <typename T>
struct Vector : public gc {
Vector() { }
Vector(ssize_t initial_capacity, T filler)
: m_size { initial_capacity }
, m_capacity { initial_capacity }
, m_data { static_cast<T *>(malloc(sizeof(T) * initial_capacity)) } {
fill(0, initial_capacity, filler);
}
Vector(const Vector &other)
: m_size { other.m_size }
, m_capacity { other.m_size }
, m_data { static_cast<T *>(malloc(sizeof(T) * m_size)) } {
memcpy(m_data, other.m_data, sizeof(T) * m_size);
}
Vector slice(ssize_t offset, ssize_t count = -1) {
if (count == -1 && m_size >= offset)
count = m_size - offset;
auto size = count;
auto capacity = size;
T *data = nullptr;
if (offset >= 0 && count >= 0 && m_size >= offset + count) {
if constexpr (NAT_VECTOR_GROW_FACTOR == 2) {
--capacity;
for (auto i = 0; i < 64; i += 4)
capacity |= capacity >> i;
++capacity;
} else {
capacity /= NAT_VECTOR_GROW_FACTOR;
++capacity;
capacity *= NAT_VECTOR_GROW_FACTOR;
}
data = static_cast<T *>(malloc(sizeof(T) * capacity));
memcpy(data, m_data + offset, sizeof(T) * size);
} else {
// FIXME: We should probably say something here.
size = 0;
capacity = 0;
data = nullptr;
}
return { size, capacity, data };
}
Vector &operator=(Vector &&other) {
m_size = other.m_size;
m_capacity = other.m_size;
m_data = other.m_data;
other.m_data = nullptr;
other.m_size = 0;
other.m_capacity = 0;
return *this;
}
~Vector() {
if (m_data)
free(m_data);
}
T &operator[](ssize_t index) const {
return m_data[index];
}
void push(T val) {
ssize_t len = m_size;
if (m_size >= m_capacity) {
grow_at_least(m_size + 1);
}
m_size++;
m_data[len] = val;
}
void push_front(T val) {
if (m_size >= m_capacity) {
grow_at_least(m_size + 1);
}
m_size++;
for (ssize_t i = m_size - 1; i > 0; i--) {
m_data[i] = m_data[i - 1];
}
m_data[0] = val;
}
ssize_t is_empty() const { return m_size == 0; }
ssize_t size() const { return m_size; }
ssize_t capacity() const { return m_capacity; }
T *data() { return m_data; }
void fill(ssize_t from, ssize_t to_exclusive, T filler) {
assert(from >= 0);
assert(to_exclusive <= m_size);
for (ssize_t i = from; i < to_exclusive; i++) {
m_data[i] = filler;
}
}
void set_size(ssize_t new_size) {
assert(new_size <= m_size);
grow(new_size);
m_size = new_size;
}
void set_size(ssize_t new_size, T filler) {
grow(new_size);
ssize_t old_size = m_size;
m_size = new_size;
fill(old_size, new_size, filler);
}
void set_capacity(ssize_t new_size) {
grow_at_least(new_size);
}
class iterator {
public:
iterator(T *ptr)
: m_ptr { ptr } { }
iterator operator++() {
m_ptr++;
return *this;
}
iterator operator++(int _) {
iterator i = *this;
m_ptr++;
return i;
}
T &operator*() { return *m_ptr; }
T *operator->() { return m_ptr; }
friend bool operator==(const iterator &i1, const iterator &i2) {
return i1.m_ptr == i2.m_ptr;
}
friend bool operator!=(const iterator &i1, const iterator &i2) {
return i1.m_ptr != i2.m_ptr;
}
private:
T *m_ptr;
};
iterator begin() {
return iterator { m_data };
}
iterator end() {
return iterator { m_data + m_size };
}
struct SortComparator {
void *data;
bool (*cmp)(void *, T, T);
};
void sort(SortComparator cmp) {
quicksort(0, m_size - 1, cmp);
}
private:
Vector(ssize_t size, ssize_t capacity, T *data)
: m_size(size)
, m_capacity(capacity)
, m_data(data) { }
void grow(ssize_t capacity) {
m_data = static_cast<T *>(realloc(m_data, sizeof(T) * capacity));
m_capacity = capacity;
}
void grow_at_least(ssize_t min_capacity) {
if (m_capacity >= min_capacity) {
return;
}
if (m_capacity > 0 && min_capacity <= m_capacity * NAT_VECTOR_GROW_FACTOR) {
grow(m_capacity * NAT_VECTOR_GROW_FACTOR);
} else {
grow(min_capacity);
}
}
void quicksort(int start, int end, SortComparator cmp) {
if (start >= end) return;
int p_index = quicksort_partition(start, end, cmp);
quicksort(start, p_index - 1, cmp);
quicksort(p_index + 1, end, cmp);
}
int quicksort_partition(int start, int end, SortComparator cmp) {
T pivot = m_data[end];
int p_index = start;
T temp;
for (int i = start; i < end; i++) {
if (cmp.cmp(cmp.data, m_data[i], pivot)) {
temp = m_data[i];
m_data[i] = m_data[p_index];
m_data[p_index] = temp;
p_index++;
}
}
temp = m_data[end];
m_data[end] = m_data[p_index];
m_data[p_index] = temp;
return p_index;
}
ssize_t m_size { 0 };
ssize_t m_capacity { 0 };
T *m_data { nullptr };
};
}
| 25.450216 | 84 | 0.514373 | [
"vector"
] |
1dfd204af04b02eb849281a12f9245e2df23b5f0 | 4,052 | cpp | C++ | shared/source/os_interface/windows/driver_info_windows.cpp | mattcarter2017/compute-runtime | 1f52802aac02c78c19d5493dd3a2402830bbe438 | [
"Intel",
"MIT"
] | null | null | null | shared/source/os_interface/windows/driver_info_windows.cpp | mattcarter2017/compute-runtime | 1f52802aac02c78c19d5493dd3a2402830bbe438 | [
"Intel",
"MIT"
] | null | null | null | shared/source/os_interface/windows/driver_info_windows.cpp | mattcarter2017/compute-runtime | 1f52802aac02c78c19d5493dd3a2402830bbe438 | [
"Intel",
"MIT"
] | null | null | null | /*
* Copyright (C) 2020-2022 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#include "shared/source/os_interface/windows/driver_info_windows.h"
#include "shared/source/os_interface/os_interface.h"
#include "shared/source/os_interface/windows/debug_registry_reader.h"
#include "shared/source/os_interface/windows/sys_calls.h"
#include "shared/source/os_interface/windows/wddm/wddm.h"
std::string getCurrentLibraryPath() {
std::string returnValue;
WCHAR pathW[MAX_PATH];
char path[MAX_PATH];
HMODULE handle = NULL;
auto status = NEO::SysCalls::getModuleHandle(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS |
GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
reinterpret_cast<LPCWSTR>(&getCurrentLibraryPath), &handle);
if (status != 0) {
status = NEO::SysCalls::getModuleFileName(handle, pathW, sizeof(pathW));
if (status != 0) {
std::wcstombs(path, pathW, MAX_PATH);
returnValue.append(path);
}
}
return returnValue;
}
namespace NEO {
DriverInfo *DriverInfo::create(const HardwareInfo *hwInfo, const OSInterface *osInterface) {
if (osInterface == nullptr) {
return nullptr;
}
auto wddm = osInterface->getDriverModel()->as<Wddm>();
UNRECOVERABLE_IF(wddm == nullptr);
return new DriverInfoWindows(wddm->getDeviceRegistryPath(), wddm->getPciBusInfo());
};
DriverInfoWindows::DriverInfoWindows(const std::string &fullPath, const PhysicalDevicePciBusInfo &pciBusInfo)
: path(DriverInfoWindows::trimRegistryKey(fullPath)), registryReader(createRegistryReaderFunc(path)) {
this->pciBusInfo = pciBusInfo;
}
DriverInfoWindows::~DriverInfoWindows() = default;
std::string DriverInfoWindows::trimRegistryKey(std::string path) {
std::string prefix("\\REGISTRY\\MACHINE\\");
auto pos = prefix.find(prefix);
if (pos != std::string::npos)
path.erase(pos, prefix.length());
return path;
}
std::string DriverInfoWindows::getDeviceName(std::string defaultName) {
return registryReader->getSetting("HardwareInformation.AdapterString", defaultName);
}
std::string DriverInfoWindows::getVersion(std::string defaultVersion) {
return registryReader->getSetting("DriverVersion", defaultVersion);
};
bool DriverInfoWindows::isCompatibleDriverStore() const {
auto toLowerAndUnifyDriverStore = [](std::string &input) -> std::string {
std::transform(input.begin(), input.end(), input.begin(), [](unsigned char c) { return std::tolower(c); });
auto hostDriverStorePos = input.find("\\hostdriverstore\\");
if (hostDriverStorePos != std::string::npos) {
input.erase(hostDriverStorePos + 1, 4);
}
return input;
};
auto currentLibraryPath = toLowerAndUnifyDriverStore(getCurrentLibraryPath());
auto openclDriverName = registryReader->getSetting("OpenCLDriverName", std::string{});
if (openclDriverName.empty()) {
return false;
}
auto driverStorePath = toLowerAndUnifyDriverStore(registryReader->getSetting("DriverStorePathForComputeRuntime", currentLibraryPath));
return currentLibraryPath.find(driverStorePath.c_str()) == 0u;
}
bool isCompatibleDriverStore(std::string &&deviceRegistryPath) {
DriverInfoWindows driverInfo(deviceRegistryPath, PhysicalDevicePciBusInfo(PhysicalDevicePciBusInfo::invalidValue, PhysicalDevicePciBusInfo::invalidValue, PhysicalDevicePciBusInfo::invalidValue, PhysicalDevicePciBusInfo::invalidValue));
return driverInfo.isCompatibleDriverStore();
}
decltype(DriverInfoWindows::createRegistryReaderFunc) DriverInfoWindows::createRegistryReaderFunc = [](const std::string ®istryPath) -> std::unique_ptr<SettingsReader> {
return std::make_unique<RegistryReader>(false, registryPath);
};
bool DriverInfoWindows::getMediaSharingSupport() {
return registryReader->getSetting(is64bit ? "UserModeDriverName" : "UserModeDriverNameWOW", std::string("")) != "<>";
}
} // namespace NEO
| 38.961538 | 239 | 0.71693 | [
"transform"
] |
380bcedddab3db89b740e9cb95220c21249259e5 | 1,406 | cc | C++ | cinn/hlir/framework/buffer_test.cc | edithgogo/CINN | bed13f4752d80d01a3e1d96a4cc4f5aa56b1e292 | [
"Apache-2.0"
] | 1 | 2019-10-23T09:16:23.000Z | 2019-10-23T09:16:23.000Z | cinn/hlir/framework/buffer_test.cc | edithgogo/CINN | bed13f4752d80d01a3e1d96a4cc4f5aa56b1e292 | [
"Apache-2.0"
] | null | null | null | cinn/hlir/framework/buffer_test.cc | edithgogo/CINN | bed13f4752d80d01a3e1d96a4cc4f5aa56b1e292 | [
"Apache-2.0"
] | null | null | null | #include "cinn/hlir/framework/buffer.h"
#ifdef CINN_WITH_CUDA
#include "cinn/backends/cuda_util.h"
#endif
#include <gtest/gtest.h>
#include <vector>
namespace cinn {
namespace hlir {
namespace framework {
TEST(Buffer, basic) {
Buffer buffer(common::DefaultHostTarget());
buffer.Resize(10 * sizeof(float));
auto* data = reinterpret_cast<float*>(buffer.data());
for (int i = 0; i < 10; i++) data[i] = i;
}
#ifdef CINN_WITH_CUDA
TEST(Buffer, nvgpu) {
const int num_elements = 10;
Buffer buffer(common::DefaultNVGPUTarget());
buffer.Resize(num_elements * sizeof(float));
auto* data = reinterpret_cast<float*>(buffer.data());
std::vector<float> host_data(num_elements);
std::vector<float> host_target(num_elements, 0);
for (int i = 0; i < num_elements; i++) {
host_data[i] = i;
}
LOG(INFO) << "Cuda copy data";
CUDA_DRIVER_CALL(cuMemcpy(reinterpret_cast<CUdeviceptr>(data),
reinterpret_cast<CUdeviceptr>(host_data.data()),
num_elements * sizeof(float)));
CUDA_DRIVER_CALL(cuMemcpy(reinterpret_cast<CUdeviceptr>(host_target.data()),
reinterpret_cast<CUdeviceptr>(data),
num_elements * sizeof(float)));
for (int i = 0; i < num_elements; i++) {
ASSERT_EQ(host_target[i], i);
}
}
#endif
} // namespace framework
} // namespace hlir
} // namespace cinn
| 29.291667 | 78 | 0.64936 | [
"vector"
] |
380c82b261719363e8362763e049ca2a7150451d | 25,107 | hpp | C++ | cell_based/test/aSF/ApicalStressFibers5C.hpp | SoftMatterMechanics/ApicalStressFibers | 17d343c09a246a50f9e3a3cbfc399ca6bef353ce | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | cell_based/test/aSF/ApicalStressFibers5C.hpp | SoftMatterMechanics/ApicalStressFibers | 17d343c09a246a50f9e3a3cbfc399ca6bef353ce | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | cell_based/test/aSF/ApicalStressFibers5C.hpp | SoftMatterMechanics/ApicalStressFibers | 17d343c09a246a50f9e3a3cbfc399ca6bef353ce | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | /*
Copyright (c) 2005-2018, University of Oxford.
All rights reserved.
University of Oxford means the Chancellor, Masters and Scholars of the
University of Oxford, having an administrative office at Wellington
Square, Oxford OX1 2JD, UK.
This file is part of Chaste.
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 University of Oxford 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.
*/
/*
This program is customized for investigating the roles of apical stress fibers
during the Drosophila development, particularly at the stage of 18-26hAPF (hours
after pupa formation), by Dr. Chao FANG at Department of Mechanical Engineering,
The University of Hong Kong.
*/
#ifndef APICALSTRESSFIBERS_HPP_
#define APICALSTRESSFIBERS_HPP_
#include <cxxtest/TestSuite.h>
#include "CheckpointArchiveTypes.hpp"
#include "AbstractCellBasedTestSuite.hpp"
#include "CellsGenerator.hpp"
#include "OffLatticeSimulation.hpp"
#include "ForwardEulerNumericalMethod.hpp"
#include "TransitCellProliferativeType.hpp"
#include "SmartPointers.hpp"
#include "UniformG1GenerationalCellCycleModel.hpp"
#include "BernoulliTrialCellCycleModel.hpp"
#include "HoneycombVertexMeshGenerator.hpp"
#include "VertexBasedCellPopulation.hpp"
#include "SimpleTargetAreaModifier.hpp"
#include "TargetAreaLinearGrowthModifier.hpp"
// #include "FaceValueAndStressStateModifier.hpp"
#include "PolarityModifier.hpp"
#include "FakePetscSetup.hpp"
#include "PlaneBoundaryCondition.hpp"
#include "ToroidalHoneycombVertexMeshGenerator.hpp"
#include "MyNoPBCToroidalHoneycombVertexMeshGenerator.hpp"
// #include "MyToroidalHoneycombVertexMeshGenerator.hpp"
// #include "NagaiHondaForce.hpp"
#include "MyNagaiHondaForce.hpp"
// #include "MyMorphogeneticForce.hpp"
#include "MyStressfiberTensionForce.hpp"
#include "DiffusionForce.hpp"
#include "PlaneBasedCellKiller.hpp"
// #include <ctime>
class ApicalStressFibers : public AbstractCellBasedTestSuite
{
public:
void TestApicalStressFibers()
{
/*-------------------------START: Basic Settings-----------------------*/
/* Energy equation form: 1/2*Ka*(A-A0)^2 + 1/2*Kp*(P-P0)^2 + Gamma*L */
double target_shape_index = 3.0;
double cell_cell_adhesion_energy_density = -0.1; // Gamma, this parameter consists of cell-cell adhesion and cortical contraction
double cell_boundary_adhesion_energy_density = -0.1; // Gamma at boundary
unsigned seed_for_initial_random_polarity = 4;
double polarity_magnitude_before_equilibrium = 0.025; // for before equilibrium
double nucleation_perimeter_tension = 0.4;
double adhesion_energy = 0.0002;
double sf_stiffness = 0.04;
// 1. Cell mesh and size
unsigned num_ele_across = 16; // cell number along anterior-posterior, must be an even number
unsigned num_ele_up = 16; // cell number along medial-lateral, must be an even number
// double target_shape_index = 3.0;
bool seed_manually = true;
unsigned random_seed_for_target_area = 1;
double min_target_area = 1.0;
double max_target_area = 7.0;
bool use_fixed_target_area_without_modifier = false;
double target_area = (min_target_area + max_target_area)/2; // A0, target areas are not uniform
double initial_area = (min_target_area + max_target_area)/2; // set the initial areas to be uniform, A = 3*sqrt(3)/2*l^2
double center_y_coordination = 0.5*(1.5*num_ele_up+0.5)*sqrt(initial_area/(3*sqrt(3)/2));
double half_width = num_ele_across/2*sqrt(initial_area/(3*sqrt(3)/2))*sqrt(3)/2*2;
// 2. Area elasticity
double area_elastic_modulus = 1.0; // Ka
// 4. Cell-cell adhesion & constant cortical contraction
// this parameter value here is one half of its real value because the edge is shared by two cells
// double cell_cell_adhesion_energy_density = -0.3; // Gamma, this parameter consists of cell-cell adhesion and cortical contraction
// double cell_boundary_adhesion_energy_density = -0.3; // Gamma at boundary
bool if_use_face_element_to_get_adhesion_parameter = false;
// 5. Stress fiber tension
// double sf_stiffness = 0.05;
// double nucleation_perimeter_tension = 0.4;
double rest_length_of_nucleation = 0.02; // delta0 = 0.02;
// double adhesion_energy = 0.0002;
double k = 1;
double C0 = 0.1;
double rate_power = 0.4;
// 6. morphogenetic force
double horizontal_morphogenetic_force = 5.5;
double vertical_morphogenetic_force = 2;
double horizontal_morphogenetic_force_growth_rate = 0.001;
double vertical_morphogenetic_force_growth_rate = 0.02;
// 7. Random force
bool add_random_force = true;
bool has_brownian_random_force = false; // brownian random force is used in cell center model
double translational_diffusion_constant = 0.0;
double set_node_radius = 2.0; // effective cell diameter (in units of 10 microns)
bool has_polarity = true;
// unsigned seed_for_initial_random_polarity = 3;
// double polarity_magnitude_before_equilibrium = 0.04; // for before equilibrium
double polarity_magnitude_after_equilibrium = 0.0; // for after equilibrium
double rotational_diffusion_constant = 0.5;
// 8. Time
bool if_equilibrate_for_a_while = true;
double time_for_rest = 0;
double time_for_random_movement = 400.0;
double time_for_relaxation = 150.0;
double time_for_equilibrium = time_for_rest + time_for_random_movement + time_for_relaxation;
if (time_for_equilibrium <= 0.0)
if_equilibrate_for_a_while = false;
double dt = 0.05;
double real_equilibrium_time = time_for_equilibrium + vertical_morphogenetic_force/vertical_morphogenetic_force_growth_rate;
double start_time_for_stretching = real_equilibrium_time;
double end_time = real_equilibrium_time + (horizontal_morphogenetic_force - vertical_morphogenetic_force)/horizontal_morphogenetic_force_growth_rate;
double max_movement_per_timestep = 0.05;
bool apply_adaptive_timestep = true;
double sampling_time = 1.0;
unsigned sampling_timestep_multiple = (unsigned) round(sampling_time/dt);
// 9. Cell rearrangement threshold length for T1 & T2 transitions
double cell_rearrangement_threshold = 0.01;
double t2_threshold = 0.001;
double t3_threshold = 5.0;
// 10. Output & display
bool if_update_face_elements_in_mesh = true;
bool output_concise_swap_information_when_remesh = false;
bool output_detailed_swap_information_when_remesh = false;
bool output_numerical_method_information = false;
// bool output_information_for_nagai_honda_force = false;
// bool if_set_cell_data_of_detailed_force_contributions = false; // for output and display each component in Paraview
bool use_concise_output_directory = true;
/*------------------------------END: Basic Settings----------------------------*/
/*-----------------------START: Generate cell monolayer mesh-------------------*/
MyNoPBCToroidalHoneycombVertexMeshGenerator generator(num_ele_across, num_ele_up, initial_area, cell_rearrangement_threshold, t2_threshold);
MyNoPBCToroidal2dVertexMesh* p_mesh = generator.GetToroidalMesh();
p_mesh->SetDistanceForT3SwapChecking(t3_threshold);
p_mesh->SetUpdateFaceElementsInMeshBoolean(if_update_face_elements_in_mesh);
// p_mesh->SetIfClassifyElementsWithGroupNumbers(classify_elements_with_group_numbers);
// p_mesh->SetMarkLeadingCells(mark_leading_cells);
p_mesh->SetOutputConciseSwapInformationWhenRemesh(output_concise_swap_information_when_remesh);
p_mesh->SetOutputDetailedSwapInformationWhenRemesh(output_detailed_swap_information_when_remesh);
/*------------------------END: Generate cell monolayer mesh--------------------*/
/*---------------------------START: Cells and Cell population--------------------------*/
std::vector<CellPtr> cells;
MAKE_PTR(TransitCellProliferativeType, p_transit_type);
CellsGenerator<BernoulliTrialCellCycleModel, 2> cells_generator;
bool use_bernoulli_trial_cell_cycle_model = true;
double period_of_cell_division = DOUBLE_UNSET;
double divide_probability_for_a_cell = 1.0/period_of_cell_division/(num_ele_across*num_ele_up);
double minimum_division_age = -0.01;
cells_generator.SetUseBernoulliTrialCellCycleModel(use_bernoulli_trial_cell_cycle_model);
cells_generator.SetDivisionProbability(divide_probability_for_a_cell);
cells_generator.SetMinimumDivisionAge(minimum_division_age);
cells_generator.SetRandomSeedForTargetAreas(random_seed_for_target_area);
cells_generator.SetLimitsOfTargetAreas(min_target_area, max_target_area);
// cells_generator.SetPerimeterElasticityParameter(edge_elastic_modulus);
cells_generator.GenerateBasicRandom(cells, p_mesh->GetNumElements(), p_transit_type);
bool restrict_vertex_movement = false;
VertexBasedCellPopulation<2> cell_population(*p_mesh, cells);
cell_population.SetRestrictVertexMovementBoolean(restrict_vertex_movement);
/*------------------------------END: Cells and Cell population--------------------------*/
/*---------------------------------START: Simulator settings----------------------------*/
OffLatticeSimulation<2> simulator(cell_population);
// output cell velocity:
bool run_with_birth = false;
bool output_cell_velocity = true;
bool my_output_cell_velocity = true;
bool output_cell_elongation = true;
simulator.SetNoBirth(!run_with_birth);
simulator.SetOutputCellVelocities(output_cell_velocity);
simulator.SetMyOutputCellVelocities(my_output_cell_velocity);
if (my_output_cell_velocity && seed_manually)
simulator.SetMySeed(random_seed_for_target_area);
simulator.SetOutputCellElongation(output_cell_elongation);
// Timestep
simulator.SetApplyAdaptiveTimestep(apply_adaptive_timestep);
simulator.SetDt(dt);
simulator.SetApplySamplingTimeInsteadOfSamplingTimestep(apply_adaptive_timestep);
simulator.SetSamplingTimestepMultiple(sampling_timestep_multiple);
simulator.SetSamplingTime(sampling_time);
simulator.SetEndTime(end_time);
// Numerical Method
boost::shared_ptr<ForwardEulerNumericalMethod<2,2>> p_numerical_method(new ForwardEulerNumericalMethod<2,2>());
p_numerical_method->SetCellPopulation(&cell_population);
//Note: Here the address of std::vector of force collections are different from that in simulator!
//But the corresponding shared_ptrs in the vectors should be the same.
std::vector< boost::shared_ptr<AbstractForce<2, 2>> > force_collection = simulator.rGetForceCollection();
p_numerical_method->SetForceCollection(&force_collection);
p_numerical_method->SetMaxMovementPerTimestep(max_movement_per_timestep);
p_numerical_method->SetOutputNumericalMethodInformation(output_numerical_method_information);
p_numerical_method->SetCenterYCoordination(center_y_coordination);
p_numerical_method->SetIfEquilibrateForAWhile(if_equilibrate_for_a_while);
p_numerical_method->SetTimeForEquilibrium(time_for_equilibrium);
p_numerical_method->SetRealEquilibriumTime(real_equilibrium_time);
p_numerical_method->SetMorphogeneticForceGrowthRate(horizontal_morphogenetic_force_growth_rate, vertical_morphogenetic_force_growth_rate);
simulator.SetNumericalMethod(p_numerical_method);
/*---------------------------------END: Simulator settings-----------------------------*/
/*--------------------------------START: Modifier Settings-----------------------------*/
// Polarity modifier
if (has_polarity)
{
MAKE_PTR_ARGS(PolarityModifier<2>, p_polarity_modifier, ());
p_polarity_modifier->SetPolarityMagnitudeAfterEquilibrium(polarity_magnitude_after_equilibrium);
p_polarity_modifier->SetPolarityMagnitudeBeforeEquilibrium(polarity_magnitude_before_equilibrium);
p_polarity_modifier->SetSeedManually(seed_manually);
p_polarity_modifier->SetSeedForInitialRandomPolarity(seed_for_initial_random_polarity);
p_polarity_modifier->SetD(rotational_diffusion_constant);
simulator.AddSimulationModifier(p_polarity_modifier);
}
/*----------------------------------END: Modifier Settings------------------------------*/
// /*---------------------------------START: MyMorphogeneticForce-----------------------------*/
// MAKE_PTR(MyMorphogeneticForce<2>, p_morphogenetic_force);
// p_morphogenetic_force->SetAddPullingForceEvenlyOnNodesOfLeadingCell(add_pulling_force_evenly_on_nodes_of_leading_cell);
// p_morphogenetic_force->SetPullingForceOnLeadingCell(pulling_force_on_leading_cell);
// p_morphogenetic_force->SetCenterYCoordination(center_y_coordination);
// p_morphogenetic_force->SetIfEquilibrateForAWhile(if_equilibrate_for_a_while);
// p_morphogenetic_force->SetEndTimeForEquilibrium(time_for_equilibrium);
// simulator.AddForce(p_morphogenetic_force);
// /*-------------------------------------END: MyNagaiHondaForce------------------------------*/
/*---------------------------------START: MyNagaiHondaForce-----------------------------*/
MAKE_PTR(MyNagaiHondaForce<2>, p_nh_force);
p_nh_force->SetNagaiHondaDeformationEnergyParameter(area_elastic_modulus); // KA
// p_nh_force->SetNagaiHondaMembraneSurfaceEnergyParameter(edge_elastic_modulus); // KL
p_nh_force->SetNagaiHondaCellCellAdhesionEnergyParameter(cell_cell_adhesion_energy_density); // Gamma
p_nh_force->SetNagaiHondaCellBoundaryAdhesionEnergyParameter(cell_boundary_adhesion_energy_density); // Gamma at boundary
p_nh_force->SetUseFixedTargetArea(use_fixed_target_area_without_modifier); // used in the case where there is no target area modifier! (no division)
p_nh_force->SetFixedTargetArea(target_area); // to be determined
p_nh_force->SetTargetShapeIndex(target_shape_index);
// p_nh_force->SetFixedTargetPerimeter(target_perimeter);
p_nh_force->SetTimeForRest(time_for_rest);
p_nh_force->SetUseFaceElementToGetAdhesionParameterBoolean(if_use_face_element_to_get_adhesion_parameter);
// p_force->SetOutputInformationForNagaiHondaForce(output_information_for_nagai_honda_force);
simulator.AddForce(p_nh_force);
/*-------------------------------------END: MyNagaiHondaForce------------------------------*/
/*---------------------------------START: My Stressfiber Tension Force-----------------------------*/
MAKE_PTR(MyStressfiberTensionForce<2>, p_sf_force);
p_sf_force->SetIfEquilibrateForAWhile(if_equilibrate_for_a_while);
p_sf_force->SetStartTimeForStretching(start_time_for_stretching);
p_sf_force->SetFlagForStressfiberCreation(0);
p_sf_force->SetStressfiberStiffness(sf_stiffness);
p_sf_force->SetNucleationThresholdOfPerimeterTension(nucleation_perimeter_tension);
p_sf_force->SetHalfWidth(half_width);
p_sf_force->SetRestLengthOfNucleation(rest_length_of_nucleation);
p_sf_force->SetPeelingParameters(adhesion_energy, k, C0, rate_power);
// simulator.AddForce(p_sf_force);
/*-------------------------------------END: My Stressfiber Tension Force------------------------------*/
/*-----------------------------------START: Brownian Random Force -------------------------*/
// Brownian diffusion
if (add_random_force)
{
MAKE_PTR(DiffusionForce<2>, p_random_force);
bool use_the_same_node_radius = true;
double node_radius = 2.0; // effective cell diameter (in units 10 microns)
if (translational_diffusion_constant >0.0)
node_radius = p_random_force->GetDiffusionScalingConstant()/translational_diffusion_constant;
else
node_radius = set_node_radius;
translational_diffusion_constant = p_random_force->GetDiffusionScalingConstant()/node_radius;
p_random_force->SetHasBrownianRandomForce(has_brownian_random_force);
p_random_force->SetUseTheSameNodeRadius(use_the_same_node_radius);
p_random_force->SetTheSameNodeRadius(node_radius);
p_random_force->SetHasPolarity(has_polarity);
p_random_force->SetIfEquilibrateForAWhile(if_equilibrate_for_a_while);
p_random_force->SetStartTimeForRandom(time_for_rest);
p_random_force->SetEndTimeForRandom(time_for_rest + time_for_random_movement);
simulator.AddForce(p_random_force);
}
/*------------------------------------END: Brownian Random Force ---------------------------*/
/*------------------------------------START: CellKiller---------------------------------------*/
c_vector<double, 2> point_vec = zero_vector<double>(2);
double kill_height = 10000.0;
point_vec[1] = kill_height;
c_vector<double, 2> norm_vec = zero_vector<double>(2);
norm_vec[1] = 1.0;
bool kill_cells_group_number_from1 = true;
MAKE_PTR_ARGS(PlaneBasedCellKiller<2>, p_killer, (&cell_population, point_vec, norm_vec) );
p_killer->SetKillCellsGroupNumberFrom1(kill_cells_group_number_from1);
simulator.AddCellKiller(p_killer);
/*------------------------------------END: CellKiller---------------------------------------*/
/*----------------------------------START: Boundary condition-------------------------------*/
c_vector<double,2> point1 = zero_vector<double>(2);
c_vector<double,2> normal1 = zero_vector<double>(2);
normal1(1) = -1.0;
double stop_time1 = time_for_equilibrium;
MAKE_PTR_ARGS(PlaneBoundaryCondition<2>, p_bc1, (&cell_population, point1, normal1, stop_time1));
c_vector<double,2> point2 = zero_vector<double>(2);
c_vector<double,2> normal2 = zero_vector<double>(2);
point2(1) = (1.5*num_ele_up + 0.5)*sqrt(initial_area/(3*sqrt(3)/2));
normal2(1) = 1.0;
double stop_time2 = time_for_equilibrium;
MAKE_PTR_ARGS(PlaneBoundaryCondition<2>, p_bc2, (&cell_population, point2, normal2, stop_time2));
// c_vector<double,2> point3 = zero_vector<double>(2);
// c_vector<double,2> normal3 = zero_vector<double>(2);
// point3(0) = -half_width;
// normal3(0) = -1.0;
// double stop_time3 = time_for_equilibrium;
// MAKE_PTR_ARGS(PlaneBoundaryCondition<2>, p_bc3, (&cell_population, point3, normal3, stop_time3));
// c_vector<double,2> point4 = zero_vector<double>(2);
// c_vector<double,2> normal4 = zero_vector<double>(2);
// point4(0) = half_width + sqrt(initial_area/(3*sqrt(3)/2))*sqrt(3)/2;
// normal4(0) = 1.0;
// double stop_time4 = time_for_equilibrium;
// MAKE_PTR_ARGS(PlaneBoundaryCondition<2>, p_bc4, (&cell_population, point4, normal4, stop_time4));
simulator.AddCellPopulationBoundaryCondition(p_bc1);
simulator.AddCellPopulationBoundaryCondition(p_bc2);
// simulator.AddCellPopulationBoundaryCondition(p_bc3);
// simulator.AddCellPopulationBoundaryCondition(p_bc4);
/*--------------------------------END: Boundary condition-----------------------------*/
/*--------------------------START: Output Directory and Simulation Information File---------------------*/
// Output directory:
std::ostringstream oss;
time_t raw_time = time(0);
struct tm * now = localtime(& raw_time);
std::string output_directory = "aSF/Date: ";
oss.str("");
oss << (now->tm_year + 1900 -2000) << '-' << (now->tm_mon + 1) << '-' << now->tm_mday << '/';
output_directory += oss.str();
oss.str("");
oss << "Timestamp=" << now->tm_hour << ':' << now->tm_min << ':' << now->tm_sec;
oss << "_NumUp=" << num_ele_up;
oss << "_NumAc=" << num_ele_across;
oss << "_Ka=" << ((area_elastic_modulus>=0.01 || area_elastic_modulus==0.0)? std::fixed : std::scientific)
<< setprecision(2) << area_elastic_modulus;
// oss << "_Kp=" << ((edge_elastic_modulus>=0.01 || edge_elastic_modulus==0.0)? std::fixed : std::scientific)
// << setprecision(2) << edge_elastic_modulus;
oss << "_Gamma=" << ((fabs(cell_cell_adhesion_energy_density)>=0.01 || fabs(cell_cell_adhesion_energy_density)==0.0)? std::fixed : std::scientific)
<< setprecision(2) << cell_cell_adhesion_energy_density;
oss << "_p0=" << std::fixed << setprecision(2) << target_shape_index;
oss << "_Ai=" << std::fixed << setprecision(2) << initial_area;
oss << "_minA0=" << std::fixed << setprecision(2) << min_target_area;
oss << "_maxA0=" << std::fixed << setprecision(2) << max_target_area;
oss << "_Aseed=" << random_seed_for_target_area;
oss << "_fp=" << std::fixed << setprecision(3) << polarity_magnitude_before_equilibrium;
oss << "_Pseed=" << seed_for_initial_random_polarity;
oss << "_dt=" << std::fixed << setprecision(3) << dt;
oss << "_maxd=" << std::fixed << setprecision(3) << max_movement_per_timestep;
if (if_equilibrate_for_a_while)
{
oss << "_eqtime=" << std::fixed << setprecision(1) << time_for_equilibrium;
}
oss << "_realeqtime=" << std::fixed << setprecision(1) << real_equilibrium_time;
oss << "_simtime=" << std::fixed << setprecision(1) << end_time;
oss << "_Fx=" << std::fixed << setprecision(1) << horizontal_morphogenetic_force;
oss << "_Fy=" << std::fixed << setprecision(1) << vertical_morphogenetic_force;
oss << "_vFx=" << std::fixed << setprecision(3) << horizontal_morphogenetic_force_growth_rate;
oss << "_vFy=" << std::fixed << setprecision(2) << vertical_morphogenetic_force_growth_rate;
output_directory += oss.str();
std::string concise_output_directory = output_directory;
bool omit_file_name_results_from_time_X = true;
bool output_simulatin_information_to_file = true;
simulator.SetOmitFileNameResultsFromTimeX(omit_file_name_results_from_time_X);
simulator.SetOutputSimulationInformationToFile(output_simulatin_information_to_file);
if (output_simulatin_information_to_file)
simulator.InputSimulationInformation(output_directory);
if (use_concise_output_directory)
{
simulator.SetOutputDirectory(concise_output_directory);
std::cout << std::endl << "Concise output directory is set: " << concise_output_directory << std::endl;
}
else
{
std::cout << std::endl << "Output directory is not set. Please set up an output directory!" << std::endl;
EXCEPTION("Output directory is not set.");
}
/*--------------------------END: Output Directory and Simulation Information File---------------------*/
p_sf_force->SetOutputDirectory(concise_output_directory);
simulator.AddForce(p_sf_force);
simulator.Solve();
}
};
#endif /* APICALSTRESSFIBERS_HPP_ */
| 52.415449 | 158 | 0.675668 | [
"mesh",
"vector",
"model"
] |
38144468400adc17d5fa20e94fa0ade51f89abbb | 13,509 | hpp | C++ | include/codegen/include/System/Double.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | 1 | 2021-11-12T09:29:31.000Z | 2021-11-12T09:29:31.000Z | include/codegen/include/System/Double.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | null | null | null | include/codegen/include/System/Double.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: System.ValueType
#include "System/ValueType.hpp"
// Including type: System.IComparable
#include "System/IComparable.hpp"
// Including type: System.IFormattable
#include "System/IFormattable.hpp"
// Including type: System.IConvertible
#include "System/IConvertible.hpp"
// Including type: System.IComparable`1
#include "System/IComparable_1.hpp"
// Including type: System.IEquatable`1
#include "System/IEquatable_1.hpp"
// Completed includes
// Begin forward declares
// Forward declaring namespace: System
namespace System {
// Forward declaring type: IFormatProvider
class IFormatProvider;
// Forward declaring type: TypeCode
struct TypeCode;
// Forward declaring type: Decimal
struct Decimal;
// Forward declaring type: DateTime
struct DateTime;
// Forward declaring type: Type
class Type;
}
// Forward declaring namespace: System::Globalization
namespace System::Globalization {
// Forward declaring type: NumberStyles
struct NumberStyles;
// Forward declaring type: NumberFormatInfo
class NumberFormatInfo;
}
// Completed forward declares
// Type namespace: System
namespace System {
// Autogenerated type: System.Double
struct Double : public System::ValueType, public System::IComparable, public System::IFormattable, public System::IConvertible, public System::IComparable_1<double>, public System::IEquatable_1<double> {
public:
// System.Double m_value
// Offset: 0x0
double m_value;
// static field const value: static public System.Double MinValue
static constexpr const double MinValue = -1.7976931348623157e+308;
// Get static field: static public System.Double MinValue
static double _get_MinValue();
// Set static field: static public System.Double MinValue
static void _set_MinValue(double value);
// static field const value: static public System.Double MaxValue
static constexpr const double MaxValue = 1.7976931348623157e+308;
// Get static field: static public System.Double MaxValue
static double _get_MaxValue();
// Set static field: static public System.Double MaxValue
static void _set_MaxValue(double value);
// static field const value: static public System.Double Epsilon
static constexpr const double Epsilon = 5e-324;
// Get static field: static public System.Double Epsilon
static double _get_Epsilon();
// Set static field: static public System.Double Epsilon
static void _set_Epsilon(double value);
// Get static field: static public System.Double NegativeInfinity
static double _get_NegativeInfinity();
// Set static field: static public System.Double NegativeInfinity
static void _set_NegativeInfinity(double value);
// Get static field: static public System.Double PositiveInfinity
static double _get_PositiveInfinity();
// Set static field: static public System.Double PositiveInfinity
static void _set_PositiveInfinity(double value);
// Get static field: static public System.Double NaN
static double _get_NaN();
// Set static field: static public System.Double NaN
static void _set_NaN(double value);
// Get static field: static System.Double NegativeZero
static double _get_NegativeZero();
// Set static field: static System.Double NegativeZero
static void _set_NegativeZero(double value);
// Creating value type constructor for type: Double
Double(double m_value_ = {}) : m_value{m_value_} {}
// static public System.Boolean IsInfinity(System.Double d)
// Offset: 0xDA1D9C
static bool IsInfinity(double d);
// static public System.Boolean IsPositiveInfinity(System.Double d)
// Offset: 0xDA1DB4
static bool IsPositiveInfinity(double d);
// static public System.Boolean IsNegativeInfinity(System.Double d)
// Offset: 0xDA1DC8
static bool IsNegativeInfinity(double d);
// static public System.Boolean IsNaN(System.Double d)
// Offset: 0xDA1DDC
static bool IsNaN(double d);
// public System.String ToString(System.String format)
// Offset: 0xA30190
::Il2CppString* ToString(::Il2CppString* format);
// static public System.Double Parse(System.String s)
// Offset: 0xDA22DC
static double Parse(::Il2CppString* s);
// static public System.Double Parse(System.String s, System.IFormatProvider provider)
// Offset: 0xDA2364
static double Parse(::Il2CppString* s, System::IFormatProvider* provider);
// static public System.Double Parse(System.String s, System.Globalization.NumberStyles style, System.IFormatProvider provider)
// Offset: 0xDA23F4
static double Parse(::Il2CppString* s, System::Globalization::NumberStyles style, System::IFormatProvider* provider);
// static private System.Double Parse(System.String s, System.Globalization.NumberStyles style, System.Globalization.NumberFormatInfo info)
// Offset: 0xDA235C
static double Parse(::Il2CppString* s, System::Globalization::NumberStyles style, System::Globalization::NumberFormatInfo* info);
// static public System.Boolean TryParse(System.String s, System.Globalization.NumberStyles style, System.IFormatProvider provider, System.Double result)
// Offset: 0xDA2494
static bool TryParse(::Il2CppString* s, System::Globalization::NumberStyles style, System::IFormatProvider* provider, double& result);
// static private System.Boolean TryParse(System.String s, System.Globalization.NumberStyles style, System.Globalization.NumberFormatInfo info, System.Double result)
// Offset: 0xDA2540
static bool TryParse(::Il2CppString* s, System::Globalization::NumberStyles style, System::Globalization::NumberFormatInfo* info, double& result);
// static private System.Void .cctor()
// Offset: 0xDA2D98
static void _cctor();
// public System.Int32 CompareTo(System.Object value)
// Offset: 0xA30130
// Implemented from: System.IComparable
// Base method: System.Int32 IComparable::CompareTo(System.Object value)
int CompareTo(::Il2CppObject* value);
// Creating proxy method: System_IComparable_CompareTo
// Maps to method: CompareTo
int System_IComparable_CompareTo(::Il2CppObject* value);
// public System.Int32 CompareTo(System.Double value)
// Offset: 0xA30138
// Implemented from: System.IComparable`1
// Base method: System.Int32 IComparable`1::CompareTo(System.Double value)
int CompareTo(double value);
// public override System.Boolean Equals(System.Object obj)
// Offset: 0xA30140
// Implemented from: System.ValueType
// Base method: System.Boolean ValueType::Equals(System.Object obj)
bool Equals(::Il2CppObject* obj);
// public System.Boolean Equals(System.Double obj)
// Offset: 0xA30148
// Implemented from: System.IEquatable`1
// Base method: System.Boolean IEquatable`1::Equals(System.Double obj)
bool Equals(double obj);
// public override System.Int32 GetHashCode()
// Offset: 0xA30150
// Implemented from: System.ValueType
// Base method: System.Int32 ValueType::GetHashCode()
int GetHashCode();
// public override System.String ToString()
// Offset: 0xA3015C
// Implemented from: System.ValueType
// Base method: System.String ValueType::ToString()
::Il2CppString* ToString();
// public System.String ToString(System.IFormatProvider provider)
// Offset: 0xA301D0
// Implemented from: System.IConvertible
// Base method: System.String IConvertible::ToString(System.IFormatProvider provider)
::Il2CppString* ToString(System::IFormatProvider* provider);
// public System.String ToString(System.String format, System.IFormatProvider provider)
// Offset: 0xA30208
// Implemented from: System.IFormattable
// Base method: System.String IFormattable::ToString(System.String format, System.IFormatProvider provider)
::Il2CppString* ToString(::Il2CppString* format, System::IFormatProvider* provider);
// public System.TypeCode GetTypeCode()
// Offset: 0xA3024C
// Implemented from: System.IConvertible
// Base method: System.TypeCode IConvertible::GetTypeCode()
System::TypeCode GetTypeCode();
// private System.Boolean System.IConvertible.ToBoolean(System.IFormatProvider provider)
// Offset: 0xA30254
// Implemented from: System.IConvertible
// Base method: System.Boolean IConvertible::ToBoolean(System.IFormatProvider provider)
bool System_IConvertible_ToBoolean(System::IFormatProvider* provider);
// private System.Char System.IConvertible.ToChar(System.IFormatProvider provider)
// Offset: 0xA3025C
// Implemented from: System.IConvertible
// Base method: System.Char IConvertible::ToChar(System.IFormatProvider provider)
::Il2CppChar System_IConvertible_ToChar(System::IFormatProvider* provider);
// private System.SByte System.IConvertible.ToSByte(System.IFormatProvider provider)
// Offset: 0xA30268
// Implemented from: System.IConvertible
// Base method: System.SByte IConvertible::ToSByte(System.IFormatProvider provider)
int8_t System_IConvertible_ToSByte(System::IFormatProvider* provider);
// private System.Byte System.IConvertible.ToByte(System.IFormatProvider provider)
// Offset: 0xA30270
// Implemented from: System.IConvertible
// Base method: System.Byte IConvertible::ToByte(System.IFormatProvider provider)
uint8_t System_IConvertible_ToByte(System::IFormatProvider* provider);
// private System.Int16 System.IConvertible.ToInt16(System.IFormatProvider provider)
// Offset: 0xA30278
// Implemented from: System.IConvertible
// Base method: System.Int16 IConvertible::ToInt16(System.IFormatProvider provider)
int16_t System_IConvertible_ToInt16(System::IFormatProvider* provider);
// private System.UInt16 System.IConvertible.ToUInt16(System.IFormatProvider provider)
// Offset: 0xA30280
// Implemented from: System.IConvertible
// Base method: System.UInt16 IConvertible::ToUInt16(System.IFormatProvider provider)
uint16_t System_IConvertible_ToUInt16(System::IFormatProvider* provider);
// private System.Int32 System.IConvertible.ToInt32(System.IFormatProvider provider)
// Offset: 0xA30288
// Implemented from: System.IConvertible
// Base method: System.Int32 IConvertible::ToInt32(System.IFormatProvider provider)
int System_IConvertible_ToInt32(System::IFormatProvider* provider);
// private System.UInt32 System.IConvertible.ToUInt32(System.IFormatProvider provider)
// Offset: 0xA30290
// Implemented from: System.IConvertible
// Base method: System.UInt32 IConvertible::ToUInt32(System.IFormatProvider provider)
uint System_IConvertible_ToUInt32(System::IFormatProvider* provider);
// private System.Int64 System.IConvertible.ToInt64(System.IFormatProvider provider)
// Offset: 0xA30298
// Implemented from: System.IConvertible
// Base method: System.Int64 IConvertible::ToInt64(System.IFormatProvider provider)
int64_t System_IConvertible_ToInt64(System::IFormatProvider* provider);
// private System.UInt64 System.IConvertible.ToUInt64(System.IFormatProvider provider)
// Offset: 0xA302A0
// Implemented from: System.IConvertible
// Base method: System.UInt64 IConvertible::ToUInt64(System.IFormatProvider provider)
uint64_t System_IConvertible_ToUInt64(System::IFormatProvider* provider);
// private System.Single System.IConvertible.ToSingle(System.IFormatProvider provider)
// Offset: 0xA302A8
// Implemented from: System.IConvertible
// Base method: System.Single IConvertible::ToSingle(System.IFormatProvider provider)
float System_IConvertible_ToSingle(System::IFormatProvider* provider);
// private System.Double System.IConvertible.ToDouble(System.IFormatProvider provider)
// Offset: 0xA302B0
// Implemented from: System.IConvertible
// Base method: System.Double IConvertible::ToDouble(System.IFormatProvider provider)
double System_IConvertible_ToDouble(System::IFormatProvider* provider);
// private System.Decimal System.IConvertible.ToDecimal(System.IFormatProvider provider)
// Offset: 0xA302B8
// Implemented from: System.IConvertible
// Base method: System.Decimal IConvertible::ToDecimal(System.IFormatProvider provider)
System::Decimal System_IConvertible_ToDecimal(System::IFormatProvider* provider);
// private System.DateTime System.IConvertible.ToDateTime(System.IFormatProvider provider)
// Offset: 0xA302C0
// Implemented from: System.IConvertible
// Base method: System.DateTime IConvertible::ToDateTime(System.IFormatProvider provider)
System::DateTime System_IConvertible_ToDateTime(System::IFormatProvider* provider);
// private System.Object System.IConvertible.ToType(System.Type type, System.IFormatProvider provider)
// Offset: 0xA302CC
// Implemented from: System.IConvertible
// Base method: System.Object IConvertible::ToType(System.Type type, System.IFormatProvider provider)
::Il2CppObject* System_IConvertible_ToType(System::Type* type, System::IFormatProvider* provider);
}; // System.Double
}
#include "extern/beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
DEFINE_IL2CPP_ARG_TYPE(System::Double, "System", "Double");
#pragma pack(pop)
| 53.820717 | 205 | 0.753276 | [
"object"
] |
38152ac7bdcafada8632606e11dd136ad7267201 | 932 | cpp | C++ | Algorithms/1567.Maximum_Length_of_Subarray_With_Positive_Product.cpp | metehkaya/LeetCode | 52f4a1497758c6f996d515ced151e8783ae4d4d2 | [
"MIT"
] | 2 | 2020-07-20T06:40:22.000Z | 2021-11-20T01:23:26.000Z | Problems/LeetCode/Problems/1567.Maximum_Length_of_Subarray_With_Positive_Product.cpp | metehkaya/Algo-Archive | 03b5fdcf06f84a03125c57762c36a4e03ca6e756 | [
"MIT"
] | null | null | null | Problems/LeetCode/Problems/1567.Maximum_Length_of_Subarray_With_Positive_Product.cpp | metehkaya/Algo-Archive | 03b5fdcf06f84a03125c57762c36a4e03ca6e756 | [
"MIT"
] | null | null | null | class Solution {
public:
int getMaxLen(vector<int>& ar) {
int n = ar.size() , ans = 0;
int idxPos = 0 , idxNeg = -1;
bool isPos = true;
for( int i = 0 ; i < n ; i++ ) {
if(ar[i] == 0) {
idxPos = i+1;
idxNeg = -1;
isPos = true;
}
else if(ar[i] > 0) {
if(isPos && idxPos != -1)
ans = max(ans,i-idxPos+1);
else if(!isPos && idxNeg != -1)
ans = max(ans,i-idxNeg+1);
}
else {
isPos = !isPos;
if(!isPos && idxNeg == -1)
idxNeg = i+1;
if(isPos && idxPos != -1)
ans = max(ans,i-idxPos+1);
else if(!isPos && idxNeg != -1)
ans = max(ans,i-idxNeg+1);
}
}
return ans;
}
}; | 30.064516 | 47 | 0.33691 | [
"vector"
] |
381a393ed78fc2e3a29d914fb9ed2251cd4acb69 | 5,153 | cc | C++ | localization/graph_localizer/src/rotation_factor_adder.cc | jdekarske/astrobee | c882f9f39719487770bbe7c7322d2ca7f71a1272 | [
"Apache-2.0"
] | 629 | 2017-08-31T23:09:00.000Z | 2022-03-30T11:55:40.000Z | localization/graph_localizer/src/rotation_factor_adder.cc | jdekarske/astrobee | c882f9f39719487770bbe7c7322d2ca7f71a1272 | [
"Apache-2.0"
] | 269 | 2018-05-05T12:31:16.000Z | 2022-03-30T22:04:11.000Z | localization/graph_localizer/src/rotation_factor_adder.cc | jdekarske/astrobee | c882f9f39719487770bbe7c7322d2ca7f71a1272 | [
"Apache-2.0"
] | 248 | 2017-08-31T23:20:56.000Z | 2022-03-30T22:29:16.000Z | /* Copyright (c) 2017, United States Government, as represented by the
* Administrator of the National Aeronautics and Space Administration.
*
* All rights reserved.
*
* The Astrobee platform is 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 <graph_localizer/pose_rotation_factor.h>
#include <graph_localizer/rotation_factor_adder.h>
#include <graph_localizer/utilities.h>
#include <localization_common/logger.h>
#include <gtsam/inference/Symbol.h>
#include <opencv2/calib3d.hpp>
#include <opencv2/core/eigen.hpp>
#include <opencv2/core/types.hpp>
namespace graph_localizer {
namespace go = graph_optimizer;
namespace lm = localization_measurements;
namespace sym = gtsam::symbol_shorthand;
RotationFactorAdder::RotationFactorAdder(const RotationFactorAdderParams& params,
std::shared_ptr<const FeatureTracker> feature_tracker)
: RotationFactorAdder::Base(params), feature_tracker_(feature_tracker) {}
std::vector<go::FactorsToAdd> RotationFactorAdder::AddFactors(const lm::FeaturePointsMeasurement& measurement) {
std::vector<cv::Point2d> points_1;
std::vector<cv::Point2d> points_2;
double total_disparity = 0;
for (const auto& feature_track_pair : feature_tracker_->feature_tracks()) {
const auto& feature_track = *(feature_track_pair.second);
if (feature_track.size() < 2) continue;
// Get points for most recent and second to most recent images
const auto& point_1 = std::next(feature_track.points().crbegin())->second.image_point;
const auto& point_2 = feature_track.points().crbegin()->second.image_point;
points_1.emplace_back(cv::Point2d(point_1.x(), point_1.y()));
points_2.emplace_back(cv::Point2d(point_2.x(), point_2.y()));
total_disparity += (point_1 - point_2).norm();
}
if (points_1.size() < 5) {
LogDebug("AddFactors: Not enough corresponding points found.");
return {};
}
const double average_disparity = total_disparity / points_1.size();
if (average_disparity < params().min_avg_disparity) {
LogDebug("AddFactors: Disparity too low.");
return {};
}
cv::Mat intrinsics;
cv::eigen2cv(params().nav_cam_intrinsics.K(), intrinsics);
cv::Mat outlier_mask;
const auto essential_matrix =
cv::findEssentialMat(points_1, points_2, intrinsics, cv::RANSAC, 0.999, 1e-3, outlier_mask);
int num_inliers_essential_matrix = 0;
for (int i = 0; i < outlier_mask.rows; ++i) {
if (outlier_mask.at<uint8_t>(i, 0) == 1) ++num_inliers_essential_matrix;
}
cv::Mat cv_cam_2_R_cam_1;
cv::Mat cv_translation;
const int num_inliers_pose_calculation =
cv::recoverPose(essential_matrix, points_1, points_2, intrinsics, cv_cam_2_R_cam_1, cv_translation, outlier_mask);
// Only consider outliers from recoverPose calculation, ignore already pruned outliers from findEssentialMat
const double percent_outliers =
static_cast<double>(num_inliers_essential_matrix - num_inliers_pose_calculation) / num_inliers_essential_matrix;
if (percent_outliers > params().max_percent_outliers) {
LogDebug("AddFactors: Too many outliers, discarding result.");
return {};
}
Eigen::Matrix3d eigen_cam_2_R_cam_1;
cv::cv2eigen(cv_cam_2_R_cam_1, eigen_cam_2_R_cam_1);
const gtsam::Rot3& body_R_cam = params().body_T_nav_cam.rotation();
// Put measurement in body frame since factor expects this
const gtsam::Rot3 cam_1_R_cam_2(eigen_cam_2_R_cam_1.transpose());
const gtsam::Rot3 body_1_R_body_2 = body_R_cam * cam_1_R_cam_2 * body_R_cam.inverse();
// Create Rotation Factor
const go::KeyInfo pose_1_key_info(&sym::P, go::NodeUpdaterType::CombinedNavState,
*(feature_tracker_->PreviousTimestamp()));
const go::KeyInfo pose_2_key_info(&sym::P, go::NodeUpdaterType::CombinedNavState, measurement.timestamp);
const gtsam::Vector3 rotation_noise_sigmas(
(gtsam::Vector(3) << params().rotation_stddev, params().rotation_stddev, params().rotation_stddev).finished());
const auto rotation_noise = Robust(
gtsam::noiseModel::Diagonal::Sigmas(Eigen::Ref<const Eigen::VectorXd>(rotation_noise_sigmas)), params().huber_k);
const auto rotation_factor = boost::make_shared<gtsam::PoseRotationFactor>(
body_1_R_body_2, rotation_noise, pose_1_key_info.UninitializedKey(), pose_2_key_info.UninitializedKey());
go::FactorsToAdd rotation_factors_to_add;
rotation_factors_to_add.push_back({{pose_1_key_info, pose_2_key_info}, rotation_factor});
rotation_factors_to_add.SetTimestamp(pose_2_key_info.timestamp());
LogDebug("AddFactors: Added a rotation factor.");
return {rotation_factors_to_add};
}
} // namespace graph_localizer
| 48.613208 | 118 | 0.751019 | [
"vector"
] |
381cf82aa012a329a5ae11024829a43b31642b94 | 3,475 | hh | C++ | testData/parser/Types/Type_aliases_rf.hh | jhsx/hacklang-idea | 45d190444662c8ced0614c91f8fa7701f0936e95 | [
"MIT"
] | 3 | 2016-03-05T13:24:29.000Z | 2016-09-20T11:54:06.000Z | testData/parser/Types/Type_aliases_rf.hh | jhsx/hacklang-idea | 45d190444662c8ced0614c91f8fa7701f0936e95 | [
"MIT"
] | 1 | 2016-05-04T23:30:45.000Z | 2016-06-10T13:36:27.000Z | testData/parser/Types/Type_aliases_rf.hh | jhsx/hacklang-idea | 45d190444662c8ced0614c91f8fa7701f0936e95 | [
"MIT"
] | null | null | null | <?hh // strict
namespace NS_type_aliases;
// TTA == Transparent type alias
// OTA == Opaque type alias
// ------------------------------------------------------
type TTA1a = int;
newtype OTA1b = TTA1a;
type TTA1c = OTA1b;
// ------------------------------------------------------
type TTA_bool1 = bool;
newtype OTA_bool1 = bool;
type TTA_bool2 = bool; // duplicate aliases
newtype OTA_bool2 = bool; // duplicate aliases
type TTA_bool3 = TTA_bool1; // aliasing an alias
newtype OTA_bool3 = OTA_bool1; // aliasing an alias
// ------------------------------------------------------
type TTA_void = void;
newtype OTA_void = void;
type TTA_int = int;
type TTA_float = float;
type TTA_num = num;
type TTA_string = string;
type TTA_arraykey = arraykey;
type TTA_resource = resource;
type TTA_n_bool = ?TTA_bool1; // using a ? modifier + an alias
newtype OTA_n_bool = ?OTA_bool1; // using a ? modifier + an alias
type TTA_n_int = ?int;
type TTA_n_n_int = ?TTA_n_int; // I don't think this should be allowed
type TTA_mixed = mixed;
type TTA_n_mixed = ?TTA_mixed; // I don't think this should be allowed
// ------------------------------------------------------
enum Modes: int { Stopped = 0; Stopping = 1; Starting = 2; Started = 3; }
type TTA_enum_Modes = Modes;
newtype OTA_enum_Modes = Modes;
// ------------------------------------------------------
type TTA_array_string = array<string>;
newtype OTA_array_string = array<string>;
type TTA_array_array_string = array<array<string>>;
newtype OTA_array_array_string = array<array<string>>;
// ------------------------------------------------------
class Fullname {
public string $firstName = '';
public string $lastName = '';
}
type TTA_class_Fullname = Fullname;
newtype OTA_class_Fullname = Fullname;
// ------------------------------------------------------
interface MyCollection<T> {
public function put(T $item): void;
public function get(): T;
}
type TTA_interface_MyCollection1 = MyCollection;
type TTA_interface_MyCollection2<T> = MyCollection<T>; // Okay? Really?
type TTA_interface_MyCollection3 = MyCollection<int>;
// ------------------------------------------------------
trait TR1 { public function compute(): void {} }
trait TR2 { public function compute(): void {} }
trait TR3 { public function sort(): void {} }
trait TR4a {
use TR3;
use TR1, TR2;
}
/*
type TTA_trait1 = TR1; // TR1 is uninstantiable
type TTA_trait2 = TR2; // TR2 is uninstantiable
type TTA_trait3 = TR3; // TR3 is uninstantiable
trait TR4b {
use TTA_trait3;
use TTA_trait1, TTA_trait2;
}
*/
// ------------------------------------------------------
type TTA_tuple = (int, string, int);
newtype OTA_tuple = (int, string, int);
// ------------------------------------------------------
type TTA_closure = (function (int): void);
newtype OTA_closure = (function (int): void);
// ------------------------------------------------------
type TTA_shape_point = shape('x' => int, 'y' => int);
newtype OTA_shape_point = shape('x' => int, 'y' => int);
type TTA_shape_complex = shape('real' => float, 'imag' => float);
newtype OTA_shape_complex = shape('real' => float, 'imag' => float);
// ------------------------------------------------------
newtype Counter as int = int;
//newtype Counter as float = int; // float not compatible with int
//newtype Counter as num = int;
//newtype OTA_x1 as int = Fullname; // int not compatible with Fullname
// ------------------------------------------------------
| 28.719008 | 73 | 0.560288 | [
"shape"
] |
381d348bc09ef61eb4c9da32a18aebd677ae787e | 1,500 | cpp | C++ | tools/mull-dump-mutants/mull-dump-mutants.cpp | kateinoigakukun/mull-xctest | e7be5afa9afb64bef97dde29417c016af2a50dcc | [
"MIT"
] | 43 | 2021-03-04T04:57:41.000Z | 2022-03-03T17:16:54.000Z | tools/mull-dump-mutants/mull-dump-mutants.cpp | kateinoigakukun/mull-xctest | e7be5afa9afb64bef97dde29417c016af2a50dcc | [
"MIT"
] | 2 | 2021-03-09T10:32:29.000Z | 2021-10-19T12:01:25.000Z | tools/mull-dump-mutants/mull-dump-mutants.cpp | kateinoigakukun/mull-xctest | e7be5afa9afb64bef97dde29417c016af2a50dcc | [
"MIT"
] | 1 | 2021-03-09T14:29:17.000Z | 2021-03-09T14:29:17.000Z | #include "MullXCTest/MutantSerialization.h"
#include <llvm/Object/Binary.h>
#include <llvm/Object/MachO.h>
#include <llvm/Support/CommandLine.h>
#include <mull/Diagnostics/Diagnostics.h>
#include <mull/MutationPoint.h>
#include <mull/Mutators/MutatorsFactory.h>
#include <mull/Reporters/IDEReporter.h>
#include <mull/Version.h>
#include <sstream>
#include <vector>
using namespace llvm::cl;
using namespace llvm;
using namespace mull;
using namespace mull_xctest;
static std::string dumpMutant(mull::Mutant &mutant) {
std::stringstream ss;
ss << "Mutation Point: " << mutant.getMutatorIdentifier() << " "
<< mutant.getSourceLocation().filePath << ":"
<< mutant.getSourceLocation().line << ":"
<< mutant.getSourceLocation().column;
return ss.str();
}
opt<std::string> InputFile(Positional, desc("<input file>"), Required,
value_desc("path"));
int main(int argc, char **argv) {
bool validOptions =
llvm::cl::ParseCommandLineOptions(argc, argv, "", &llvm::errs());
if (!validOptions) {
return 1;
}
mull::Diagnostics diagnostics;
mull::MutatorsFactory factory(diagnostics);
factory.init();
auto result = ExtractMutantInfo(InputFile, factory, diagnostics);
if (!result) {
diagnostics.error(llvm::toString(result.takeError()));
}
if (result->empty()) {
llvm::outs() << "no mutant info found\n";
return 0;
}
for (auto &mutant : *result) {
llvm::outs() << dumpMutant(*mutant) << "\n";
}
return 0;
}
| 27.272727 | 71 | 0.673333 | [
"object",
"vector"
] |
3824ecaeb9e3e77103ee2684d9b62fc5ddb0c683 | 7,290 | cpp | C++ | Tests/DataFileGenerator.cpp | mpartio/MXADataModel | cfab4b41bca5c71d0ab16fb4f3ed3097093f0a57 | [
"BSD-3-Clause"
] | null | null | null | Tests/DataFileGenerator.cpp | mpartio/MXADataModel | cfab4b41bca5c71d0ab16fb4f3ed3097093f0a57 | [
"BSD-3-Clause"
] | null | null | null | Tests/DataFileGenerator.cpp | mpartio/MXADataModel | cfab4b41bca5c71d0ab16fb4f3ed3097093f0a57 | [
"BSD-3-Clause"
] | 1 | 2020-08-26T07:08:26.000Z | 2020-08-26T07:08:26.000Z | ///////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2007, 2010 Michael A. Jackson for BlueQuartz Software
// All rights reserved.
// BSD License: http://www.opensource.org/licenses/bsd-license.html
//
// This code was written under United States Air Force Contract number
// FA8650-04-C-5229
//
///////////////////////////////////////////////////////////////////////////////
#include "DataFileGenerator.h"
#include <MXA/HDF5/H5MXADataFile.h>
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
DataFileGenerator::DataFileGenerator()
{
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
DataFileGenerator::~DataFileGenerator()
{
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
void DataFileGenerator::setFilePath(const std::string &filePath)
{
this->_filePath = filePath;
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
herr_t DataFileGenerator::generate()
{
herr_t err = 1;
MXADataModel::Pointer modelPtr = MXADataModel::New();
MXADataModel* model = modelPtr.get();
model->setDataRoot( DataGen::DataRoot );
model->setModelType(MXA::MXACurrentFileType);
model->setModelVersion(MXA::MXACurrentFileVersion);
// ---------- Create the Required MetaData
std::map<std::string, std::string> md;
md[MXA::MXA_CREATOR_TAG] = "Mike Jackson";
md[MXA::MXA_DATE_TAG] = "2006:12:24 15:34.51";
md[MXA::MXA_DSET_NAME_TAG] = "Testing Data Import";
md[MXA::MXA_DESCRIPTION_TAG] = "Application to test importing data to the data file";
md[MXA::MXA_PEDIGREE_TAG] = "Original";
md[MXA::MXA_DERIVED_SRC_TAG] = "Original Data Files";
md[MXA::MXA_RIGHTS_TAG] = "Unlimited";
md[MXA::MXA_RELEASE_NUMBER_TAG] = "90312901291239012390";
model->setRequiredMetaData(md);
// ---------- Create 2 Data Dimensions
MXADataDimension::Pointer dim0 = MXADataDimension::New( DataGen::Dimension1, DataGen::Dimension1, 0, 2, 1, 2, 1, 1);
model->addDataDimension(dim0);
MXADataDimension::Pointer dim1 = MXADataDimension::New(DataGen::Dimension2, DataGen::Dimension2, 1, 3, 1, 3, 1, 1);
model->addDataDimension(dim1);
//Create the DataImport Class
MXADataImport::Pointer dataImport( new MXADataImport() );
// Create some Scalar Data
MXADataRecord::Pointer scalarRec = MXADataRecord::New(1, DataGen::ScalarRec, DataGen::ScalarRec);
modelPtr->addDataRecord(scalarRec);
std::vector<hsize_t> scalarDims;
scalarDims.push_back(1);
err = this->makeRecords(modelPtr, dataImport, scalarRec, scalarDims);
// ---------- Create top level Data Record to hold the vector data
MXADataRecord::Pointer tableRec = MXADataRecord::New(0, DataGen::TableRec, DataGen::TableRec );
modelPtr->addDataRecord(tableRec); // Add a top level Record
std::vector<hsize_t> tableDims;
tableDims.push_back(10); tableDims.push_back(10);
err = this->makeRecords(modelPtr, dataImport, tableRec, tableDims);
// Create some Scalar Data
MXADataRecord::Pointer volumeRec = MXADataRecord::New(2, DataGen::VolumeRec, DataGen::VolumeRec);
modelPtr->addDataRecord(volumeRec);
std::vector<hsize_t> volumeDims;
volumeDims.push_back(10); volumeDims.push_back(10); volumeDims.push_back(10);
err = this->makeRecords(modelPtr, dataImport, volumeRec, volumeDims);
// Write the model to the HDF5 File
IDataFile::Pointer dataFile = H5MXADataFile::CreateFileWithModel(_filePath, modelPtr);
if (NULL == dataFile.get() )
{
std::cout << logTime() << "Error writing Data Model" << std::endl;
return err;
}
// Set the MXADataModel Object into the dataImport Object
dataImport->setDataFile(dataFile);
//std::cout << "IMPORTING DATA NOW" << std::endl;
err = dataImport->import();
// std::cout << logTime() << "err=" << err << std::endl;
if (err < 0)
{
std::cout << logTime() << "Error Populating the H5 data file with test data" << std::endl;
}
return err;
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
herr_t DataFileGenerator::makeRecords(MXADataModel::Pointer modelPtr, MXADataImport::Pointer dataImport, MXADataRecord::Pointer parentRec, std::vector<hsize_t> dims)
{
#if 0
// Add all the Data for this record
MXADataRecord::Pointer int8_tRec = MXADataRecord::New(0, DataGen::Int8Rec, DataGen::Int8Rec );
modelPtr->addDataRecord(int8_tRec, parentRec);
this->createAndStore(modelPtr, int8_tRec, dataImport, MXATypes::Int8Type, dims);
MXADataRecord::Pointer int16_tRec = MXADataRecord::New(1, DataGen::Int16Rec, DataGen::Int16Rec );
modelPtr->addDataRecord(int16_tRec, parentRec);
this->createAndStore(modelPtr, int16_tRec, dataImport, MXATypes::Int16Type, dims);
MXADataRecord::Pointer int32_tRec = MXADataRecord::New(2, DataGen::Int32Rec, DataGen::Int32Rec );
modelPtr->addDataRecord(int32_tRec, parentRec);
this->createAndStore(modelPtr, int32_tRec, dataImport, MXATypes::Int32Type, dims);
MXADataRecord::Pointer int64_tRec = MXADataRecord::New(3, DataGen::Int64Rec, DataGen::Int64Rec );
modelPtr->addDataRecord(int64_tRec, parentRec);
this->createAndStore(modelPtr, int64_tRec, dataImport, MXATypes::Int64Type, dims);
// Add all the Data for this record
MXADataRecord::Pointer uint8_tRec = MXADataRecord::New(4, DataGen::Uint8_tRec, DataGen::Uint8_tRec );
modelPtr->addDataRecord(uint8_tRec, parentRec);
this->createAndStore(modelPtr, uint8_tRec, dataImport, MXATypes::Uint8_tType, dims);
MXADataRecord::Pointer uint16_tRec = MXADataRecord::New(5, DataGen::Uint16_tRec, DataGen::Uint16_tRec );
modelPtr->addDataRecord(uint16_tRec, parentRec);
this->createAndStore(modelPtr, uint16_tRec, dataImport, MXATypes::Uint16_tType, dims);
MXADataRecord::Pointer uint32_tRec = MXADataRecord::New(6, DataGen::Uint32_tRec, DataGen::Uint32_tRec );
modelPtr->addDataRecord(uint32_tRec, parentRec);
this->createAndStore(modelPtr, uint32_tRec, dataImport, MXATypes::Uint32_tType, dims);
MXADataRecord::Pointer uint64_tRec = MXADataRecord::New(7, DataGen::Uint64_tRec, DataGen::Uint64_tRec );
modelPtr->addDataRecord(uint64_tRec, parentRec);
this->createAndStore(modelPtr, uint64_tRec, dataImport, MXATypes::Uint64_tType, dims);
MXADataRecord::Pointer floatRec = MXADataRecord::New(8, DataGen::Float32Rec, DataGen::Float32Rec );
modelPtr->addDataRecord(floatRec, parentRec);
this->createAndStore(modelPtr, floatRec, dataImport, MXATypes::Float32Type, dims);
MXADataRecord::Pointer doubleRec = MXADataRecord::New(9, DataGen::Float64Rec, DataGen::Float64Rec );
modelPtr->addDataRecord(doubleRec, parentRec);
this->createAndStore(modelPtr, doubleRec, dataImport, MXATypes::Float64Type, dims);
#endif
return 1;
}
| 44.181818 | 165 | 0.628395 | [
"object",
"vector",
"model"
] |
38297392a7a425ce30c9f84d2907be6c2f111bbd | 3,700 | hpp | C++ | include/deft.hpp | EACcodes/deft | e9a7294e54e1a72152be4c36ef11178dbc7e1887 | [
"BSD-3-Clause"
] | null | null | null | include/deft.hpp | EACcodes/deft | e9a7294e54e1a72152be4c36ef11178dbc7e1887 | [
"BSD-3-Clause"
] | null | null | null | include/deft.hpp | EACcodes/deft | e9a7294e54e1a72152be4c36ef11178dbc7e1887 | [
"BSD-3-Clause"
] | null | null | null | #include <complex>
#include <memory>
#include <fftw3.h>
#include <armadillo>
using namespace std;
using namespace arma;
#ifndef __DEFT_HPP__
#define __DEFT_HPP__
class deft{
public:
// constructors
deft(const size_t, const size_t, const size_t, const double*, const double*, const double*);
deft(const deft&);
// read data
double at(const size_t, const size_t, const size_t) const;
double operator()(const size_t, const size_t, const size_t) const;
// copy data
void copy_data_from(const double*);
// assignment
void equals(const double);
void operator=(const double);
void equals(const deft);
void operator=(const deft);
// addition
void addEquals(const double);
void operator+=(const double);
void addEquals(const deft);
void operator+=(const deft);
// subtraction
void subtractEquals(const double);
void operator-=(const double);
void subtractEquals(const deft);
void operator-=(const deft);
// multiplication
void multiplyEquals(const double);
void operator*=(const double);
void multiplyEquals(const deft);
void operator*=(const deft);
// division
void divideEquals(const double);
void operator/=(const double);
void divideEquals(const deft);
void operator/=(const deft);
// elementwise math
void pow(const double);
// fourier transform operations
void computeFT();
void computeIFT();
// derivatives (using fourier transforms)
void compute_gradient_x();
void compute_gradient_y();
void compute_gradient_z();
void compute_gradient_squared();
void compute_laplacian();
// integrate
double integrate() const;
// update cell geometry and reciprocal lattice vectors
void updateGeometry(const double*, const double*, const double*);
// read cell information
double cellVecX(const size_t) const;
double cellVecY(const size_t) const;
double cellVecZ(const size_t) const;
double cellLenX() const;
double cellLenY() const;
double cellLenZ() const;
double vol() const;
double dv() const;
double kVecX(const size_t) const;
double kVecX(const size_t, const size_t, const size_t) const;
double kVecY(const size_t) const;
double kVecY(const size_t, const size_t, const size_t) const;
double kVecZ(const size_t) const;
double kVecZ(const size_t, const size_t, const size_t) const;
double kVecLen(const size_t) const;
double kVecLen(const size_t, const size_t, const size_t) const;
// interpolate
deft* interpolate(const size_t new_x, const size_t new_y, const size_t new_z);
// sum a function over a lattice
void sum_over_lattice(mat loc, double (*func)(double));
private:
public:
// real-space dimensions and data
const size_t _xDim;
const size_t _yDim;
const size_t _zDim;
const size_t _dimXYZ;
// TODO: decide whether this should remain a pointer
cube* _data;
private:
// cell geometry
shared_ptr<vec> _cellVecX;
shared_ptr<vec> _cellVecY;
shared_ptr<vec> _cellVecZ;
shared_ptr<double> _cellLenX;
shared_ptr<double> _cellLenY;
shared_ptr<double> _cellLenZ;
shared_ptr<double> _vol;
shared_ptr<double> _dv;
public:
// fourier-space dimensions and data
const size_t _xDimFT;
const size_t _yDimFT;
const size_t _zDimFT;
// TODO: add ft_numXYZ
cx_cube* _dataFT;
private:
// reciprocal lattice vectors
shared_ptr<cube> _kVecX;
shared_ptr<cube> _kVecY;
shared_ptr<cube> _kVecZ;
shared_ptr<cube> _kVecLen;
// fftw info
fftw_plan _planR2C;
fftw_plan _planC2R;
};
#endif // __DEFT_HPP__
| 24.832215 | 96 | 0.688108 | [
"geometry",
"transform"
] |
382d6c1b601ee55953d8f0b5f8b8cd8a65c59dd4 | 2,053 | hpp | C++ | gamma/mvp.hpp | fabianschuiki/gamma | ef5de69eae854267fecebdebd0c7fab7d7d2bf60 | [
"MIT"
] | 1 | 2017-11-09T02:15:41.000Z | 2017-11-09T02:15:41.000Z | gamma/mvp.hpp | fabianschuiki/gamma | ef5de69eae854267fecebdebd0c7fab7d7d2bf60 | [
"MIT"
] | 1 | 2015-08-10T20:54:11.000Z | 2015-08-10T20:54:11.000Z | gamma/mvp.hpp | fabianschuiki/gamma | ef5de69eae854267fecebdebd0c7fab7d7d2bf60 | [
"MIT"
] | null | null | null | /* Copyright (c) 2013-2014 Fabian Schuiki */
#pragma once
#include "gamma/matrix.hpp"
namespace gma {
template <typename T> struct mvp
{
typedef mvp<T> self;
typedef T scalar_type;
typedef matrix3<T> matrix3_type;
typedef matrix4<T> matrix4_type;
matrix4_type model;
matrix4_type view;
matrix4_type projection;
matrix4_type model_view;
matrix4_type model_view_projection;
matrix3_type normal;
mvp():
model(1),
view(1),
projection(1),
model_view(1),
model_view_projection(1),
normal(1) {}
mvp(
const matrix4_type& model,
const matrix4_type& view,
const matrix4_type& projection):
model(model),
view(view),
projection(projection),
model_view(view*model),
model_view_projection(projection*model_view),
normal(
#define m model_view
m.m11*m.m22-m.m21*m.m12, m.m20*m.m12-m.m10*m.m22, m.m10*m.m21-m.m20*m.m11,
m.m21*m.m02-m.m01*m.m22, m.m00*m.m22-m.m20*m.m02, m.m20*m.m01-m.m00*m.m21,
m.m01*m.m12-m.m11*m.m02, m.m10*m.m02-m.m00*m.m12, m.m00*m.m11-m.m10*m.m01
#undef m
) {}
mvp set (const matrix4_type& m, const matrix4_type& v, const matrix4_type& p) const { return mvp(m, v, p); }
mvp set_model (const matrix4_type& m) const { return mvp(m, view, projection); }
mvp set_view (const matrix4_type& v) const { return mvp(model, v, projection); }
mvp set_projection (const matrix4_type& p) const { return mvp(model, view, p); }
mvp mul_model (const matrix4_type& m) const { return mvp(model*m, view, projection); }
mvp mul_view (const matrix4_type& v) const { return mvp(model, view*v, projection); }
mvp mul_projection (const matrix4_type& p) const { return mvp(model, view, projection*p); }
mvp reset() const { return mvp(); }
mvp reset_model() const { return mvp(matrix4_type(1), view, projection); }
mvp reset_view() const { return mvp(model, matrix4_type(1), projection); }
mvp reset_projection() const { return mvp(model, view, matrix4_type(1)); }
};
typedef mvp<float> mvpf;
typedef mvp<double> mvpd;
} // namespace gma
| 31.584615 | 120 | 0.688261 | [
"model"
] |
382de71ec28f3fbd41a10e090c238649c0017b5e | 1,021 | cpp | C++ | easy/POINTS.cpp | VasuGoel/codechef-problems | 53951be4d2a5a507798fb83e25bdaa675f65077b | [
"MIT"
] | null | null | null | easy/POINTS.cpp | VasuGoel/codechef-problems | 53951be4d2a5a507798fb83e25bdaa675f65077b | [
"MIT"
] | null | null | null | easy/POINTS.cpp | VasuGoel/codechef-problems | 53951be4d2a5a507798fb83e25bdaa675f65077b | [
"MIT"
] | null | null | null | //
// Created by Vasu Goel on 2/10/20.
//
#include <bits/stdc++.h>
using namespace std;
typedef struct Point {
int x, y;
Point(int a, int b) {
this->x = a, this->y = b;
}
} point;
bool comparator(point a, point b) {
return a.x < b.x || (a.x == b.x && a.y >= b.y);
}
double coordinate_distance(point a, point b) {
return sqrt(pow(a.x - b.x, 2) + pow(a.y - b.y, 2));
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
int t, n, x, y;
cin >> t;
while(t--) {
cin >> n;
vector<point> coordinates;
while(n--) {
cin >> x >> y;
coordinates.push_back(point(x, y));
}
sort(coordinates.begin(), coordinates.end(), &comparator);
double distance = 0;
for(int i = 0; i < coordinates.size() - 1; i++) {
distance += coordinate_distance(coordinates[i], coordinates[i+1]);
}
cout << std::fixed << std::setprecision( 2 ) << distance << '\n';
}
return 0;
} | 23.204545 | 78 | 0.516161 | [
"vector"
] |
382f093d6aef56416c5fc77915ff800a0bd49873 | 3,015 | hpp | C++ | test/module/shared_model/builders/common_objects/account_asset_builder.hpp | coderintherye/iroha | 68509282851130c9818f21acef1ef28e53622315 | [
"Apache-2.0"
] | null | null | null | test/module/shared_model/builders/common_objects/account_asset_builder.hpp | coderintherye/iroha | 68509282851130c9818f21acef1ef28e53622315 | [
"Apache-2.0"
] | null | null | null | test/module/shared_model/builders/common_objects/account_asset_builder.hpp | coderintherye/iroha | 68509282851130c9818f21acef1ef28e53622315 | [
"Apache-2.0"
] | null | null | null | /**
* Copyright Soramitsu Co., Ltd. 2018 All Rights Reserved.
* http://soramitsu.co.jp
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef IROHA_ACCOUNT_ASSET_BUILDER_HPP
#define IROHA_ACCOUNT_ASSET_BUILDER_HPP
#include "interfaces/common_objects/account_asset.hpp"
#include "module/shared_model/builders/common_objects/common.hpp"
// TODO: 14.02.2018 nickaleks Add check for uninitialized fields IR-972
namespace shared_model {
namespace builder {
/**
* AccountAssetBuilder is a class, used for construction of AccountAsset
* objects
* @tparam BuilderImpl is a type, which defines builder for implementation
* of shared_model. Since we return abstract classes, it is necessary for
* them to be instantiated with some concrete implementation
* @tparam Validator is a type, whose responsibility is
* to perform stateless validation on model fields
*/
template <typename BuilderImpl, typename Validator>
class DEPRECATED AccountAssetBuilder
: public CommonObjectBuilder<interface::AccountAsset,
BuilderImpl,
Validator> {
public:
AccountAssetBuilder accountId(
const interface::types::AccountIdType &account_id) {
AccountAssetBuilder copy(*this);
copy.builder_ = this->builder_.accountId(account_id);
return copy;
}
AccountAssetBuilder assetId(
const interface::types::AssetIdType &asset_id) {
AccountAssetBuilder copy(*this);
copy.builder_ = this->builder_.assetId(asset_id);
return copy;
}
AccountAssetBuilder balance(const interface::Amount &amount) {
AccountAssetBuilder copy(*this);
copy.builder_ = this->builder_.balance(amount);
return copy;
}
protected:
virtual std::string builderName() const override {
return "Account Asset Builder";
}
virtual validation::ReasonsGroupType validate(
const interface::AccountAsset &object) override {
validation::ReasonsGroupType reasons;
this->validator_.validateAccountId(reasons, object.accountId());
this->validator_.validateAssetId(reasons, object.assetId());
// Do not validate balance, since its amount can be 0, which is
// forbidden by validation
return reasons;
}
};
} // namespace builder
} // namespace shared_model
#endif // IROHA_ACCOUNT_ASSET_BUILDER_HPP
| 36.768293 | 78 | 0.688557 | [
"object",
"model"
] |
383c62e3c7151383011d53ef57e54958cb6cd259 | 3,487 | cpp | C++ | libraries/utils/khepera.cpp | LucasWaelti/RL_Webots | 778091996434a9acb217d10941b629c2154d638f | [
"MIT"
] | 32 | 2020-04-06T13:27:26.000Z | 2022-02-21T06:39:17.000Z | libraries/utils/khepera.cpp | LucasWaelti/RL_Webots | 778091996434a9acb217d10941b629c2154d638f | [
"MIT"
] | null | null | null | libraries/utils/khepera.cpp | LucasWaelti/RL_Webots | 778091996434a9acb217d10941b629c2154d638f | [
"MIT"
] | 6 | 2020-04-16T03:04:39.000Z | 2020-10-07T07:56:02.000Z | #include "khepera.hpp"
static int time_step = 8;
static const char *infrared_sensors_names[NUMBER_OF_INFRARED_SENSORS] = {
// turret sensors
"rear left infrared sensor", "left infrared sensor", "front left infrared sensor", "front infrared sensor",
"front right infrared sensor", "right infrared sensor", "rear right infrared sensor", "rear infrared sensor",
// ground sensors
"ground left infrared sensor", "ground front left infrared sensor", "ground front right infrared sensor",
"ground right infrared sensor"};
// Declare required device tags
static WbDeviceTag leds[3];
static WbDeviceTag infrared_sensors[12];
static WbDeviceTag left_motor, right_motor;
int k4::init_robot(){
wb_robot_init();
time_step = (int)wb_robot_get_basic_time_step();
// get and enable the infrared sensors
for (int i = 0; i < 12; ++i) {
infrared_sensors[i] = wb_robot_get_device(infrared_sensors_names[i]);
wb_distance_sensor_enable(infrared_sensors[i], time_step);
}
// get the led actuators
leds[0] = wb_robot_get_device("front left led");
leds[1] = wb_robot_get_device("front right led");
leds[2] = wb_robot_get_device("rear led");
for (int i = 0; i < 3; ++i)
wb_led_set(leds[i], 0xFFFFFF & rand());
// get the motors and set target position to infinity (speed control)
left_motor = wb_robot_get_device("left wheel motor");
right_motor = wb_robot_get_device("right wheel motor");
wb_motor_set_position(left_motor, INFINITY);
wb_motor_set_position(right_motor, INFINITY);
wb_motor_set_velocity(left_motor, 0.0);
wb_motor_set_velocity(right_motor, 0.0);
return time_step;
}
int k4::khepera_running(){
return (wb_robot_step(time_step) != -1) ? 1 : 0;
}
void k4::set_motors_speed(double left, double right){
wb_motor_set_velocity(left_motor, left);
wb_motor_set_velocity(right_motor, right);
}
std::vector<double> k4::get_motors_speed(){
std::vector<double> speed;
speed.push_back(wb_motor_get_velocity(left_motor));
speed.push_back(wb_motor_get_velocity(right_motor));
return speed;
}
void k4::set_normalized_motors_speed(double left, double right){
if(abs(left)>1 || abs(right)>1){
std::cout << "ERROR in set_normalized_motors_speed: input must be in [-1,1]" <<std::endl;
set_motors_speed(0.0,0.0);
return;
}
set_motors_speed(left*MAX_SPEED*REDUCER,right*MAX_SPEED*REDUCER);
}
std::vector<double> k4::get_normalized_motors_speed(){
std::vector<double> speed = get_motors_speed();
speed[0] /= (MAX_SPEED*REDUCER);
speed[1] /= (MAX_SPEED*REDUCER);
return speed;
}
double k4::normalize_range(double range){
double offset = 50.0;
double value = (range - IR_MIN - offset)/(IR_MAX - IR_MIN - offset);
if(value < 0.0)
value = 0.0;
else if(value > 1.0)
value = 1.0;
return value;
}
double k4::get_range(int i){
return wb_distance_sensor_get_value(infrared_sensors[i]);
}
std::vector<double> k4::get_ranges(){
std::vector<double> ranges;
for(int i=0; i<NUMBER_OF_PERIMETER_IR_SENSORS; i++)
ranges.push_back(wb_distance_sensor_get_value(infrared_sensors[i]));
return ranges;
}
std::vector<double> k4::get_normalized_ranges(){
std::vector<double> ranges;
for(int i=0; i<NUMBER_OF_PERIMETER_IR_SENSORS; i++)
ranges.push_back(normalize_range(wb_distance_sensor_get_value(infrared_sensors[i])));
return ranges;
} | 32.896226 | 111 | 0.698882 | [
"vector"
] |
383c64a0a04fc0315d6ab9e3fe8b5b3eaee89632 | 56,820 | cpp | C++ | src/shadingfactors.cpp | bje-/SAM | a52536b211c90a8e5fb15e4998212f313abcbfbe | [
"BSD-3-Clause"
] | 219 | 2017-07-28T17:25:14.000Z | 2022-03-17T23:03:17.000Z | src/shadingfactors.cpp | bje-/SAM | a52536b211c90a8e5fb15e4998212f313abcbfbe | [
"BSD-3-Clause"
] | 729 | 2017-08-10T14:42:30.000Z | 2022-03-31T23:14:09.000Z | src/shadingfactors.cpp | bje-/SAM | a52536b211c90a8e5fb15e4998212f313abcbfbe | [
"BSD-3-Clause"
] | 109 | 2017-09-16T00:52:54.000Z | 2022-03-31T18:05:05.000Z | /**
BSD-3-Clause
Copyright 2019 Alliance for Sustainable Energy, LLC
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, CONTRIBUTORS, UNITED STATES GOVERNMENT OR UNITED STATES
DEPARTMENT OF ENERGY, NOR ANY OF THEIR EMPLOYEES, 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 <wx/clipbrd.h>
#include <wx/dcbuffer.h>
#include <wx/filename.h>
#include <wx/notebook.h>
#include <wx/statline.h>
#include <wx/tokenzr.h>
#include <wx/textfile.h>
#include <fstream>
#include <wex/csv.h>
#include "main.h"
#include "widgets.h"
#include "variables.h"
#include "shadingfactors.h"
/********* SHADING BUTTON CTRL ************/
ShadingInputData::ShadingInputData()
{
clear();
}
void ShadingInputData::save( std::vector<double> &data )
{
data.clear();
// data.push_back(3.0); // version number of data format - allows for expansion of options in future.
data.push_back(4.0); // version number of data format - allows for expansion of options in future.
data.push_back((en_mxh && mxh.nrows() == 12 && mxh.ncols() == 24) ? 1.0 : 0.0);
data.push_back( en_azal ? 1.0 : 0.0 );
data.push_back( en_diff ? 1.0 : 0.0 );
data.push_back( -1.0 );
data.push_back( -1.0 );
data.push_back( -1.0 );
if ( mxh.nrows() != 12 || mxh.ncols() != 24 )
mxh.resize_fill(12, 24, 0.0);
for (int r=0;r<12;r++)
for (int c=0;c<24;c++)
data.push_back( mxh.at(r,c) );
data.push_back( azal.nrows() );
data.push_back( azal.ncols() );
for (size_t r=0;r<azal.nrows();r++)
for (size_t c=0;c<azal.ncols();c++)
data.push_back( azal.at(r,c) );
data.push_back( diff );
// timestep at end for potential backwards compatibility
// timestep string shading fractions matrix added timestep x number of parallel strings
data.push_back((en_timestep && (timestep.nrows() % 8760 == 0)) ? 1.0 : 0.0);
data.push_back(timestep.nrows());
data.push_back(timestep.ncols());
for (size_t r = 0; r < timestep.nrows(); r++)
for (size_t c = 0; c < timestep.ncols(); c++)
data.push_back(timestep.at(r, c));
data.push_back(((string_option >= 0) && (timestep.nrows() % 8760 == 0) && en_timestep) ? string_option : -1);
data.push_back( data.size() + 1 ); // verification flag that size is consistent
}
void ShadingInputData::clear()
{
en_mxh = en_azal = en_diff = en_timestep = false;
timestep.resize(8760, 0);
mxh.resize_fill(12,24, 0.0);
azal.resize_fill(10, 18, 0.0);
for ( int c=0;c<18;c++ )
azal.at(0, c) = c*20;
for ( int r=0;r<10;r++ )
azal.at(r, 0) = r*10;
diff = 0.0;
string_option = 0;
}
bool ShadingInputData::load( const std::vector<double> &data )
{
clear();
if (data.size() < 3) return false;
if (data.size() != (size_t)data[ data.size() - 1 ]) return false; // verification check
int idx = 0; // indexer to step through data
int ver = (int)data[idx++];
if (ver == 2)
{
en_timestep = data[idx++] > 0 ? true : false;
en_mxh = data[idx++] > 0 ? true : false;
en_azal = data[idx++] > 0 ? true : false;
en_diff = data[idx++] > 0 ? true : false;
idx++; // skip unused -1
idx++; // skip unused -1
idx++; // skip unused -1
timestep.resize_fill(8760, 1, 0);
for (int r = 0; r<8760; r++)
timestep.at(r, 0) = data[idx++];
for (int r=0;r<12;r++)
for (int c=0;c<24;c++)
mxh.at(r,c) = data[idx++];
int nr = (int)data[idx++];
int nc = (int)data[idx++];
azal.resize_fill( nr, nc, 1.0 );
for (int r=0;r<nr;r++)
for (int c=0;c<nc;c++)
azal.at(r,c) = data[idx++];
diff = data[idx++];
int verify = data[idx++];
return idx == verify;
}
else
{
en_mxh = data[idx++] > 0 ? true : false;
en_azal = data[idx++] > 0 ? true : false;
en_diff = data[idx++] > 0 ? true : false;
idx++; // skip unused -1
idx++; // skip unused -1
idx++; // skip unused -1
for (int r = 0; r<12; r++)
for (int c = 0; c<24; c++)
mxh.at(r, c) = data[idx++];
int nr = (int)data[idx++];
int nc = (int)data[idx++];
azal.resize_fill(nr, nc, 1.0);
for (int r = 0; r<nr; r++)
for (int c = 0; c<nc; c++)
azal.at(r, c) = data[idx++];
diff = data[idx++];
en_timestep = data[idx++] > 0 ? true : false;
nr = (int)data[idx++];
nc = (int)data[idx++];
timestep.resize_fill(nr, nc, 0);
for (int r = 0; r<nr; r++)
for (int c = 0; c<nc; c++)
timestep.at(r, c) = data[idx++];
string_option = data[idx++];
int verify = data[idx++];
return idx == verify;
}
}
void ShadingInputData::write( VarValue *vv )
{
vv->SetType( VV_TABLE );
VarTable &tab = vv->Table();
tab.Set("en_string_option", VarValue(true)); // to enable optional values
if (!en_timestep) string_option = -1;
tab.Set("string_option", VarValue((int)string_option));
tab.Set("en_timestep", VarValue((bool)en_timestep));
tab.Set("timestep", VarValue(timestep));
tab.Set("en_mxh", VarValue((bool)en_mxh));
tab.Set( "mxh", VarValue( mxh ) );
tab.Set( "en_azal", VarValue( (bool)en_azal ) );
tab.Set( "azal", VarValue( azal ) );
tab.Set( "en_diff", VarValue( (bool)en_diff ) );
tab.Set( "diff", VarValue( (float)diff ) );
}
bool ShadingInputData::read( VarValue *root )
{
clear();
if ( root->Type() == VV_TABLE )
{
VarTable &tab = root->Table();
if (VarValue *vv = tab.Get("string_option")) string_option = vv->Integer();
if (VarValue *vv = tab.Get("en_timestep")) en_timestep = vv->Boolean();
if (VarValue *vv = tab.Get("timestep")) timestep = vv->Matrix();
if (VarValue *vv = tab.Get("en_mxh")) en_mxh = vv->Boolean();
if ( VarValue *vv = tab.Get("mxh") ) mxh = vv->Matrix();
if ( VarValue *vv = tab.Get("en_azal") ) en_azal = vv->Boolean();
if ( VarValue *vv = tab.Get("azal") ) azal = vv->Matrix();
if ( VarValue *vv = tab.Get("en_diff") ) en_diff = vv->Boolean();
if ( VarValue *vv = tab.Get("diff") ) diff = vv->Value();
return true;
}
else
return false;
}
static const char *hourly_text_basic = "Enter or import a beam shading loss percentage for each of the simulation time steps in a single year. No shading is 0%, and full shading is 100%. Choose a time step in minutes equivalent to the weather file time step.\n\nNote that the 3D Shade Calculator automatically populates this beam shading table.";
static const char *hourly_text_strings = "Enter or import a beam shading loss percentage for each of the simulation time steps in a single year. No shading is 0%, and full shading is 100%. Choose a time step in minutes equivalent to the weather file time step. For a subarray of modules with c-Si cells and up to 8 strings of modules, you can use the partial shading model to estimate the impact of partial shading on the subarray's DC output.\n\nIf you use the 3D Shade Calculator to populate this beam shading table, be sure that the active surface subarray number(s) and string number(s) match the system design.";
static const char *mxh_text = "Enter 288 (24 hours x 12 month) beam shading loss percentages that apply to the 24 hours of the day for each month of the year. No shading is 0%, and full shading is 100%. Select a cell or group of cells and type a number to assign values to the table by hand. Click Import to import a table of values from a properly formatted text file. Click Export to export the data to a text file, or to create a template file for importing.";
static const char *azal_text = "Use the Azimuth by Altitude option if you have a set of beam shading losses for different sun positions.\n\n"
"1. Define the size of the table by entering values for the number of rows and columns.\n"
"2. Enter solar azimuth values (0 to 360 degrees) in the first row of the table, where 0 = north, 90 = east, 180 = south, 270 = west.\n"
"3. Enter solar altitude values (0 to 90 degrees) in the first column of the table, where zero is on the horizon.\n"
"4. Enter shading losses as the shaded percentage of the beam component of the incident radiation in the remaining table cells. No shading is 0%, and full shading is 100%.\n\n"
"Click Paste to populate the table from your computer\'s clipboard, or click Import to import a table of values from a properly formatted text file. Click Export to export the data to a text file, or to create a template file for importing.";
static const char *diff_text = "The constant sky diffuse shading loss reduces the diffuse irradiance for each time step in the year. Valid values are between 0% and 100%.";
enum { ID_ENABLE_HOURLY = ::wxID_HIGHEST+999,
ID_ENABLE_MXH, ID_ENABLE_AZAL, ID_ENABLE_DIFF,
ID_IMPORT_PVSYST_NEAR_SHADING,
ID_IMPORT_SUNEYE_HOURLY,
ID_IMPORT_SUNEYE_OBSTRUCTIONS,
ID_IMPORT_SOLPATH_MXH};
class ShadingDialog : public wxDialog
{
wxScrolledWindow *m_scrollWin;
wxCheckBox *m_enableTimestep;
wxShadingFactorsCtrl *m_timestep;
wxStaticText *m_textTimestep;
wxCheckBox *m_enableMxH;
AFMonthByHourFactorCtrl *m_mxh;
wxStaticText *m_textMxH;
wxCheckBox *m_enableAzal;
AFDataMatrixCtrl *m_azal;
wxStaticText *m_textAzal;
wxCheckBox *m_enableDiffuse;
wxNumericCtrl *m_diffuseFrac;
wxStaticText *m_textDiffuse;
bool m_show_db_options;
public:
ShadingDialog( wxWindow *parent, const wxString &descText, bool show_db_options = false )
: wxDialog( parent, wxID_ANY,
wxString("Edit Shading Data") + wxString( (!descText.IsEmpty() ? " for " : "") ) + descText,
wxDefaultPosition, wxScaleSize(950,600),
wxDEFAULT_DIALOG_STYLE|wxRESIZE_BORDER)
{
SetEscapeId( wxID_CANCEL );
m_show_db_options = show_db_options;
m_scrollWin = new wxScrolledWindow( this, wxID_ANY );
m_scrollWin->SetScrollRate( 50, 50 );
m_enableTimestep = new wxCheckBox( m_scrollWin, ID_ENABLE_HOURLY, "Enable beam irradiance shading losses by time step" );
m_timestep = new wxShadingFactorsCtrl(m_scrollWin, wxID_ANY, wxDefaultPosition, wxDefaultSize, m_show_db_options);
m_timestep->SetInitialSize(wxScaleSize(900, 300));
m_timestep->SetMinuteCaption("Time step in minutes:");
m_timestep->SetColCaption(wxString("Strings") + wxString((!descText.IsEmpty() ? " in " : "")) + descText + wxString((!descText.IsEmpty() ? ":" : "")));
// m_timestep->SetStringCaption(wxString("Method for converting string losses to subarray:"));
m_timestep->SetDBCaption(wxString("Enable partial shading model (c-Si modules only)"));
int num_cols = 8;
matrix_t<double> ts_data(8760, num_cols, 0.);
m_timestep->SetData(ts_data);
m_enableMxH = new wxCheckBox( m_scrollWin, ID_ENABLE_MXH, "Enable month-by-hour beam irradiance shading losses" );
m_mxh = new AFMonthByHourFactorCtrl( m_scrollWin, wxID_ANY );
m_mxh->SetInitialSize( wxScaleSize(900,330) );
m_enableAzal = new wxCheckBox( m_scrollWin, ID_ENABLE_AZAL, "Enable solar azimuth-by-altitude beam irradiance shading losses" );
//m_azal = new AFDataMatrixCtrl(m_scrollWin, wxID_ANY);
// bottom buttons for import/export and added row and column labels
m_azal = new AFDataMatrixCtrl(m_scrollWin, wxID_ANY, wxDefaultPosition, wxDefaultSize, false, wxEmptyString, wxEmptyString, wxEmptyString, -1, true);
m_azal->SetInitialSize( wxScaleSize(900,280) );
//m_azal->ShowRowLabels( false );
m_azal->SetNumRowsLabel("Number of altitude values (rows):");
m_azal->SetNumColsLabel("Number of azimuth values (columns):");
m_azal->PasteAppendCols(true);
m_azal->PasteAppendRows(true);
m_azal->ShadeR0C0(true);
matrix_t<double> data(10, 18, 0.);
for ( int c=0;c<18;c++ )
data.at(0, c) = c*20;
for ( int r=0;r<10;r++ )
data.at(r, 0) = r*10;
m_azal->SetData( data );
m_enableDiffuse = new wxCheckBox( m_scrollWin, ID_ENABLE_DIFF, "Enable constant sky diffuse shading loss" );
m_diffuseFrac = new wxNumericCtrl( m_scrollWin, wxID_ANY, 0.0 );
wxSizer *import_tools = new wxStaticBoxSizer( wxHORIZONTAL, m_scrollWin, "Import shading data from external tools");
import_tools->Add( new wxButton( m_scrollWin, ID_IMPORT_PVSYST_NEAR_SHADING, "PVsyst near shading..." ), 0, wxALL, 3 );
import_tools->Add( new wxButton( m_scrollWin, ID_IMPORT_SUNEYE_HOURLY, "SunEye hourly shading..." ), 0, wxALL, 3 );
import_tools->Add( new wxButton( m_scrollWin, ID_IMPORT_SUNEYE_OBSTRUCTIONS, "SunEye obstructions table..." ), 0, wxALL, 3 );
import_tools->Add( new wxButton( m_scrollWin, ID_IMPORT_SOLPATH_MXH, "SolarPathfinder month-by-hour shading..." ), 0, wxALL, 3 );
wxColour text_color( 0, 128, 192 );
int wrap_width = 700;
wxSizer *scroll = new wxBoxSizer( wxVERTICAL );
scroll->Add( import_tools, 0, wxALL, 5 );
scroll->Add( new wxStaticLine( m_scrollWin ), 0, wxALL|wxEXPAND );
scroll->Add( m_enableTimestep, 0, wxALL|wxEXPAND, 5 );
scroll->Add( m_textTimestep = new wxStaticText( m_scrollWin, wxID_ANY, !descText.IsEmpty() ? hourly_text_strings : hourly_text_basic ), 0, wxALL|wxEXPAND, 10 );
scroll->Add( m_timestep, 0, wxALL, 5 );
m_textTimestep->Wrap(wrap_width);
m_textTimestep->SetForegroundColour(text_color);
scroll->Add( new wxStaticLine( m_scrollWin ), 0, wxALL|wxEXPAND );
scroll->Add( m_enableMxH, 0, wxALL|wxEXPAND, 5 );
scroll->Add( m_textMxH = new wxStaticText( m_scrollWin, wxID_ANY, mxh_text ), 0, wxALL|wxEXPAND, 10 );
scroll->Add( m_mxh, 0, wxALL, 5 );
m_textMxH->Wrap( wrap_width );
m_textMxH->SetForegroundColour( text_color );
scroll->Add( new wxStaticLine( m_scrollWin ), 0, wxALL|wxEXPAND );
scroll->Add( m_enableAzal, 0, wxALL|wxEXPAND, 5 );
scroll->Add( m_textAzal = new wxStaticText( m_scrollWin, wxID_ANY, azal_text ), 0, wxALL|wxEXPAND, 10 );
scroll->Add( m_azal, 0, wxALL, 5 );
m_textAzal->Wrap( wrap_width );
m_textAzal->SetForegroundColour( text_color );
scroll->Add( new wxStaticLine( m_scrollWin ), 0, wxALL|wxEXPAND );
scroll->Add( m_enableDiffuse, 0, wxALL|wxEXPAND, 5 );
scroll->Add( m_textDiffuse = new wxStaticText( m_scrollWin, wxID_ANY, diff_text ), 0, wxALL|wxEXPAND, 10 );
scroll->Add( m_diffuseFrac, 0, wxALL, 5 );
m_textDiffuse->Wrap( wrap_width );
m_textDiffuse->SetForegroundColour( text_color );
m_scrollWin->SetSizer( scroll );
wxSizer *box = new wxBoxSizer(wxVERTICAL);
box->Add( m_scrollWin, 1, wxALL|wxEXPAND );
box->Add( CreateButtonSizer(wxOK|wxCANCEL|wxHELP), 0, wxALL|wxEXPAND, 10 );
SetSizer( box );
UpdateVisibility();
}
void UpdateVisibility()
{
m_timestep->Show( m_enableTimestep->IsChecked() );
m_textTimestep->Show( m_enableTimestep->IsChecked() );
m_mxh->Show( m_enableMxH->IsChecked() );
m_textMxH->Show( m_enableMxH->IsChecked() );
m_azal->Show( m_enableAzal->IsChecked() );
m_textAzal->Show( m_enableAzal->IsChecked() );
m_diffuseFrac->Show( m_enableDiffuse->IsChecked() );
m_textDiffuse->Show( m_enableDiffuse->IsChecked() );
m_scrollWin->FitInside();
m_scrollWin->Refresh();
}
void ImportData( wxCommandEvent &e )
{
ShadingInputData dat;
switch( e.GetId() )
{
case ID_IMPORT_PVSYST_NEAR_SHADING:
if ( ImportPVsystNearShading( dat, this ) )
{
wxMessageBox( Load( dat, false ) );
UpdateVisibility();
}
break;
case ID_IMPORT_SUNEYE_HOURLY:
if ( ImportSunEyeHourly( dat, this ) )
{
wxMessageBox( Load( dat, false ) );
UpdateVisibility();
}
break;
case ID_IMPORT_SUNEYE_OBSTRUCTIONS:
if ( ImportSunEyeObstructions( dat, this ) )
{
wxMessageBox( Load( dat, false ) );
UpdateVisibility();
}
break;
case ID_IMPORT_SOLPATH_MXH:
if ( ImportSolPathMonthByHour( dat, this ) )
{
wxMessageBox( Load( dat, false ) );
UpdateVisibility();
}
break;
}
}
void OnCommand( wxCommandEvent &e )
{
switch( e.GetId() )
{
case wxID_HELP:
SamApp::ShowHelp("edit_shading_data");
break;
case ID_ENABLE_HOURLY:
case ID_ENABLE_MXH:
case ID_ENABLE_AZAL:
case ID_ENABLE_DIFF:
UpdateVisibility();
break;
}
}
void OnClose( wxCloseEvent & )
{
EndModal( wxID_CANCEL );
}
wxString Load( ShadingInputData &sh, bool all = true )
{
wxString stat;
if (all || sh.en_timestep)
{
m_enableTimestep->SetValue(sh.en_timestep);
if (sh.timestep.nrows() < 8760 || sh.timestep.ncols() > 8)
{
sh.timestep.resize_fill(8760, 1, 0);
}
m_timestep->SetData(sh.timestep);
size_t ncols = sh.timestep.ncols();
m_timestep->SetNumCols(ncols);
size_t nminutes = 60;
if ((sh.timestep.nrows() / 8760) > 0)
nminutes /= (sh.timestep.nrows() / 8760);
m_timestep->SetNumMinutes(nminutes);
stat += "Updated timestep beam shading losses.\n";
int string_option = sh.string_option;
m_timestep->SetDBOption(string_option);
// m_timestep->SetStringOption(string_option);
}
if ( all || sh.en_mxh )
{
m_enableMxH->SetValue( sh.en_mxh );
m_mxh->SetData( sh.mxh );
stat += "Updated month-by-hour beam shading loss table.\n";
}
if ( all || sh.en_azal )
{
m_enableAzal->SetValue( sh.en_azal );
m_azal->SetData( sh.azal );
stat += "Updated azimuth-by-altitude beam shading factor table.\n";
}
if ( all || sh.en_diff )
{
m_enableDiffuse->SetValue( sh.en_diff );
m_diffuseFrac->SetValue( sh.diff );
stat += "Updated constant sky diffuse factor.\n";
}
UpdateVisibility();
return stat;
}
void Save( ShadingInputData &sh )
{
sh.en_timestep = m_enableTimestep->IsChecked();
m_timestep->GetData(sh.timestep);
sh.string_option = m_timestep->GetDBOption();
// sh.string_option = m_timestep->GetStringOption();
sh.en_mxh = m_enableMxH->IsChecked();
sh.mxh.copy( m_mxh->GetData() );
sh.en_azal = m_enableAzal->IsChecked();
m_azal->GetData( sh.azal );
sh.en_diff = m_enableDiffuse->IsChecked();
sh.diff = m_diffuseFrac->Value();
}
DECLARE_EVENT_TABLE()
};
BEGIN_EVENT_TABLE( ShadingDialog, wxDialog )
EVT_CLOSE( ShadingDialog::OnClose )
EVT_CHECKBOX( ID_ENABLE_HOURLY, ShadingDialog::OnCommand )
EVT_CHECKBOX( ID_ENABLE_MXH, ShadingDialog::OnCommand )
EVT_CHECKBOX( ID_ENABLE_AZAL, ShadingDialog::OnCommand )
EVT_CHECKBOX( ID_ENABLE_DIFF, ShadingDialog::OnCommand )
EVT_BUTTON( ID_IMPORT_PVSYST_NEAR_SHADING, ShadingDialog::ImportData )
EVT_BUTTON( ID_IMPORT_SUNEYE_HOURLY, ShadingDialog::ImportData )
EVT_BUTTON( ID_IMPORT_SUNEYE_OBSTRUCTIONS, ShadingDialog::ImportData )
EVT_BUTTON( ID_IMPORT_SOLPATH_MXH, ShadingDialog::ImportData )
EVT_BUTTON( wxID_HELP, ShadingDialog::OnCommand )
END_EVENT_TABLE()
BEGIN_EVENT_TABLE(ShadingButtonCtrl, wxButton)
EVT_BUTTON(wxID_ANY, ShadingButtonCtrl::OnPressed)
END_EVENT_TABLE()
ShadingButtonCtrl::ShadingButtonCtrl(wxWindow *parent, int id, bool show_db_options,
const wxPoint &pos, const wxSize &size)
: wxButton( parent, id, "Edit shading...", pos, size )
{
m_show_db_options = show_db_options;
}
void ShadingButtonCtrl::Write( VarValue *vv )
{
m_shad.write( vv );
}
bool ShadingButtonCtrl::Read( VarValue *vv )
{
return m_shad.read( vv );
}
void ShadingButtonCtrl::OnPressed(wxCommandEvent &evt)
{
ShadingDialog dlg( this, m_descText, m_show_db_options );
dlg.Load( m_shad );
if (dlg.ShowModal()==wxID_OK)
{
dlg.Save( m_shad );
evt.Skip(); // allow event to propagate indicating underlying value changed
}
}
/***************************************************************
Utility functions to import externally generated shading data
**************************************************************/
bool ImportPVsystNearShading( ShadingInputData &dat, wxWindow *parent )
{
//ask about version of PVsyst (5 versus 6) due to change in shading convention
bool new_version = true;
wxString msg = "Is this shading file from PVsyst version 6 or newer?";
msg += "\n\nPVsyst changed their shading convention starting in Version 6 and later such that 0 now equals no shade and 1 equals full shade. ";
msg += "To import a file from PVsyst versions 6 or newer, click Yes below. However, you may still import a file from versions 5 and older by selecting No below.";
int ret = wxMessageBox(msg, "Important Notice", wxICON_EXCLAMATION | wxYES_NO, parent);
if (ret == wxNO)
new_version = false;
//read in the file
wxString buf;
double diffuse = 0.0;
int i;
int j;
bool readdata = false;
bool readok = true;
bool headingok = true;
bool colok = true;
int linesok = 0;
matrix_t<double> azaltvals;
azaltvals.resize_fill(11,20, 0.0f);
azaltvals.at(0,0) = 0.0f;
for (i=1;i<20;i++) azaltvals.at(0,i) = 20*(i-1); // removed -180 degree offset to account for new azimuth convention (180=south) 4/2/2012, apd
for (i=1;i<10;i++) azaltvals.at(i,0) = 10*i;
azaltvals.at(10,0) = 2.0f;
wxFileDialog fdlg(parent, "Import PVsyst Near Shading File");
if (fdlg.ShowModal() != wxID_OK) return false;
wxString file = fdlg.GetPath();
wxTextFile tf;
if ( !tf.Open( file ) )
{
wxMessageBox("Could not open file for read:\n\n" + file);
return false;
}
j = 0;
buf = tf.GetFirstLine();
while( !tf.Eof() )
{
wxArrayString lnp = wxStringTokenize( buf, ";:,\t" );
if (readdata == false && j == 0)
{
if (lnp.Count() > 0)
{
if (lnp.Item(0) == "Height") readdata = true;
}
}
else if (j < 10)
{
j++;
if (lnp.Count() != 20)
{
colok = false;
readok = false;
break;
}
else
{
for (i = 0; i<20; i++) // read in Altitude in column zero
{
if (i == 0) azaltvals.at(j, i) = (float)wxAtof(lnp[i]); //do not change azimuth values
else
{
if (lnp.Item(i) == "Behind")
azaltvals.at(j, i) = 100; //"Behind" means it is fully behind another obstruction
else if (new_version) //PVsyst versions 6 and newer: 0 means no shade, 1 means full shade
azaltvals.at(j, i) = (float)wxAtof(lnp[i]) * 100; //convert to percentage
else //PVsyst versions 5 and older: 1 means no shade, 0 means full shade
azaltvals.at(j, i) = (1 - (float)wxAtof(lnp[i])) * 100; //convert from factor to loss
}
}
}
}
else if (j == 10)
{
if (lnp.Count()== 3)
{
if (new_version) //PVsyst versions 6 and newer: 0 means no shade, 1 means full shade
diffuse = (float)wxAtof(lnp[1]) * 100; //convert to percentage
else //PVsyst versions 5 and older: 1 means no shade, 0 means full shade
diffuse = (1 - (float)wxAtof(lnp[1])) * 100; //convert from factor to loss
}
else
{
readok = false;
colok = false;
break;
}
j++;
}
else j++;
buf = tf.GetNextLine();
}
if (j < 11)
{
readok = false;
linesok = -1;
}
else if (j > 11)
{
readok = false;
linesok = 1;
}
if (readdata != true)
{
readok = false;
headingok = false;
}
if (readok)
{
// re-sort from small altitude to large, if necessary
if (azaltvals.at(10, 0) < azaltvals.at(1, 0))
{
azaltvals.resize_preserve(12, 20, 1.0);
for (j = 1; j < 12 / 2; j++)
{
for (i = 0; i < 20; i++) azaltvals.at(11, i) = azaltvals.at(j, i);
for (i = 0; i < 20; i++) azaltvals.at(j, i) = azaltvals.at(11-j, i);
for (i = 0; i < 20; i++) azaltvals.at(11-j, i) = azaltvals.at(11, i);
}
azaltvals.resize_preserve(11, 20, 1.0);
}
dat.clear();
dat.en_azal = true;
dat.azal.copy( azaltvals );
dat.en_diff = true;
dat.diff = diffuse;
return true;
}
else
{
wxString m = "Invalid file format.\n\n";
if (!headingok) m.Append("Invalid heading format.\n");
if (!colok) m.Append("Invalid number of columns.\n");
if (linesok == -1) m.Append("File contains fewer lines than expected.\n");
if (linesok == 1) m.Append("File contains more lines than expected.\n");
wxMessageBox(m);
return false;
}
}
bool ImportSunEyeHourly( ShadingInputData &dat, wxWindow *parent )
{
wxFileDialog fdlg(parent, "Import SunEye Shading File");
if (fdlg.ShowModal() != wxID_OK) return false;
wxTextFile tf;
if ( !tf.Open( fdlg.GetPath() ) )
{
wxMessageBox("Could not open file for read:\n\n" + fdlg.GetPath());
return false;
}
wxString buf;
int i;
bool readdata = false;
bool readok = true;
bool headingok = true;
bool colok = true;
int linesok = 0;
int day = 0;
int start_timestep=0;
int start_hour=0;
int end_timestep=0;
int end_hour=0;
int hour_duration=0; // how many hours (including incomplete hours) in the Suneye file
double beam[8760];
for (i=0;i<8760;i++) beam[i]=0.0;
buf = tf.GetFirstLine();
while( !tf.Eof() )
{
wxArrayString lnp = wxStringTokenize(buf, ",", wxTOKEN_RET_EMPTY_ALL);
if (readdata == false)
{
if (lnp.Count() > 0)
{
if (lnp.Item(0) == "begin data")
{
readdata = true;
int iend = lnp.Count()-1;
int icolon = 0;
icolon = lnp.Item(1).find(":");
if (icolon>0)
{
start_timestep = wxAtoi(lnp.Item(1).substr(icolon+1,2));
start_hour = wxAtoi(lnp.Item(1).substr(0,icolon));
}
icolon = lnp.Item(iend).find(":");
if (icolon>0)
{
end_timestep = wxAtoi(lnp.Item(iend).substr(icolon+1,2));
end_hour = wxAtoi(lnp.Item(iend).substr(0,icolon));
}
// check for valid duration
if ((start_hour==0) || (end_hour==0))
{
readdata=false;
break;
}
hour_duration = end_hour - start_hour + 1;
}
}
}
else
{
// shj update 5/25/11 - read in begin data and to end - no fixed count
// assume that 15 timestep intervals and use start and end time and adjust to hour
// JMF update 10/17/2014- average all values for an hour instead of taking the midpoint of the hour
int index = 1; //keep track of where you are in the row- starts at 1 because of the date column.
for (i=0;i<hour_duration;i++)
{
//compute which hour to enter the shading factor into
int x = day*24+start_hour+i;
if (x >= 8760)
{
readok = false;
break;
}
//how many 15-min entries are in this hour?
int count = 0;
if (i == 0) //first hour
count = (60 - start_timestep) / 15;
else if (i == hour_duration - 1) //last hour
count = end_timestep / 15 + 1;
else //whole hours in between
count = 4;
//loop through the correct number of 15-timestep entries and to calculate an average shading value
double total = 0;
for (int j = 0; j < count; j++)
{
if (lnp.Item(index).IsEmpty()) total += 0;
else total += wxAtof(lnp.Item(index));
index++; //don't forget to increment the index so that you read the next cell
}
//compute average and assign it to the appropriate hour
beam[x] = (1 - (total / count)) * 100; //don't forget to convert it to a loss factor
}
day++;
}
buf = tf.GetNextLine();
}
if (day !=365)
{
readok = false;
if (day - 365 < 0 && day != 0) linesok = -1;
if (day - 365 > 0 && day != 0) linesok = 1;
}
if (readdata == false)
{
readok = false;
headingok = false;
}
if (readok)
{
dat.clear();
dat.en_timestep = true;
dat.timestep.clear();
dat.timestep.resize_fill(8760,1,0);
for (size_t i = 0; i<8760; i++)
dat.timestep.at(i,0) = beam[i];
return true;
}
else
{
wxString m = "Invalid file format.\n\n";
if (!headingok) m.Append("Invalid heading format.\n");
if (!colok) m.Append("Invalid number of columns.\n");
if (linesok == -1) m.Append("File contains fewer lines than expected.\n");
if (linesok == 1) m.Append("File contains more lines than expected.\n");
wxMessageBox(m);
return false;
}
}
bool ImportSunEyeObstructions( ShadingInputData &dat, wxWindow *parent )
{
wxFileDialog fdlg(parent, "Import SunEye Obstruction Elevations File");
if (fdlg.ShowModal() != wxID_OK) return false;
wxString file = fdlg.GetPath();
wxTextFile tf;
if ( !tf.Open( file ) )
{
wxMessageBox("Could not open file for read:\n\n" + file);
return false;
}
wxString buf;
int j = -2;
bool readdata = false;
bool readok = true;
bool headingok = true;
bool colok = true;
int linesok = 0;
double azi[361];
int imageCount = 0;
int columnCount = 0;
int elevationStartCol = -1;
float obstructionStep = 0.0;
matrix_t<float> azaltvals, obstructions;
azaltvals.resize_fill(91,362, 0.0);
azaltvals.at(0,0) = 0.;
buf = tf.GetFirstLine();
while( !tf.Eof() )
{
wxArrayString lnp = wxStringTokenize( buf, "," );
if (readdata == false)
{
if (lnp.Count() > 0 && j == -2)
{
if (lnp.Item(0) == "begin data")
{
readdata = true;
j++;
}
}
}
else if (readdata == true && j == -1)
{ // get image count here
columnCount = lnp.Count();
for (int i = 0; i < columnCount; i++)
{
int ndx = lnp[i].Lower().Find("elevation");
if (ndx != wxNOT_FOUND && (ndx < 2)) // Not Average or Maximum
{
imageCount++;
// set elevation start column
if (elevationStartCol < 0) elevationStartCol = i;
}
}
if (imageCount < 1 || elevationStartCol < 0)
{
wxMessageBox("Error: No 'Elevations' data columns found.");
return false;
}
j++;
}
else
{
if( j == 0)
{
obstructions.resize_fill( 362, imageCount, 0.0);
obstructionStep = 100.0 / imageCount;
}
if (j <= 360)
{
if ((int)lnp.Count() < elevationStartCol + imageCount)
{
wxMessageBox(wxString::Format("Error: Not enough data found at data row=%d.", j ));
return false;
}
else
{
azi[j] = wxAtof(lnp[0]); //first column contains compass heading azimuth values (0=north, 90=east)
for (int ii=0; ii<imageCount && (ii+elevationStartCol) < (int)lnp.Count(); ii++)
obstructions.at(j,ii) = wxAtof(lnp[ii+elevationStartCol]);
}
j++;
}
else j++;
}
buf = tf.GetNextLine();
}
if (j < 361)
{
readok = false;
linesok = -1;
}
else if (j > 361)
{
readok = false;
linesok = 1;
}
if (readdata != true)
{
readok = false;
headingok = false;
}
if (readok)
{
//copy azimuth/compass values into the first row
for (int i=1;i<362;i++)
azaltvals.at(0,i) = azi[i-1];
//elevation always goes from 1-90 degrees
for (int i=1;i<91;i++)
azaltvals.at(i,0) = i;
//loop through all azimuth values
for (int j=0;j<362;j++)
{
for(int k=0; k<imageCount;k++){ // Sev 150624: loop over images
if (obstructions.at(j,k)<0 || obstructions.at(j,k)>90) //changed from && to || 6/18/15 jmf
{
wxMessageBox("Error: Elevations Must be less than 90 degrees and greater than 0 degrees");
return false;
}
//changed jmf 6/18/15- values UP TO the altitude value should be fully shaded.
for (int i = 1; i <= obstructions.at(j,k); i++)
azaltvals.at(i, j + 1) += obstructionStep; // Sev 150624: obstruction amount now increase incrementally instead of going straight from 0 to 100
}
}
dat.clear();
dat.en_azal = true;
dat.azal = azaltvals;
return true;
}
else
{
wxString m = "Invalid file format.\n\n";
if (!headingok) m.Append("Invalid heading format.\n");
if (!colok) m.Append("Invalid number of columns.\n");
if (linesok == -1) m.Append("File contains fewer lines than expected.\n");
if (linesok == 1) m.Append("File contains more lines than expected.\n");
wxMessageBox(m);
return false;
}
}
bool ImportSolPathMonthByHour( ShadingInputData &dat, wxWindow *parent )
{
wxFileDialog fdlg(parent, "Import Solar Pathfinder Month By Hour Shading File");
if (fdlg.ShowModal() != wxID_OK) return false;
wxString file = fdlg.GetPath();
wxTextFile tf;
if ( !tf.Open( file ) )
{
wxMessageBox("Could not open file for read:\n\n" + file);
return false;
}
// read in month by hour grid from first image in shading file - Oliver Hellwig - Solar Pathfinder programmer - every half hour - read 2 value and average for now
// 12:00 AM 12:30 AM 1:00 AM 1:30 AM 2:00 AM 2:30 AM 3:00 AM 3:30 AM 4:00 AM 4:30 AM 5:00 AM 5:30 AM 6:00 AM 6:30 AM 7:00 AM 7:30 AM 8:00 AM 8:30 AM 9:00 AM 9:30 AM 10:00 AM 10:30 AM 11:00 AM 11:30 AM 12:00 PM 12:30 PM 1:00 PM 1:30 PM 2:00 PM 2:30 PM 3:00 PM 3:30 PM 4:00 PM 4:30 PM 5:00 PM 5:30 PM 6:00 PM 6:30 PM 7:00 PM 7:30 PM 8:00 PM 8:30 PM 9:00 PM 9:30 PM 10:00 PM 10:30 PM 11:00 PM 11:30 PM
// 12,24,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1
// double array 12rowsx24columns Solar pathfinder percentages to fractions
wxString buf;
int i, imageCount = 0;
bool readdata = false;
bool readok = true;
int month=0; //
double beam[290];
for (i=0;i<290;i++) beam[i]=0.0;
beam[0]=12;
beam[1]=24;
buf = tf.GetFirstLine();
// data at half hour is recorded for hour in 8760 shading file - e.g. Jan-1 5:30 data recoded at hour 5
while( !tf.Eof() )
{
wxArrayString lnp = wxStringTokenize(buf, ",", wxTOKEN_RET_EMPTY_ALL);
if (readdata == false)
{
if (lnp.Count() > 0)
{
if ( ((std::string)(lnp.Item(0))).find("Image Layout Number ")==0 )
{
imageCount++;
month = 0;
buf = tf.GetNextLine();
readdata = true;
}
}
}
else
{
if (month==11)
{
readdata = false;
}
for (i=0;i<24;i++)
{
int ndex=i+month*24+2; // skip 12x24 array size
if (ndex > 289)
{
readok=false;
break;
}
// average hour and half hour values starting at midnight (skip row label)
if (imageCount==1){
beam[ndex] = 100- (wxAtof(lnp.Item(2*i+1))+wxAtof(lnp.Item(2*i+1+1)))/2.0; //convert from a factor to a loss
} else {
beam[ndex] += 100- (wxAtof(lnp.Item(2*i+1))+wxAtof(lnp.Item(2*i+1+1)))/2.0; //convert from a factor to a loss
}
}
month++;
}
buf = tf.GetNextLine();
if (tf.Eof() ) readdata = true;
}
if (readdata == false || imageCount == 0)
{
readok = false;
}
if (readok)
{
dat.clear();
dat.en_mxh = true;
dat.mxh.resize_fill(12,24, 0.0);
for (int r=0;r<12;r++)
for (int c=0;c<24;c++)
dat.mxh.at(r,c) = beam[ 24*r+c+2 ] / imageCount;
return true;
}
else
{
wxString m = "Invalid file format.\n\n";
wxMessageBox(m);
return false;
}
}
DEFINE_EVENT_TYPE(wxEVT_wxShadingFactorsCtrl_CHANGE)
//enum { ISFC_CHOICECOL = wxID_HIGHEST + 857, ISFC_CHOICEMINUTE, ISFC_CHOICESTRING, ISFC_GRID, ISFC_COPY, ISFC_PASTE, ISFC_IMPORT, ISFC_EXPORT };
enum { ISFC_CHOICECOL = wxID_HIGHEST + 857, ISFC_CHOICEMINUTE, ISFC_CHKDB, ISFC_GRID, ISFC_COPY, ISFC_PASTE, ISFC_IMPORT, ISFC_EXPORT };
BEGIN_EVENT_TABLE(wxShadingFactorsCtrl, wxPanel)
EVT_GRID_CMD_CELL_CHANGED(ISFC_GRID, wxShadingFactorsCtrl::OnCellChange)
EVT_CHOICE(ISFC_CHOICECOL, wxShadingFactorsCtrl::OnChoiceCol)
EVT_CHOICE(ISFC_CHOICEMINUTE, wxShadingFactorsCtrl::OnChoiceMinute)
EVT_BUTTON(ISFC_COPY, wxShadingFactorsCtrl::OnCommand)
EVT_CHECKBOX(ISFC_CHKDB, wxShadingFactorsCtrl::OnCommand)
EVT_BUTTON(ISFC_PASTE, wxShadingFactorsCtrl::OnCommand)
EVT_BUTTON(ISFC_EXPORT, wxShadingFactorsCtrl::OnCommand)
EVT_BUTTON(ISFC_IMPORT, wxShadingFactorsCtrl::OnCommand)
END_EVENT_TABLE()
wxShadingFactorsCtrl::wxShadingFactorsCtrl(wxWindow *parent, int id,
const wxPoint &pos,
const wxSize &sz,
bool show_db_options,
bool sidebuttons)
: wxPanel(parent, id, pos, sz)
{
m_default_val = 0;
m_num_minutes = 60;
m_grid_data = NULL;
m_show_db_options = show_db_options;
m_col_arystrvals.Clear();
m_minute_arystrvals.Clear();
//m_string_arystrvals.Clear();
m_grid = new wxExtGridCtrl(this, ISFC_GRID);
m_grid->CreateGrid(8760, 8);
m_grid->EnableCopyPaste(true);
m_grid->EnablePasteEvent(true);
m_grid->DisableDragCell();
m_grid->DisableDragRowSize();
m_grid->DisableDragColMove();
m_grid->DisableDragGridSize();
m_grid->SetRowLabelAlignment(wxALIGN_LEFT, wxALIGN_CENTER);
// m_string_arystrvals.push_back("Database lookup");
// m_string_arystrvals.push_back("Average of strings");
// m_string_arystrvals.push_back("Maximum of strings");
// m_string_arystrvals.push_back("Minimum of strings");
// m_choice_string_option = new wxChoice(this, ISFC_CHOICESTRING, wxDefaultPosition, wxDefaultSize, m_string_arystrvals);
// m_choice_string_option->SetBackgroundColour(*wxWHITE);
m_caption_col = new wxStaticText(this, wxID_ANY, "");
m_caption_col->SetFont(*wxNORMAL_FONT);
m_caption_shading_db = new wxStaticText(this, wxID_ANY, "");
m_caption_shading_db->SetFont(*wxNORMAL_FONT);
m_chk_shading_db = new wxCheckBox(this, ISFC_CHKDB, "");
// m_caption_string = new wxStaticText(this, wxID_ANY, "");
// m_caption_string->SetFont(*wxNORMAL_FONT);
m_col_arystrvals.push_back("1");
m_col_arystrvals.push_back("2");
m_col_arystrvals.push_back("3");
m_col_arystrvals.push_back("4");
m_col_arystrvals.push_back("5");
m_col_arystrvals.push_back("6");
m_col_arystrvals.push_back("7");
m_col_arystrvals.push_back("8");
m_choice_col = new wxChoice(this, ISFC_CHOICECOL, wxDefaultPosition, wxDefaultSize, m_col_arystrvals);
m_choice_col->SetBackgroundColour(*wxWHITE);
m_caption_timestep = new wxStaticText(this, wxID_ANY, "");
m_caption_timestep->SetFont(*wxNORMAL_FONT);
m_minute_arystrvals.push_back("1");
m_minute_arystrvals.push_back("3");
m_minute_arystrvals.push_back("5");
m_minute_arystrvals.push_back("10");
m_minute_arystrvals.push_back("15");
m_minute_arystrvals.push_back("30");
m_minute_arystrvals.push_back("60");
m_choice_timestep = new wxChoice(this, ISFC_CHOICEMINUTE, wxDefaultPosition, wxDefaultSize, m_minute_arystrvals);
m_choice_timestep->SetBackgroundColour(*wxWHITE);
m_btn_import = new wxButton(this, ISFC_IMPORT, "Import...");
m_btn_export = new wxButton(this, ISFC_EXPORT, "Export...");
m_btn_copy = new wxButton(this, ISFC_COPY, "Copy");
m_btn_paste = new wxButton(this, ISFC_PASTE, "Paste");
if (!show_db_options)
{
m_caption_col->Show(false);
m_choice_col->Show(false);
// m_caption_string->Show(false);
// m_choice_string_option->Show(false);
}
if (sidebuttons)
{
// for side buttons layout
wxBoxSizer *v_tb_sizer = new wxBoxSizer(wxVERTICAL);
v_tb_sizer->Add(m_caption_timestep, 0, wxALL | wxEXPAND, 3);
v_tb_sizer->Add(m_choice_timestep, 0, wxALL | wxEXPAND, 3);
v_tb_sizer->AddSpacer(5);
v_tb_sizer->Add(m_caption_shading_db, 0, wxALL | wxEXPAND, 3);
v_tb_sizer->Add(m_chk_shading_db, 0, wxALL | wxEXPAND, 3);
if (show_db_options)
{
v_tb_sizer->AddSpacer(5);
v_tb_sizer->Add(m_caption_col, 0, wxALL | wxEXPAND, 3);
v_tb_sizer->Add(m_choice_col, 0, wxALL | wxEXPAND, 3);
// v_tb_sizer->AddSpacer(5);
// v_tb_sizer->Add(m_caption_string, 0, wxALL | wxEXPAND, 3);
// v_tb_sizer->Add(m_choice_string_option, 0, wxALL | wxEXPAND, 3);
}
v_tb_sizer->AddSpacer(5);
v_tb_sizer->Add(m_btn_copy, 0, wxALL | wxEXPAND, 3);
v_tb_sizer->Add(m_btn_paste, 0, wxALL | wxEXPAND, 3);
v_tb_sizer->Add(m_btn_import, 0, wxALL | wxEXPAND, 3);
v_tb_sizer->Add(m_btn_export, 0, wxALL | wxEXPAND, 3);
v_tb_sizer->AddStretchSpacer();
wxBoxSizer *h_sizer = new wxBoxSizer(wxHORIZONTAL);
h_sizer->Add(v_tb_sizer, 0, wxALL | wxEXPAND, 1);
h_sizer->Add(m_grid, 1, wxALL | wxEXPAND, 1);
SetSizer(h_sizer);
}
else
{
// for top buttons layout (default)
wxBoxSizer *h_tb_sizer = new wxBoxSizer(wxHORIZONTAL);
h_tb_sizer->Add(m_caption_timestep, 0, wxALL | wxALIGN_CENTER_VERTICAL, 3);
h_tb_sizer->Add(m_choice_timestep, 0, wxALL | wxALIGN_CENTER_VERTICAL, 3);
h_tb_sizer->AddSpacer(5);
h_tb_sizer->Add(m_caption_shading_db, 0, wxALL | wxALIGN_CENTER_VERTICAL, 3);
h_tb_sizer->Add(m_chk_shading_db, 0, wxALL | wxALIGN_CENTER_VERTICAL, 3);
if (show_db_options)
{
h_tb_sizer->AddSpacer(5);
h_tb_sizer->Add(m_caption_col, 0, wxALL | wxALIGN_CENTER_VERTICAL, 3);
h_tb_sizer->Add(m_choice_col, 0, wxALL | wxALIGN_CENTER_VERTICAL, 3);
// h_tb_sizer->AddSpacer(5);
// h_tb_sizer->Add(m_caption_string, 0, wxALL | wxALIGN_CENTER_VERTICAL, 3);
// h_tb_sizer->Add(m_choice_string_option, 0, wxALL | wxALIGN_CENTER_VERTICAL, 3);
}
/*
h_tb_sizer->AddSpacer(5);
h_tb_sizer->Add(m_btn_copy, 0, wxALL, 3);
h_tb_sizer->Add(m_btn_paste, 0, wxALL, 3);
h_tb_sizer->Add(m_btn_import, 0, wxALL, 3);
h_tb_sizer->Add(m_btn_export, 0, wxALL, 3);
*/
h_tb_sizer->AddStretchSpacer();
wxBoxSizer *v_sizer = new wxBoxSizer(wxVERTICAL);
v_sizer->Add(h_tb_sizer, 0, wxALL | wxEXPAND, 1);
v_sizer->Add(m_grid, 1, wxALL | wxEXPAND, 1);
// bottom buttons per Paul 4/4/16
wxBoxSizer *h_bb_sizer = new wxBoxSizer(wxHORIZONTAL);
h_bb_sizer->Add(m_btn_import, 0, wxALL, 3);
h_bb_sizer->Add(m_btn_export, 0, wxALL, 3);
h_bb_sizer->Add(new wxStaticLine(this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxVERTICAL), 0, wxALL | wxEXPAND, 1);
h_bb_sizer->Add(m_btn_copy, 0, wxALL, 3);
h_bb_sizer->Add(m_btn_paste, 0, wxALL, 3);
h_bb_sizer->AddStretchSpacer();
v_sizer->Add(h_bb_sizer, 0, wxALL | wxEXPAND, 1);
SetSizer(v_sizer, false);
}
}
void wxShadingFactorsCtrl::UpdateNumberColumns(size_t &new_cols)
{
// resize and preserve existing data and fill new data with default.
m_data.resize_preserve(m_data.nrows(), new_cols, m_default_val);
SetData(m_data);
}
void wxShadingFactorsCtrl::AverageCols()
{
size_t ncols = m_data.ncols();
for (size_t nr = 0; nr < m_data.nrows(); nr++)
{
float avg = 0;
for (size_t nc = 0; nc < ncols; nc++)
avg += m_data.at(nr, nc);
avg /= ncols;
m_data.at(nr, 0) = avg;
}
m_data.resize_preserve(m_data.nrows(), 1, m_default_val);
SetData(m_data);
m_choice_col->SetSelection(0);
}
void wxShadingFactorsCtrl::UpdateNumberRows(size_t &new_rows)
{
// resize and preserve existing data and fill new data with default.
m_data.resize_preserve(new_rows, m_data.ncols(), m_default_val);
SetData(m_data);
}
void wxShadingFactorsCtrl::UpdateNumberMinutes(size_t &new_timesteps)
{
// resize and preserve existing data and fill new data with default.
// multiple of 8760 timesteps to number of timesteps
if ((new_timesteps > 0) && (new_timesteps <= 60))
{
size_t new_rows = 60 / new_timesteps * 8760;
m_data.resize_preserve(new_rows, m_data.ncols(), m_default_val);
SetData(m_data);
}
}
void wxShadingFactorsCtrl::OnCommand(wxCommandEvent &evt)
{
switch (evt.GetId())
{
case ISFC_CHKDB:
{
bool bol_db = m_chk_shading_db->GetValue();
m_caption_col->Show(bol_db);
m_choice_col->Show(bol_db);
if (!bol_db)
AverageCols();
}
break;
case ISFC_COPY:
m_grid->Copy(true);
break;
case ISFC_PASTE:
{
// resize rows per data pasted
if (wxTheClipboard->Open())
{
wxString data;
wxTextDataObject textobj;
if (wxTheClipboard->GetData(textobj))
{
data = textobj.GetText();
wxTheClipboard->Close();
}
if (data.IsEmpty()) return;
#ifdef __WXMAC__
wxArrayString lines = wxStringTokenize(data, "\r", ::wxTOKEN_RET_EMPTY_ALL);
#else
wxArrayString lines = wxStringTokenize(data, "\n", ::wxTOKEN_RET_EMPTY_ALL);
#endif
int ncols = m_grid->GetNumberCols();
if (m_show_db_options && (lines.Count() > 0))
{
wxArrayString col_vals1 = wxStringTokenize(lines[0], "\t", ::wxTOKEN_RET_EMPTY_ALL);
ncols = col_vals1.Count();
if (ncols > (int)m_col_arystrvals.Count())
ncols = m_col_arystrvals.Count();
int ndx = m_col_arystrvals.Index(wxString::Format("%d", ncols));
if (ndx >= 0)
m_choice_col->SetSelection(ndx);
}
int nrows = lines.Count() - 1;
if ((nrows == 0) || (nrows % 8760 != 0)) return;
int minutes = 60 / (nrows / 8760);
if (!IsValidMinutes(minutes)) return;
m_grid->ResizeGrid(nrows, ncols);
m_data.resize_preserve(nrows, ncols, 0.0);
m_grid->Paste( wxExtGridCtrl::PASTE_ALL );
for (size_t r = 0; r < m_data.nrows(); r++)
for (size_t c = 0; c < m_data.ncols(); c++)
m_data.at(r, c) = atof(m_grid->GetCellValue(r, c).c_str());
SetData(m_data);
int ndx = m_minute_arystrvals.Index(wxString::Format("%d", minutes));
if (ndx >= 0)
m_choice_timestep->SetSelection(ndx);
m_chk_shading_db->SetValue(true);
m_caption_col->Show(true);
m_choice_col->Show(true);
}
}
break;
case ISFC_IMPORT:
{
wxFileDialog dlg(this, "Select data matrix file to import");
if (dlg.ShowModal() == wxID_OK)
{
if (!Import(dlg.GetPath()))
wxMessageBox("Error import data file:\n\n" + dlg.GetPath());
else
{
m_chk_shading_db->SetValue(true);
m_caption_col->Show(true);
m_choice_col->Show(true);
}
}
}
break;
case ISFC_EXPORT:
{
wxFileDialog dlg(this, "Select file for data export", wxEmptyString, wxEmptyString, wxFileSelectorDefaultWildcardStr, wxFD_SAVE | wxFD_OVERWRITE_PROMPT);
if (dlg.ShowModal() == wxID_OK)
if (!Export(dlg.GetPath()))
wxMessageBox("Error exporting data to file:\n\n" + dlg.GetPath());
}
break;
}
}
bool wxShadingFactorsCtrl::Export(const wxString &file)
{
wxCSVData csv;
for (size_t r = 0; r<m_data.nrows(); r++)
for (size_t c = 0; c<m_data.ncols(); c++)
csv(r, c) = wxString::Format("%g", m_data(r, c));
return csv.WriteFile(file);
}
bool wxShadingFactorsCtrl::IsValidMinutes(int &minutes)
{
return (m_minute_arystrvals.Index(wxString::Format("%d", minutes)) != wxNOT_FOUND);
}
bool wxShadingFactorsCtrl::Import(const wxString &file)
{
wxCSVData csv;
if (!csv.ReadFile(file)) return false;
int nrows = csv.NumRows();
if ((nrows == 0) || (nrows % 8760 != 0)) return false;
int minutes = 60 / (nrows / 8760);
if (!IsValidMinutes(minutes)) return false;
int ncols = m_grid->GetNumberCols();
if (m_show_db_options && (csv.NumCols() > 0))
{
ncols = csv.NumCols();
if (ncols > (int)m_col_arystrvals.Count())
ncols = m_col_arystrvals.Count();
int ndx = m_col_arystrvals.Index(wxString::Format("%d", ncols));
if (ndx >= 0)
m_choice_col->SetSelection(ndx);
}
m_grid->ResizeGrid(nrows, ncols);
m_data.resize_preserve(nrows, ncols, 0.0f);
for (size_t r = 0; r<m_data.nrows(); r++)
for (size_t c = 0; c<m_data.ncols(); c++)
m_data.at(r, c) = (float)wxAtof(csv(r, c));
SetData(m_data);
int ndx = m_minute_arystrvals.Index(wxString::Format("%d", minutes));
if (ndx >= 0)
m_choice_timestep->SetSelection(ndx);
return true;
}
void wxShadingFactorsCtrl::OnChoiceCol(wxCommandEvent &)
{
if ((m_choice_col->GetSelection() != wxNOT_FOUND) && (wxAtoi(m_choice_col->GetString(m_choice_col->GetSelection())) != (int)m_data.ncols()))
{
size_t new_cols = wxAtoi(m_choice_col->GetString(m_choice_col->GetSelection()));
UpdateNumberColumns(new_cols);
}
}
void wxShadingFactorsCtrl::OnChoiceMinute(wxCommandEvent &)
{
if ((m_choice_timestep->GetSelection() != wxNOT_FOUND) && (wxAtoi(m_choice_timestep->GetString(m_choice_timestep->GetSelection())) != (int)m_num_minutes))
{
m_num_minutes = wxAtoi(m_choice_timestep->GetString(m_choice_timestep->GetSelection()));
UpdateNumberMinutes(m_num_minutes);
}
}
void wxShadingFactorsCtrl::SetData(const matrix_t<double> &mat)
{
m_data = mat;
if (m_grid_data) m_grid_data->SetMatrix(NULL);
m_grid->SetTable(NULL);
m_grid_data = new wxShadingFactorsTable(&m_data,m_default_val);
m_grid_data->SetAttrProvider(new wxExtGridCellAttrProvider);
m_grid->SetTable(m_grid_data, true);
m_grid->Layout();
m_grid->Refresh();
}
void wxShadingFactorsCtrl::GetData(matrix_t<double> &mat)
{
mat = m_data;
}
void wxShadingFactorsCtrl::OnCellChange(wxGridEvent &evt)
{
int irow = evt.GetRow();
int icol = evt.GetCol();
if (irow == -1 && icol == -1) // paste event generated from base class
{
for (int ir = 0; ir < m_grid->GetNumberRows(); ir++)
for (int ic = 0; ic < m_grid->GetNumberCols(); ic++)
{
float val = (float)wxAtof(m_grid->GetCellValue(ir, ic).c_str());
m_data.at(ir, ic) = val;
m_grid->SetCellValue(ir, ic, wxString::Format("%g", val));
}
}
else
{
float val = (float)wxAtof(m_grid->GetCellValue(irow, icol).c_str());
if (irow < (int)m_data.nrows() && icol < (int)m_data.ncols()
&& irow >= 0 && icol >= 0)
m_data.at(irow, icol) = val;
m_grid->SetCellValue(irow, icol, wxString::Format("%g", val));
}
wxCommandEvent dmcevt(wxEVT_wxShadingFactorsCtrl_CHANGE, this->GetId());
dmcevt.SetEventObject(this);
GetEventHandler()->ProcessEvent(dmcevt);
}
void wxShadingFactorsCtrl::SetColCaption(const wxString &cap)
{
m_caption_col->SetLabel(cap);
this->Layout();
}
wxString wxShadingFactorsCtrl::GetColCaption()
{
return m_caption_col->GetLabel();
}
/*
void wxShadingFactorsCtrl::SetStringCaption(const wxString &cap)
{
m_caption_string->SetLabel(cap);
this->Layout();
}
wxString wxShadingFactorsCtrl::GetStringCaption()
{
return m_caption_string->GetLabel();
}
*/
void wxShadingFactorsCtrl::SetMinuteCaption(const wxString &cap)
{
m_caption_timestep->SetLabel(cap);
this->Layout();
}
wxString wxShadingFactorsCtrl::GetMinuteCaption()
{
return m_caption_timestep->GetLabel();
}
void wxShadingFactorsCtrl::SetDBCaption(const wxString &cap)
{
m_caption_shading_db->SetLabel(cap);
this->Layout();
}
wxString wxShadingFactorsCtrl::GetDBCaption()
{
return m_caption_shading_db->GetLabel();
}
void wxShadingFactorsCtrl::SetNumMinutes(size_t &minutes)
{
int ndx = m_minute_arystrvals.Index(wxString::Format("%d", (int)minutes));
if (ndx >= 0)
m_choice_timestep->SetSelection(ndx);
UpdateNumberMinutes(minutes);
}
void wxShadingFactorsCtrl::SetNumCols(size_t &cols)
{
int ndx = m_col_arystrvals.Index(wxString::Format("%d", (int)cols));
if (ndx >= 0)
m_choice_col->SetSelection(ndx);
UpdateNumberColumns(cols);
}
void wxShadingFactorsCtrl::SetDBOption(int &db_option)
{
// keep compatibility with shading database = 0 choice
bool bol_shade_db = (db_option == 0);
m_chk_shading_db->SetValue(bol_shade_db);
m_caption_col->Show(bol_shade_db);
m_choice_col->Show(bol_shade_db);
}
int wxShadingFactorsCtrl::GetDBOption()
{
// keep compatibility with shading database = 0 choice
if (m_chk_shading_db->GetValue())
return 0;
else
return 1; // average
}
/*
void wxShadingFactorsCtrl::SetStringOption(int &string_option)
{
if (string_option >= 0 && string_option < (int)m_string_arystrvals.Count())
m_choice_string_option->SetSelection(string_option);
else
m_choice_string_option->SetSelection(0); // default
}
int wxShadingFactorsCtrl::GetStringOption()
{
if (m_choice_string_option->IsShown())
return m_choice_string_option->GetSelection();
else
return -1; // no string options
}
*/
wxShadingFactorsTable::wxShadingFactorsTable(matrix_t<double> *da, float _def_val, const wxString &_label)
{
label = _label;
d_mat = da;
def_val = _def_val;
}
void wxShadingFactorsTable::SetMatrix(matrix_t<double> *da)
{
d_mat = da;
}
int wxShadingFactorsTable::GetNumberRows()
{
if (!d_mat) return 0;
return (int)d_mat->nrows();
}
int wxShadingFactorsTable::GetNumberCols()
{
if (!d_mat) return 0;
return (int)d_mat->ncols();
}
bool wxShadingFactorsTable::IsEmptyCell(int , int )
{
return false;
}
wxString wxShadingFactorsTable::GetValue(int row, int col)
{
if (d_mat && row >= 0 && row < (int)d_mat->nrows() && col >= 0 && col < (int)d_mat->ncols())
return wxString::Format("%g", d_mat->at(row, col));
else
return "-0.0";
}
void wxShadingFactorsTable::SetValue(int row, int col, const wxString& value)
{
if (d_mat && row >= 0 && row < (int)d_mat->nrows() && col >= 0 && col < (int)d_mat->ncols())
d_mat->at(row, col) = wxAtof(value);
}
wxString wxShadingFactorsTable::GetRowLabelValue(int row)
{
if (d_mat )
{
int nmult = d_mat->nrows() / 8760;
if (nmult != 0)
{
double step = 1.0 / ((double)nmult);
double tm = step*(row + 1);
double frac = tm - ((double)(int)tm);
if (frac == 0.0)
return wxString::Format("%lg", tm);
else
return wxString::Format(" .%lg", frac * 60);
}
}
return wxString::Format("%d", row + 1);
}
wxString wxShadingFactorsTable::GetColLabelValue(int col)
{
wxString col_label = label.IsEmpty() ? "Value" : label;
if (d_mat->ncols() > 1)
col_label = wxString::Format("String %d", col + 1);
return col_label;
}
wxString wxShadingFactorsTable::GetTypeName(int , int )
{
return wxGRID_VALUE_STRING;
}
bool wxShadingFactorsTable::CanGetValueAs(int , int , const wxString& typeName)
{
return typeName == wxGRID_VALUE_STRING;
}
bool wxShadingFactorsTable::CanSetValueAs(int , int , const wxString& typeName)
{
return typeName == wxGRID_VALUE_STRING;
}
bool wxShadingFactorsTable::AppendRows(size_t nrows)
{
if (d_mat && nrows > 0)
{
size_t new_rows = d_mat->nrows() + nrows;
d_mat->resize_preserve(new_rows, d_mat->ncols(), def_val);
if (GetView())
{
wxGridTableMessage msg(this,
wxGRIDTABLE_NOTIFY_ROWS_APPENDED,
nrows);
GetView()->ProcessTableMessage(msg);
}
}
return true;
}
bool wxShadingFactorsTable::InsertRows(size_t pos, size_t nrows)
{
if (!d_mat) return true;
if (pos > d_mat->nrows()) pos = d_mat->nrows();
size_t new_rows = d_mat->nrows() + nrows;
matrix_t<double> old(*d_mat);
d_mat->resize_fill(new_rows, d_mat->ncols(), def_val);
for (size_t r = 0; r < pos && r < old.nrows(); r++)
for (size_t c = 0; c < old.ncols(); c++)
d_mat->at(r, c) = old(r, c);
// r-nrows>=0 since pos>=0
for (size_t r = pos + nrows; r < new_rows && r - nrows < old.nrows(); r++)
for (size_t c = 0; c < old.ncols(); c++)
d_mat->at(r, c) = old(r - nrows, c);
if (GetView())
{
wxGridTableMessage msg(this,
wxGRIDTABLE_NOTIFY_ROWS_INSERTED,
pos,
nrows);
GetView()->ProcessTableMessage(msg);
}
return true;
}
bool wxShadingFactorsTable::DeleteRows(size_t pos, size_t nrows)
{
if (!d_mat) return true;
if (nrows > d_mat->nrows() - pos)
nrows = d_mat->nrows() - pos;
size_t new_rows = d_mat->nrows() - nrows;
matrix_t<double> old(*d_mat);
d_mat->resize_preserve(new_rows, d_mat->ncols(), def_val);
for (size_t r = pos; r < new_rows && r + nrows < old.nrows(); r++)
for (size_t c = 0; c < old.ncols(); c++)
d_mat->at(r, c) = old(r + nrows, c);
if (GetView())
{
wxGridTableMessage msg(this,
wxGRIDTABLE_NOTIFY_ROWS_DELETED,
pos,
nrows);
GetView()->ProcessTableMessage(msg);
}
return true;
}
bool wxShadingFactorsTable::AppendCols(size_t ncols)
{
if (d_mat && ncols > 0)
{
size_t new_cols = d_mat->ncols() + ncols;
d_mat->resize_preserve(d_mat->nrows(), new_cols, def_val);
if (GetView())
{
wxGridTableMessage msg(this,
wxGRIDTABLE_NOTIFY_COLS_APPENDED,
ncols);
GetView()->ProcessTableMessage(msg);
}
}
return true;
}
bool wxShadingFactorsTable::InsertCols(size_t pos, size_t ncols)
{
if (!d_mat) return true;
if (pos > d_mat->ncols()) pos = d_mat->ncols();
size_t new_cols = d_mat->ncols() + ncols;
matrix_t<double> old(*d_mat);
d_mat->resize_fill(d_mat->nrows(), new_cols, def_val);
for (size_t r = 0; r < old.nrows(); r++)
for (size_t c = 0; c < pos && c < old.ncols(); c++)
d_mat->at(r, c) = old(r, c);
// r-ncols>=0 since pos>=0
for (size_t r = 0; r < old.nrows(); r++)
for (size_t c = pos + ncols; c < new_cols && r - ncols < old.ncols(); c++)
d_mat->at(r, c) = old(r, c - ncols);
if (GetView())
{
wxGridTableMessage msg(this,
wxGRIDTABLE_NOTIFY_COLS_INSERTED,
pos,
ncols);
GetView()->ProcessTableMessage(msg);
}
return true;
}
bool wxShadingFactorsTable::DeleteCols(size_t pos, size_t ncols)
{
if (!d_mat) return true;
if (ncols > d_mat->ncols() - pos)
ncols = d_mat->ncols() - pos;
size_t new_cols = d_mat->ncols() - ncols;
matrix_t<double> old(*d_mat);
d_mat->resize_preserve(d_mat->nrows(), new_cols, def_val);
for (size_t r = pos; r < old.nrows(); r++)
for (size_t c = pos; c < new_cols && c + ncols < old.nrows(); c++)
d_mat->at(r, c) = old(r, c + ncols);
if (GetView())
{
wxGridTableMessage msg(this,
wxGRIDTABLE_NOTIFY_COLS_DELETED,
pos,
ncols);
GetView()->ProcessTableMessage(msg);
}
return true;
}
| 29.258496 | 617 | 0.675678 | [
"vector",
"model",
"3d"
] |
383ee236dd703c18419f5f3b90813c1f57ad1b34 | 960 | cpp | C++ | HackerRank/Algorithms/Easy/E0064.cpp | Mohammed-Shoaib/HackerRank-Problems | ccfb9fc2f0d8dff454439d75ce519cf83bad7c3b | [
"MIT"
] | 54 | 2019-05-13T12:13:09.000Z | 2022-02-27T02:59:00.000Z | HackerRank/Algorithms/Easy/E0064.cpp | Mohammed-Shoaib/HackerRank-Problems | ccfb9fc2f0d8dff454439d75ce519cf83bad7c3b | [
"MIT"
] | 2 | 2020-10-02T07:16:43.000Z | 2020-10-19T04:36:19.000Z | HackerRank/Algorithms/Easy/E0064.cpp | Mohammed-Shoaib/HackerRank-Problems | ccfb9fc2f0d8dff454439d75ce519cf83bad7c3b | [
"MIT"
] | 20 | 2020-05-26T09:48:13.000Z | 2022-03-18T15:18:27.000Z | /*
Problem Statement: https://www.hackerrank.com/challenges/find-the-median/problem
*/
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int partition(vector<int> &arr, int low, int high){
int pivot = arr[high];
int i = low-1;
for(int j=low ; j<high ; j++)
if(arr[j] < pivot){
i++;
iter_swap(&arr[i], &arr[j]);
}
i++;
iter_swap(&arr[i], &arr[high]);
return i;
}
int quickSelect(vector<int> &arr, int left, int right, int k){
if(left == right)
return arr[left];
int split = partition(arr, left, right);
if(split == k)
return arr[split];
else if(k < split)
return quickSelect(arr, left, split-1, k);
else
return quickSelect(arr, split+1, right, k);
}
int findMedian(vector<int> arr) {
return quickSelect(arr, 0, arr.size()-1, arr.size()/2);
}
int main()
{
int n, num;
vector<int> arr;
cin>>n;
for(int i=0 ; i<n ; i++){
cin>>num;
arr.push_back(num);
}
cout<<findMedian(arr);
return 0;
} | 18.823529 | 80 | 0.633333 | [
"vector"
] |
384442658cb3d9dde0f91452da0f66b97aa8cd04 | 9,804 | cc | C++ | projects/MatlabTranslation/src/typeInference/MatlabTypeInference.cc | edmcman/rose | 93075545a3810529149fcca189e0181f31017e93 | [
"BSD-3-Clause"
] | 1 | 2019-07-21T17:54:22.000Z | 2019-07-21T17:54:22.000Z | projects/MatlabTranslation/src/typeInference/MatlabTypeInference.cc | WildeGeist/rose | 17db6454e8baba0014e30a8ec23df1a11ac55a0c | [
"BSD-3-Clause"
] | null | null | null | projects/MatlabTranslation/src/typeInference/MatlabTypeInference.cc | WildeGeist/rose | 17db6454e8baba0014e30a8ec23df1a11ac55a0c | [
"BSD-3-Clause"
] | 1 | 2021-02-10T00:25:51.000Z | 2021-02-10T00:25:51.000Z |
#include "MatlabTypeInference.h"
#include "rose.h"
#include "sageGeneric.h"
#include "MatlabParser.h"
#include "FunctionAnalyzer.h"
#include "VariableDeclarationBuilder.h"
#include "BottomUpTypeAnalysis.h"
#include "MatlabVariables.h"
#include "FastNumericsRoseSupport.h"
#include "utility/utils.h"
namespace si = SageInterface;
namespace sb = SageBuilder;
namespace ru = RoseUtils;
static
MatlabAnalysis::NameToDeclarationMap
collectNameToDeclarationPair(const Rose_STL_Container<SgFunctionDeclaration*>& matlabFunctions)
{
return FastNumericsRoseSupport::collectNameToDeclarationPair(matlabFunctions);
}
MatlabAnalysis::NameToDeclarationMap
parseBuiltinDeclarations(std::string basedir)
{
typedef Rose_STL_Container<SgFunctionDeclaration*> DeclContainer;
std::string mfile = basedir + "/../../support/matlab/builtins.m";
std::string stubs = basedir + "/../../support/";
char* argv[] = { const_cast<char*>(""),
const_cast<char*>("-I"),
const_cast<char*>(stubs.c_str()),
const_cast<char*>(mfile.c_str())
};
int argc = sizeof(argv) / sizeof(char*);
SgProject* builtinProject = MatlabParser::frontend(argc, argv);
DeclContainer matlabFunctions = FastNumericsRoseSupport::getMatlabFunctions(builtinProject);
return collectNameToDeclarationPair(matlabFunctions);
}
struct UnrealVarFinder : AstSimpleProcessing
{
typedef MatlabAnalysis::NameToDeclarationMap NameToDeclarationMap;
explicit
UnrealVarFinder(NameToDeclarationMap funDecls)
: ids(), matlabFunDecls(funDecls)
{}
virtual void visit(SgNode* n);
operator std::vector<SgVarRefExp*>()
{
// return std::move(ids);
return ids;
}
private:
std::vector<SgVarRefExp*> ids;
NameToDeclarationMap matlabFunDecls;
};
struct UnrealVarHandler : sg::DispatchHandler<SgVarRefExp*>
{
typedef sg::DispatchHandler<SgVarRefExp*> base;
typedef UnrealVarFinder::NameToDeclarationMap NameToDeclarationMap;
explicit
UnrealVarHandler(const NameToDeclarationMap& funDecls)
: base(0), matlabFunDecls(funDecls)
{}
bool hasBuiltInFunction(std::string n)
{
NameToDeclarationMap::const_iterator pos = matlabFunDecls.find(n);
// \pp \todo test for zero-arity
return pos != matlabFunDecls.end();
}
void handle(SgNode&) {}
void handle(SgVarRefExp& n)
{
if ( hasBuiltInFunction(ru::nameOf(n))
&& !isSgCallExpression(n.get_parent())
)
{
res = &n;
}
}
private:
const NameToDeclarationMap& matlabFunDecls;
};
void UnrealVarFinder::visit(SgNode* n)
{
SgVarRefExp* exp = sg::dispatch(UnrealVarHandler(matlabFunDecls), n);
if (exp) ids.push_back(exp);
}
static
std::vector<SgVarRefExp*>
findUnrealVars(SgProject* proj, MatlabAnalysis::NameToDeclarationMap matlabFunDecls)
{
UnrealVarFinder uvf(matlabFunDecls);
uvf.traverse(proj, preorder);
return uvf;
}
static
SgVarRefExp*
createFunctionSymbol(SgVarRefExp* n)
{
SgVarRefExp* res = isSgVarRefExp(si::deepCopy(n));
ROSE_ASSERT(res);
return res;
}
static
void _makeFunCalls(SgVarRefExp* n)
{
ROSE_ASSERT(n);
SgFunctionCallExp* call = sb::buildFunctionCallExp(createFunctionSymbol(n));
ROSE_ASSERT(call);
std::cerr << "repl " << n->unparseToString() << " / " << call->unparseToString() << std::endl;
si::replaceExpression(n, call);
}
static
void makeFunCalls(const std::vector<SgVarRefExp*>& unrealVars)
{
std::for_each(unrealVars.begin(), unrealVars.end(), _makeFunCalls);
}
//
// function family to remove cloned declarations
static
void removeClonedFunctions_r(MatlabAnalysis::MatlabFunctionRec& fn)
{
// if the original definition was not used
if (!fn.second)
{
si::removeStatement(fn.first);
}
}
static
void removeClonedFunctions_s(MatlabAnalysis::NameToDeclarationMap::value_type& overloads)
{
std::for_each( overloads.second.begin(),
overloads.second.end(),
removeClonedFunctions_r
);
}
/**
* Removes those declarations that were cloned.
* This means we don't need the original function any more.
* Also builds variable declarations in all the functions
*/
static inline
void removeClonedFunctions(MatlabAnalysis::NameToDeclarationMap& nameToFuncDeclarations)
{
std::for_each(nameToFuncDeclarations.begin(), nameToFuncDeclarations.end(), removeClonedFunctions_s);
}
static inline
void _buildVariableDeclarations(SgNode* n)
{
MatlabAnalysis::buildVariableDeclarations(isSgFunctionDeclaration(n));
}
/**
* insert variable declarations in the cloned functions.
*/
static inline
void insertVariablesIntoFunctions(SgProject* proj)
{
Rose_STL_Container<SgNode*> fundecls = NodeQuery::querySubTree(proj, V_SgFunctionDeclaration);
std::for_each(fundecls.begin(), fundecls.end(), _buildVariableDeclarations);
}
static inline
void revertForLoopChanges(SgProject *project)
{
Rose_STL_Container<SgNode*> allMatlabFor = NodeQuery::querySubTree(project, V_SgMatlabForStatement);
for(size_t i = 0; i < allMatlabFor.size(); ++i)
{
SgMatlabForStatement* matlabFor = isSgMatlabForStatement(allMatlabFor[i]);
SgAssignOp* assignOp = isSgAssignOp(matlabFor->get_range());
SgExpression* index = assignOp->get_lhs_operand();
matlabFor->set_index(index);
index->set_parent(matlabFor);
SgExpression* range = assignOp->get_rhs_operand();
matlabFor->set_range(range);
range->set_parent(matlabFor);
}
}
namespace MatlabAnalysis
{
#if OBSOLETE_CODE
// \todo check if this is needed
void addAssignOpBeforeMatlabForStatement(SgProject *project)
{
Rose_STL_Container<SgNode*> allMatlabFor = NodeQuery::querySubTree(project, V_SgMatlabForStatement);
for(size_t i = 0; i < allMatlabFor.size(); ++i)
{
SgMatlabForStatement* matlabFor = isSgMatlabForStatement(allMatlabFor[i]);
SgExpression* index = matlabFor->get_index();
SgExpression* range = matlabFor->get_range();
SgAssignOp* assignOp = sb::buildAssignOp(index, range);
matlabFor->set_range(assignOp);
assignOp->set_parent(matlabFor);
}
}
#endif /* OBSOLETE_CODE */
static inline
bool
isPossibleEntryPoint(SgFunctionDeclaration* f)
{
ROSE_ASSERT(f);
return (sg::deref(f->get_parameterList()).get_args().size() == 0);
}
static inline
bool
isPossibleEntryPoint(MatlabFunctionRec& rec)
{
return isPossibleEntryPoint(rec.first);
}
void typeAnalysis(SgProject* project)
{
typedef Rose_STL_Container<SgFunctionDeclaration*> DeclContainer;
DeclContainer matlabFunctions = FastNumericsRoseSupport::getMatlabFunctions(project);
MatlabVariables::setTypes(project);
// There should be at least one function
if (matlabFunctions.size() == 0) return;
// Create a map from function name to the corresponding defining function declarations
// This will be used when cloning functions
Ctx::nameToFunctionDeclaration = collectNameToDeclarationPair(matlabFunctions);
// In a matlab file, the top function is always the main function.
// As a common practice its name usually matches the filename
SgFunctionDeclaration* mainFunction = matlabFunctions[0];
MatlabOverloadSet& overload = Ctx::nameToFunctionDeclaration[mainFunction->get_name()];
ROSE_ASSERT(overload.size() == 1);
MatlabFunctionRec& mainRec = overload.back();
if (!hasBeenAnalyzed(mainRec))
{
ROSE_ASSERT(isPossibleEntryPoint(mainRec));
setAnalyzed(mainRec);
FunctionAnalyzer functionAnalyzer(project);
functionAnalyzer.analyse_function(mainFunction);
}
/*
* \todo go through all entry points in a Matlab module
*
NameToDeclarationMap::iterator aa = Ctx::nameToFunctionDeclaration.begin();
NameToDeclarationMap::iterator zz = Ctx::nameToFunctionDeclaration.end();
if (aa != zz)
{
MatlabOverloadSet::iterator osaa = (*aa).second.begin();
MatlabOverloadSet::iterator oszz = (*aa).second.end();
if (osaa != oszz)
{
MatlabFunctionRec& fn = (*osaa);
++osaa;
}
++aa;
}
*/
// revertForLoopChanges(project);
// generateDOT(*project);
// The original functions from which we cloned need to be removed
// functionDeclarations
removeClonedFunctions(Ctx::nameToFunctionDeclaration);
// insert variables into cloned functions
insertVariablesIntoFunctions(project);
}
void makeFunFromUnrealVars(SgProject* proj)
{
typedef Rose_STL_Container<SgFunctionDeclaration*> DeclContainer;
NameToDeclarationMap allMatlabFunctionDeclarations = Ctx::matlabBuiltins;
const size_t numBuiltIns = allMatlabFunctionDeclarations.size();
DeclContainer matlabFunctions = FastNumericsRoseSupport::getMatlabFunctions(proj);
NameToDeclarationMap projFunctionDeclarations = collectNameToDeclarationPair(matlabFunctions);
const size_t numUserFuns = projFunctionDeclarations.size();
allMatlabFunctionDeclarations.insert( projFunctionDeclarations.begin(),
projFunctionDeclarations.end()
);
//~ std::cerr << numBuiltIns << " + " << numUserFuns
//~ << " == " << allMatlabFunctionDeclarations.size() << "?"
//~ << std::endl;
ROSE_ASSERT(numBuiltIns + numUserFuns == allMatlabFunctionDeclarations.size());
makeFunCalls(findUnrealVars(proj, allMatlabFunctionDeclarations));
}
void loadMatlabBuiltins(std::string basedir)
{
Ctx::matlabBuiltins = parseBuiltinDeclarations(basedir);
}
}
| 27.008264 | 104 | 0.700224 | [
"vector"
] |
3847aebd41006970577098b50d14950095935b28 | 1,539 | cpp | C++ | TaskLayer/EventArgs/XmlForTaskListEventArgs.cpp | edgargabriel/HPCMetaMorpheus | 160cc269464b8e563fa2f62f6843690b6a2533ee | [
"MIT"
] | 2 | 2020-09-10T19:14:20.000Z | 2021-09-11T16:36:56.000Z | TaskLayer/EventArgs/XmlForTaskListEventArgs.cpp | edgargabriel/HPCMetaMorpheus | 160cc269464b8e563fa2f62f6843690b6a2533ee | [
"MIT"
] | null | null | null | TaskLayer/EventArgs/XmlForTaskListEventArgs.cpp | edgargabriel/HPCMetaMorpheus | 160cc269464b8e563fa2f62f6843690b6a2533ee | [
"MIT"
] | 3 | 2020-09-11T01:19:47.000Z | 2021-09-02T02:05:01.000Z | #include "XmlForTaskListEventArgs.h"
#include "../DbForTask.h"
#include "stringhelper.h"
namespace TaskLayer
{
XmlForTaskListEventArgs::XmlForTaskListEventArgs(std::vector<DbForTask*> &newDatabases)
{
NewDatabases = newDatabases;
}
bool XmlForTaskListEventArgs::Equals( EventArgs *obj) const
{
XmlForTaskListEventArgs*o = dynamic_cast<XmlForTaskListEventArgs *>(obj);
if ( o != nullptr ) {
if ( o->NewDatabases.size() != NewDatabases.size() ) {
return false;
}
for ( int i=0; i <(int)NewDatabases.size(); i++ ) {
if ( o->NewDatabases[i]->getFilePath() != NewDatabases[i]->getFilePath() ||
o->NewDatabases[i]->getFileName() != NewDatabases[i]->getFileName() ||
o->NewDatabases[i]->getIsContaminant() == NewDatabases[i]->getIsContaminant() ) {
return false;
}
}
return true;
}
return false;
}
int XmlForTaskListEventArgs::GetHashCode() const
{
std::string s;
for ( auto db : NewDatabases ) {
s += db->getFilePath() + db->getFileName();
}
return StringHelper::GetHashCode(s);
}
std::string XmlForTaskListEventArgs::ToString() const
{
std::string s;
for ( auto db : NewDatabases ) {
s += db->getFilePath() + db->getFileName();
}
return s;
}
}
| 29.596154 | 103 | 0.528915 | [
"vector"
] |
384f88b5da12c3a2809f494096cd233e12aab892 | 24,738 | cpp | C++ | ts/src/debugExecutable.cpp | MrDj200/task-force-arma-3-radio | 21bb54d5d0e0b31b0522dc67e6923edb9ad85247 | [
"RSA-MD"
] | 300 | 2015-01-14T11:19:48.000Z | 2022-01-18T19:46:55.000Z | ts/src/debugExecutable.cpp | MrDj200/task-force-arma-3-radio | 21bb54d5d0e0b31b0522dc67e6923edb9ad85247 | [
"RSA-MD"
] | 742 | 2015-01-07T05:25:39.000Z | 2022-03-15T17:06:34.000Z | ts/src/debugExecutable.cpp | MrDj200/task-force-arma-3-radio | 21bb54d5d0e0b31b0522dc67e6923edb9ad85247 | [
"RSA-MD"
] | 280 | 2015-01-01T08:58:00.000Z | 2022-03-23T12:37:38.000Z |
#include "common.hpp"
#include "profilers.hpp"
#include "CommandProcessor.hpp"
#include "helpers.hpp"
#include "Logger.hpp"
#include "task_force_radio.hpp"
void assertfunc(bool as, std::string cause) {
if (as)
DebugBreak();
}
#define ASSERT(a) assertfunc(!(a),#a)
auto speedTestStringToGameCommand() {
std::string test1("TS_INFO");
std::string test2("IS_SPEAKING");
std::string test3("FREQ");
std::string test4("KILLED");
std::string test5("TRACK");
std::string test6("DFRAME");
std::string test7("SPEAKERS");
std::string test8("TANGENT");
std::string test9("TANGENT_LR");
std::string test10("TANGENT_DD");
std::string test11("RELEASE_ALL_TANGENTS");
std::string test12("SETCFG");
std::string test13("MISSIONEND");
std::string test14("unknown");
std::string test15("POS");
static gameCommand results[32];
std::chrono::high_resolution_clock::time_point start = std::chrono::high_resolution_clock::now();
for (auto i = 0; i < 1000000; ++i) {
results[0] = CommandProcessor::toGameCommand(test1, 2);
results[1] = CommandProcessor::toGameCommand(test2, 2);
results[2] = CommandProcessor::toGameCommand(test3, 14);
results[3] = CommandProcessor::toGameCommand(test4, 3);
results[4] = CommandProcessor::toGameCommand(test5, 4);
results[5] = CommandProcessor::toGameCommand(test6, 1);
results[6] = CommandProcessor::toGameCommand(test7, 1);
results[7] = CommandProcessor::toGameCommand(test8, 6);
results[8] = CommandProcessor::toGameCommand(test9, 6);
results[9] = CommandProcessor::toGameCommand(test10, 6);
results[10] = CommandProcessor::toGameCommand(test11, 2);
results[11] = CommandProcessor::toGameCommand(test12, 3);
results[12] = CommandProcessor::toGameCommand(test13, 1);
results[13] = CommandProcessor::toGameCommand(test14, 1);
results[14] = CommandProcessor::toGameCommand(test15, 12);
}
std::chrono::high_resolution_clock::time_point now = std::chrono::high_resolution_clock::now();
ASSERT(results[0] == gameCommand::TS_INFO);
ASSERT(results[1] == gameCommand::IS_SPEAKING);
ASSERT(results[2] == gameCommand::FREQ);
ASSERT(results[3] == gameCommand::KILLED);
ASSERT(results[4] == gameCommand::TRACK);
ASSERT(results[5] == gameCommand::DFRAME);
ASSERT(results[6] == gameCommand::SPEAKERS);
ASSERT(results[7] == gameCommand::TANGENT);
ASSERT(results[8] == gameCommand::TANGENT);
ASSERT(results[9] == gameCommand::TANGENT);
ASSERT(results[10] == gameCommand::RELEASE_ALL_TANGENTS);
ASSERT(results[11] == gameCommand::SETCFG);
ASSERT(results[12] == gameCommand::MISSIONEND);
ASSERT(results[13] == gameCommand::unknown);
ASSERT(results[14] == gameCommand::POS);
auto duration = std::chrono::duration_cast<std::chrono::nanoseconds>(now - start);
profiler::log(std::to_string(duration.count() / 1000000) + " nanoseconds per iteration");
return duration;
}
#include <vector>
auto speedTestStringSplit() {
std::vector<std::string> splitted;
splitted.reserve(50);
std::string toSplit("test\tTHIS is a\ttest\ttest\t\t\ttest\ttest\test");
static size_t results[32];
std::chrono::high_resolution_clock::time_point start = std::chrono::high_resolution_clock::now();
for (auto i = 0; i < 1000000; ++i) {
helpers::split(toSplit, '\t', splitted);
results[0] = splitted.size();
splitted.clear();
}
std::chrono::high_resolution_clock::time_point now = std::chrono::high_resolution_clock::now();
ASSERT(results[0] > 1);
auto duration = std::chrono::duration_cast<std::chrono::nanoseconds>(now - start);
profiler::log(std::to_string(duration.count() / 1000000) + " nanoseconds per iteration");
return duration;
}
auto speedTestStringSplitRef() {
//std::vector<boost::string_ref> splitted;
//splitted.reserve(50);
//std::string toSplit("test\tTHIS is a\ttest\ttest\t\t\ttest\ttest\test");
//static size_t results[32];
//std::chrono::high_resolution_clock::time_point start = std::chrono::high_resolution_clock::now();
//for (auto i = 0; i < 1000000; ++i) {
// helpers::split(boost::string_ref(toSplit), '\t', splitted);
// results[0] = splitted.size();
// splitted.clear();
//}
//std::chrono::high_resolution_clock::time_point now = std::chrono::high_resolution_clock::now();
//ASSERT(results[0] > 1);
//auto duration = std::chrono::duration_cast<std::chrono::nanoseconds>(now - start);
//profiler::log(std::to_string(duration.count() / 1000000) + " nanoseconds per iteration");
//return duration;
}
auto clientDataMapAccess() {
std::unordered_map<std::string, std::shared_ptr<clientData>> data;
std::map<TSClientID, std::shared_ptr<clientData>> data2;
std::string name1("test1");
std::string name2("test2");
std::string name3("test3");
std::string name4("test4");
std::string name5("test5");
std::string name6("test6");
std::string name7("test7");
auto findInData = [&](const std::string& str) {
return data.find(str);
};
auto findInData2 = [&](const TSClientID& cid) {
return data2.find(cid);
};
auto insertInData = [&](const std::string& str, TSClientID clientID) {
data.insert_or_assign(str, nullptr);
data2.insert_or_assign(clientID, nullptr);
};
insertInData(name1, 1);
insertInData(name2, 2);
insertInData(name3, 3);
insertInData(name4, 4);
insertInData(name5, 5);
insertInData(name6, 6);
insertInData(name7, 7);
static std::unordered_map<std::string, std::shared_ptr<clientData>>::iterator results[32];
static std::map<TSClientID, std::shared_ptr<clientData>>::iterator results2[32];
std::chrono::high_resolution_clock::time_point start = std::chrono::high_resolution_clock::now();
for (auto i = 0; i < 1000000; ++i) {
results[0] = findInData(name1);
results[1] = findInData(name2);
results[2] = findInData(name3);
results[3] = findInData(name4);
results[4] = findInData(name5);
results[5] = findInData(name6);
results[6] = findInData(name7);
results2[0] = findInData2(1);
results2[1] = findInData2(2);
results2[2] = findInData2(3);
results2[3] = findInData2(4);
results2[4] = findInData2(5);
results2[5] = findInData2(6);
results2[6] = findInData2(7);
}
std::chrono::high_resolution_clock::time_point now = std::chrono::high_resolution_clock::now();
ASSERT(results[0] != data.end());
ASSERT(results2[0] != data2.end());
auto duration = std::chrono::duration_cast<std::chrono::nanoseconds>(now - start);
profiler::log(std::to_string(duration.count() / 1000000) + " nanoseconds per iteration");
return duration;
}
auto clientDataVectorAccess() {
using clientDataDirectoryElement = std::tuple<size_t, TSClientID, std::shared_ptr<clientData>>;
std::vector<clientDataDirectoryElement> data;
std::string name1("test1");
std::string name2("test2");
std::string name3("test3");
std::string name4("test4");
std::string name5("test5");
std::string name6("test6");
std::string name7("test7");
auto findInData = [&](const std::string& str) {
auto range = std::equal_range(data.begin(), data.end(), std::make_tuple(std::hash<std::string>()(str), 0, nullptr), [](const auto& lhs, const auto& rhs) {
return std::get<0>(lhs) < std::get<0>(rhs);
});
if (range.first == range.second) return data.end();
return range.first;
};
auto findInData2 = [&](const TSClientID& cid) {
return std::find_if(data.begin(), data.end(), [&cid](const auto& lhs) {
return std::get<1>(lhs) == cid;
});
};
auto insertInData = [&](const std::string& str, TSClientID clientID) {
auto hash = std::hash<std::string>()(str);
data.emplace(std::upper_bound(data.begin(), data.end(), hash, [](const size_t& hash, const auto& tup) {
return hash < std::get<0>(tup);
}), hash, clientID, std::shared_ptr<clientData>());
};
insertInData(name1, 1);
insertInData(name2, 2);
insertInData(name3, 3);
insertInData(name4, 4);
insertInData(name5, 5);
insertInData(name6, 6);
insertInData(name7, 7);
static std::vector<clientDataDirectoryElement>::iterator results[32];
std::chrono::high_resolution_clock::time_point start = std::chrono::high_resolution_clock::now();
for (auto i = 0; i < 1000000; ++i) {
results[0] = findInData(name1);
results[1] = findInData(name2);
results[2] = findInData(name3);
results[3] = findInData(name4);
results[4] = findInData(name5);
results[5] = findInData(name6);
results[6] = findInData(name7);
results[0] = findInData2(1);
results[1] = findInData2(2);
results[2] = findInData2(3);
results[3] = findInData2(4);
results[4] = findInData2(5);
results[5] = findInData2(6);
results[6] = findInData2(7);
}
std::chrono::high_resolution_clock::time_point now = std::chrono::high_resolution_clock::now();
ASSERT(results[0] != data.end());
auto duration = std::chrono::duration_cast<std::chrono::nanoseconds>(now - start);
profiler::log(std::to_string(duration.count() / 1000000) + " nanoseconds per iteration");
return duration;
}
auto speedTestGainOrig() {
auto applyGainOrig = [](short * samples, size_t sampleCount, int channels, float directTalkingVolume) {
if (directTalkingVolume == 0.0f) {
memset(samples, 0, sampleCount * channels * sizeof(short));
return;
}
if (directTalkingVolume == 1.0f) //no change in gain
return;
for (size_t i = 0; i < sampleCount * channels; i++) samples[i] = static_cast<short>(samples[i] * directTalkingVolume);
};
std::vector<short> data;
data.resize(8096, 1000);
static short results[32];
std::chrono::high_resolution_clock::time_point start = std::chrono::high_resolution_clock::now();
for (auto i = 0; i < 1000000; ++i) {
applyGainOrig(data.data(), 8096 / 2, 2, 0.999f);
results[0] = data.front();
}
std::chrono::high_resolution_clock::time_point now = std::chrono::high_resolution_clock::now();
ASSERT(results[0] >= 0);
auto duration = std::chrono::duration_cast<std::chrono::nanoseconds>(now - start);
profiler::log(std::to_string(duration.count() / 1000000) + " nanoseconds per iteration");
return duration;
}
#include <emmintrin.h>
auto speedTestGainOrigInt() {
auto applyGainOrig = [](short * samples, size_t sampleCount, int channels, float directTalkingVolume) {
if (directTalkingVolume == 0.0f) {
memset(samples, 0, sampleCount * channels * sizeof(short));
return;
}
if (directTalkingVolume == 1.0f) //no change in gain
return;
if (IsProcessorFeaturePresent(PF_XMMI64_INSTRUCTIONS_AVAILABLE)) {
auto leftOver = (sampleCount * channels) % 8;
__m128 xmm3;
float multiplier[4] = { directTalkingVolume ,directTalkingVolume ,directTalkingVolume,directTalkingVolume };
xmm3 = _mm_loadu_ps(multiplier);
for (size_t i = 0; i < sampleCount * channels; i += 8) {
__m128i xmm0;
__m128i xmm1;
__m128i xmm2;
__m128i xmm4{ 0 };
_mm_store_si128(&xmm2, xmm4);
xmm1 = _mm_load_si128(reinterpret_cast<__m128i*>(samples + i));
xmm2 = _mm_cmpgt_epi16(xmm2, xmm1);
_mm_store_si128(&xmm0, xmm1);
xmm1 = _mm_unpackhi_epi16(xmm1, xmm2);
xmm0 = _mm_unpacklo_epi16(xmm0, xmm2);
auto multPack1 = _mm_cvtepi32_ps(xmm1);
auto multPack2 = _mm_cvtepi32_ps(xmm0);
multPack1 = _mm_mul_ps(multPack1, xmm3);
multPack2 = _mm_mul_ps(multPack2, xmm3);
xmm1 = _mm_cvttps_epi32(multPack1);
xmm0 = _mm_cvttps_epi32(multPack2);
_mm_store_si128(&xmm2, xmm0);
xmm0 = _mm_unpacklo_epi16(xmm0, xmm1);
xmm2 = _mm_unpackhi_epi16(xmm2, xmm1);
_mm_store_si128(&xmm1, xmm0);
xmm0 = _mm_unpacklo_epi16(xmm0, xmm2);
xmm1 = _mm_unpackhi_epi16(xmm1, xmm2);
xmm0 = _mm_unpacklo_epi16(xmm0, xmm1);
_mm_store_si128(reinterpret_cast<__m128i*>(samples + i), xmm0);
}
for (size_t i = sampleCount * channels - leftOver; i < sampleCount * channels; i++) {
samples[i] = static_cast<short>(samples[i] * directTalkingVolume);
}
} else {
for (size_t i = sampleCount * channels; i < sampleCount * channels; i++) samples[i] = static_cast<short>(samples[i] * directTalkingVolume);
//Can also use transform but that might be bad in Debug Mode
//std::transform(samples, samples + sampleCount * channels, samples, [directTalkingVolume](auto samp) {return samp * directTalkingVolume; });
}
};
std::vector<short> data;
data.resize(8096, 1000);
static short results[32];
std::chrono::high_resolution_clock::time_point start = std::chrono::high_resolution_clock::now();
for (auto i = 0; i < 1000000; ++i) {
applyGainOrig(data.data(), 8096 / 2, 2, 0.999f);
results[0] = data.front();
}
std::chrono::high_resolution_clock::time_point now = std::chrono::high_resolution_clock::now();
ASSERT(results[0] >= 0);
auto duration = std::chrono::duration_cast<std::chrono::nanoseconds>(now - start);
profiler::log(std::to_string(duration.count() / 1000000) + " nanoseconds per iteration");
return duration;
}
auto speedTestGainOrigInt2() {
auto applyGainOrig = [](short * samples, size_t sampleCount, int channels, float directTalkingVolume) {
if (directTalkingVolume == 0.0f) {
memset(samples, 0, sampleCount * channels * sizeof(short));
return;
}
if (directTalkingVolume == 1.0f) //no change in gain
return;
/*
Thanks GCC!
https://godbolt.org/#g:!((g:!((g:!((h:codeEditor,i:(j:1,source:'%23include+%3Calgorithm%3E%0Ashort+square(int+num)+%7B%0A++++short+samples%5B4096%5D%3B%0A%0A++++for+(size_t+i+%3D+0%3B+i+%3C+4096%3B+i%2B%2B)+samples%5Bi%5D+%3D+static_cast%3Cshort%3E(samples%5Bi%5D+*+0.999f)%3B%0A+++//std::transform(samples,+samples%2B4096,+samples,+%5B%5D(auto+samp)+%7Breturn+samp+*+0.999f%3B+%7D)%3B%0A++++return+samples%5B777%5D%3B%0A%7D'),l:'5',n:'0',o:'C%2B%2B+source+%231',t:'0')),k:50,l:'4',n:'0',o:'',s:0,t:'0'),(g:!((h:compiler,i:(compiler:g7snapshot,filters:(b:'0',commentOnly:'0',directives:'0',intel:'0'),options:'-O3',source:1),l:'5',n:'0',o:'x86-64+gcc+7+(snapshot)+(Editor+%231,+Compiler+%231)',t:'0')),k:50,l:'4',n:'0',o:'',s:0,t:'0')),l:'2',n:'0',o:'',t:'0')),version:4
*/
if (IsProcessorFeaturePresent(PF_XMMI64_INSTRUCTIONS_AVAILABLE)) {
auto leftOver = (sampleCount * channels) % 8;
__m128 xmm3;
float multiplier[4] = { directTalkingVolume ,directTalkingVolume ,directTalkingVolume,directTalkingVolume };
xmm3 = _mm_loadu_ps(multiplier);
helpers::shortFloatMultEx(samples, sampleCount * channels, xmm3);
for (size_t i = sampleCount * channels - leftOver; i < sampleCount * channels; i++) {
samples[i] = static_cast<short>(samples[i] * directTalkingVolume);
}
} else {
for (size_t i = sampleCount * channels; i < sampleCount * channels; i++) samples[i] = static_cast<short>(samples[i] * directTalkingVolume);
//Can also use transform but that might be bad in Debug Mode
//std::transform(samples, samples + sampleCount * channels, samples, [directTalkingVolume](auto samp) {return samp * directTalkingVolume; });
}
};
std::vector<short> data;
data.resize(8096, 1000);
static short results[32];
std::chrono::high_resolution_clock::time_point start = std::chrono::high_resolution_clock::now();
for (auto i = 0; i < 1000000; ++i) {
applyGainOrig(data.data(), 8096 / 2, 2, 0.999f);
results[0] = data.front();
}
std::chrono::high_resolution_clock::time_point now = std::chrono::high_resolution_clock::now();
ASSERT(results[0] >= 0);
auto duration = std::chrono::duration_cast<std::chrono::nanoseconds>(now - start);
profiler::log(std::to_string(duration.count() / 1000000) + " nanoseconds per iteration");
return duration;
}
auto speedTestGainTransform() {
auto applyGainOrig = [](short * samples, size_t sampleCount, int channels, float directTalkingVolume) {
if (directTalkingVolume == 0.0f) {
memset(samples, 0, sampleCount * channels * sizeof(short));
return;
}
if (directTalkingVolume == 1.0f) //no change in gain
return;
std::transform(samples, samples + sampleCount * channels, samples, [directTalkingVolume](auto samp) {return samp * directTalkingVolume; });
};
std::vector<short> data;
data.resize(8192, 1000);
static short results[32];
std::chrono::high_resolution_clock::time_point start = std::chrono::high_resolution_clock::now();
for (auto i = 0; i < 1000000; ++i) {
applyGainOrig(data.data(), 8192 / 2, 2, 0.999f);
results[0] = data.front();
}
std::chrono::high_resolution_clock::time_point now = std::chrono::high_resolution_clock::now();
ASSERT(results[0] >= 0);
auto duration = std::chrono::duration_cast<std::chrono::nanoseconds>(now - start);
profiler::log(std::to_string(duration.count() / 1000000) + " nanoseconds per iteration");
return duration;
}
#include <future>
//class threadPoolTest {
//public:
// threadPoolTest() {
// for (size_t i = 0; i < std::thread::hardware_concurrency(); i++)
// {
// threads.push_back(std::thread([&]() {
// auto mask = (static_cast<DWORD_PTR>(1) << i);//core number starts from 0
// auto ret = SetThreadAffinityMask(GetCurrentThread(), mask);
// while (running) {
// std::packaged_task<void(void)> item;
// //while (!tasks.try_dequeue(item)) {
// // continue;
// //}
// tasks.wait_dequeue(item);
// item();
// };
// }));
// }
// }
// void addTask(std::packaged_task<void(void)>&& fnc) {
// tasks.enqueue(std::move(fnc));
// }
// bool running{ true };
// moodycamel::BlockingConcurrentQueue<std::packaged_task<void(void)>> tasks;
// std::vector<std::thread> threads;
//} threadPool;
auto speedTestGainTransformPar() {
auto applyGainOrig = [](short * samples, size_t sampleCount, int channels, float directTalkingVolume) {
if (directTalkingVolume == 0.0f) {
memset(samples, 0, sampleCount * channels * sizeof(short));
return;
}
if (directTalkingVolume == 1.0f) //no change in gain
return;
if (channels == 4) {
auto func = [directTalkingVolume](short* start, short* end) {
std::transform(start, end, start, [directTalkingVolume](auto samp) {return samp * directTalkingVolume; });
};
//std::packaged_task<void(void)> tsk1([&]() {func(samples, samples + sampleCount*4); });
std::packaged_task<void(void)> tsk1([&]() {func(samples, samples + sampleCount); });
std::packaged_task<void(void)> tsk2([&]() {func(samples + sampleCount, samples + sampleCount * 2); });
std::packaged_task<void(void)> tsk3([&]() {func(samples + sampleCount * 2, samples + sampleCount * 3); });
std::packaged_task<void(void)> tsk4([&]() {func(samples + sampleCount * 3, samples + sampleCount * 4); });
auto fut1 = tsk1.get_future();
auto fut2 = tsk2.get_future();
auto fut3 = tsk3.get_future();
auto fut4 = tsk4.get_future();
//threadPool.addTask(std::move(tsk1));
//threadPool.addTask(std::move(tsk2));
//threadPool.addTask(std::move(tsk3));
//threadPool.addTask(std::move(tsk4));
//std::thread th1(std::move(tsk1), samples, samples + sampleCount);
//std::thread th2(std::move(tsk2), samples + sampleCount, samples + sampleCount * 2);
//std::thread th3(std::move(tsk3), samples + sampleCount * 2, samples + sampleCount * 3);
//std::thread th4(std::move(tsk4), samples + sampleCount * 3, samples + sampleCount * 4);
//auto fut1 = std::async(func, samples, samples + sampleCount);
//auto fut2 = std::async(func, samples + sampleCount, samples + sampleCount * 2);
//auto fut3 = std::async(func, samples + sampleCount * 2, samples + sampleCount * 3);
//auto fut4 = std::async(func, samples + sampleCount * 3, samples + sampleCount * 4);
fut1.wait();
fut2.wait();
fut3.wait();
fut4.wait();
//func(samples, samples + sampleCount);
//func(samples + sampleCount, samples + sampleCount * 2);
//func(samples + sampleCount * 2, samples + sampleCount * 3);
//func(samples + sampleCount * 3, samples + sampleCount * 4);
//th1 .join();
// th2 .join();
// th3 .join();
// th4 .join();
}
else {
std::transform(samples, samples + sampleCount * channels, samples, [directTalkingVolume](auto samp) {return samp * directTalkingVolume; });
}
};
std::vector<short> data;
data.resize(8192, 1000);
static short results[32];
std::chrono::high_resolution_clock::time_point start = std::chrono::high_resolution_clock::now();
for (auto i = 0; i < 1000000; ++i) {
applyGainOrig(data.data(), 8192 / 4, 4, 0.999f);
results[0] = data.front();
}
std::chrono::high_resolution_clock::time_point now = std::chrono::high_resolution_clock::now();
ASSERT(results[0] >= 0);
auto duration = std::chrono::duration_cast<std::chrono::nanoseconds>(now - start);
profiler::log(std::to_string(duration.count() / 1000000) + " nanoseconds per iteration");
return duration;
}
static volatile float speedTestVector3DDiv_div = 3.f;
#include <random>
auto speedTestVector3DDiv() {
static BOOL results[32];
std::chrono::high_resolution_clock::time_point start = std::chrono::high_resolution_clock::now();
for (auto i = 0; i < 1000000; ++i) {
results[0] += IsProcessorFeaturePresent(PF_XMMI64_INSTRUCTIONS_AVAILABLE);
}
std::chrono::high_resolution_clock::time_point now = std::chrono::high_resolution_clock::now();
ASSERT(results[0] > 0);
auto duration = std::chrono::duration_cast<std::chrono::nanoseconds>(now - start);
profiler::log(std::to_string(duration.count() / 1000000) + " nanoseconds per iteration");
return duration;
}
int main() {
//Logger::registerLogger(LoggerTypes::profiler, std::make_shared<DebugStringLogger>());
//auto durationStringToGameCommand = speedTestStringToGameCommand(); //should be < 300ns release <1300 ns debug
//auto durationStringSplit = speedTestStringSplit(); //should be < 260ns release
//auto durationStringSplit2 = speedTestStringSplitRef(); //should be < 140ns release
//clientDataVectorAccess();//150ns
//clientDataMapAccess();//250ns
//speedTestGainOrig();
//speedTestGainOrigInt();
//speedTestGainOrigInt2();
//auto durationApplyGainOrig = speedTestGainOrig();
//auto durationApplyGainTrans = speedTestGainTransform();
//auto durationApplyGainTransPar = speedTestGainTransformPar();
//speedTestVector3DDiv();
//ASSERT(TFAR::Version("0.9.9") > TFAR::Version("0.9.8"));
//ASSERT(TFAR::Version("0.9.13") > TFAR::Version("0.9.12"));
//ASSERT(TFAR::Version("1.0.0.0") > TFAR::Version("0.9.8"));
//ASSERT(TFAR::Version("1.0.0.0") > TFAR::Version("0.9.12"));
//ASSERT(TFAR::Version("1.0.0") > TFAR::Version("0.9.12"));
Position3D above(10, 10, 10);
Position3D below(-10, -10, -10);
float dist = above.distanceUnderwater(below);
TFAR::debugUI.run();
getchar();
return 0;
}
| 42.505155 | 778 | 0.620139 | [
"vector",
"transform",
"3d"
] |
ee2fcc92220bb415c0199e1a9a9311f0bda00db9 | 7,180 | cpp | C++ | C++/lang/templates.cpp | nihilesh/sharpner | bb74a20cebb5de284b50b1b81dc5b4b7fca34b7c | [
"Apache-2.0"
] | null | null | null | C++/lang/templates.cpp | nihilesh/sharpner | bb74a20cebb5de284b50b1b81dc5b4b7fca34b7c | [
"Apache-2.0"
] | null | null | null | C++/lang/templates.cpp | nihilesh/sharpner | bb74a20cebb5de284b50b1b81dc5b4b7fca34b7c | [
"Apache-2.0"
] | null | null | null | #include <iostream>
#include <vector>
#include <unordered_map>
#include <assert.h>
using namespace std;
#if 0
namespace test1 {
typedef struct TabletBase_t {
public:
vector<uint64_t> u64_cells;
vector<float> f64_cells;
}TabletBase;
template<class T>
T allOf_(T a, T b) {
return T();
}
template<class T>
T opAverage__(T writeVal, T readVal, int count){
assert(false && "average operatio not supported for this datatype");
}
template<>
float opAverage__<float>(float writeVal, float readVal, int count) {
float sum = (float)writeVal + (float)readVal;
return (float)(sum/count);
}
template<>
int opAverage__<int>(int writeVal, int readVal, int count) {
cout << writeVal << " " << readVal << " " << count << endl;
int sum = (int)writeVal + (int)readVal;
cout << sum/count << " " << endl;
return (int)(sum/count);
}
template<class T, int count=2>
T opAverage_(T writeVal, T readVal) {
return opAverage__(writeVal, readVal, count);
}
template<class T, T(*Op)(T, T)>
T operate(T a, T b){
T v = Op(a,b);
cout << v << endl;
return v;
}
} // Namespace
/**********************************/
struct Tablet;
using TabletPtr = Tablet *;
using RowIndex = int;
using U64 = unsigned long;
struct Tablet {
U64 u64Cell(int rowId) {return 2;}
void u64CellIs(int rowId, U64 val) {
cout << "rowID: " << rowId << " value: " << val << endl;
}
};
namespace test2 {
template <class T>
class AggregatorBase {
public:
// virtual void anyOf() = 0 ;
// virtual void average(unsigned int count) = 0 ;
// virtual void min() = 0 ;
// virtual void max() = 0 ;
// virtual void last() = 0 ;
TabletPtr writeTablet;
TabletPtr readTablet;
RowIndex writeRowIdx;
RowIndex readRowIdx;
virtual T getCell(const TabletPtr tablet, RowIndex idx) = 0;
virtual void setCell(TabletPtr tablet, RowIndex idx, T val) = 0;
virtual void allOf(){
cout << "All of" << endl;
T writeVal = getCell(writeTablet, writeRowIdx);
T readVal = getCell(readTablet, readRowIdx);
setCell(writeTablet, writeRowIdx, readVal ? writeVal : readVal);
}
};
template<class T>
class SeamAggregator : public AggregatorBase<T> {
};
template<>
class SeamAggregator<U64> : public AggregatorBase<U64> {
public:
U64 getCell(const TabletPtr tablet, RowIndex idx) {
return tablet->u64Cell(idx);
}
void setCell(TabletPtr tablet, RowIndex idx, U64 val) {
tablet->u64CellIs(idx, val);
}
using AggregatorBase::allOf;
};
// int main() {
// SeamAggregator<U64> u64Aggregator;
// Tablet writeTablet, readTablet;
// u64Aggregator.writeTablet = &writeTablet;
// u64Aggregator.readTablet = &readTablet;
// u64Aggregator.writeRowIdx = u64Aggregator.readRowIdx = 3;
// u64Aggregator.allOf();
// }
} // Namespace test2
#endif
/* ----------------------------------------------------------------------*/
#ifdef 0
namespace {
struct Tablet {
void boolCellIs(int index, bool val) {
cout <<"Bool cell is: " << val << endl;
}
void intCellIs(int index, int val) {
cout <<"Bool cell is: " << val << endl;
}
void stringCellIs(int index, string val) {
cout <<"Bool cell is: " << val << endl;
}
int intCell(int index) const { return 9; }
string stringCell(int index) const { return "device-1"; }
bool boolCell(int index) const { return false; }
};
template <class T>
struct CellAccessor {
public:
static T getCell(const Tablet& tablet, int index){}
static void setCell(Tablet& tablet, int index, T val){}
};
template<>
struct CellAccessor<int> {
static int getCell(const Tablet& tablet, int index){return tablet.intCell(index);}
static void setCell(Tablet& tablet, int index, int val){tablet.intCellIs(index, val);}
};
template<>
struct CellAccessor<string> {
static string getCell(const Tablet& tablet, int index){return tablet.stringCell(index);}
static void setCell(Tablet& tablet, int index, string val){tablet.stringCellIs(index, val);}
};
template<>
struct CellAccessor<bool> {
static bool getCell(const Tablet& tablet, int index){return tablet.boolCell(index);}
static void setCell(Tablet& tablet, int index, bool val){tablet.boolCellIs(index, val);}
};
template <class T>
void allOf(Tablet& writeTablet, Tablet& readTablet, int readIdx, int writeIdx){
auto readVal = CellAccessor<T>::getCell(readTablet, readIdx);
auto writeVal = CellAccessor<T>::getCell(readTablet, readIdx);
CellAccessor<T>::setCell(writeTablet, writeIdx, readVal ? writeVal: 0);
}
template<>
void allOf<int>(Tablet& writeTablet, Tablet& readTablet, int readIdx, int writeIdx){
auto readVal = CellAccessor<int>::getCell(readTablet, readIdx);
auto writeVal = CellAccessor<int>::getCell(readTablet, readIdx);
CellAccessor<int>::setCell(writeTablet, writeIdx, readVal ? writeVal: 0);
}
template <class T>
void average(Tablet& writeTablet, Tablet& readTablet, int readIdx, int writeIdx, int count) {
assert(false);
}
template <>
void average<int> (Tablet& writeTablet, Tablet& readTablet, int readIdx, int writeIdx, int count) {
auto readVal = CellAccessor<int>::getCell(readTablet, readIdx);
auto writeVal = CellAccessor<int>::getCell(readTablet, readIdx);
CellAccessor<int>::setCell(writeTablet, writeIdx, readVal + writeVal / count);
}
struct SeamAggregator {
SeamAggregator(
Tablet* writeTablet,
const Tablet* readTablet) : writeTablet(writeTablet), readTablet(readTablet) {}
const unordered_map <int, void*> avgFuncMap = {
{1, (void*)&average<int>},
{2, (void*)&average<float>},
};
void allOf(int type, int readIdx, int writeIdx){
switch(type) {
case 1:
{
auto readVal = CellAccessor<int>::getCell(*readTablet, readIdx);
auto writeVal = CellAccessor<int>::getCell(*writeTablet, writeIdx);
cout << "allOf(" << type << "," << readIdx << "," << writeIdx << ")" << endl;
break;
}
case 2:
{
auto readVal = CellAccessor<int>::getCell(*readTablet, readIdx);
auto writeVal = CellAccessor<int>::getCell(*writeTablet, writeIdx);
cout << "allOf(" << type << "," << readIdx << "," << writeIdx << ")" << endl;
break;
}
default:
assert(false && "type not supported");
}
}
Tablet *writeTablet;
const Tablet *readTablet;
};
} // Namespace
#endif
namespace {
template <typename T>
class SeamAggregator {
T average(T a, T b, int count){
return a+b/count;
}
};
}
int main() {
Tablet writeTablet, readTablet;
SeamAggregator sAggr(&writeTablet, &readTablet);
sAggr.allOf(1, 2, 3);
} | 29.547325 | 103 | 0.601114 | [
"vector"
] |
ee2ff56461277d7bacaf49ebc0cb6beb9275c59c | 109,094 | cc | C++ | gen/pb-cpp/flyteidl/plugins/sagemaker/parameter_ranges.pb.cc | EngHabu/flyteidl | d7970314fc2bcbd2840610b4d42ea2886f0837b9 | [
"Apache-2.0"
] | null | null | null | gen/pb-cpp/flyteidl/plugins/sagemaker/parameter_ranges.pb.cc | EngHabu/flyteidl | d7970314fc2bcbd2840610b4d42ea2886f0837b9 | [
"Apache-2.0"
] | null | null | null | gen/pb-cpp/flyteidl/plugins/sagemaker/parameter_ranges.pb.cc | EngHabu/flyteidl | d7970314fc2bcbd2840610b4d42ea2886f0837b9 | [
"Apache-2.0"
] | null | null | null | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: flyteidl/plugins/sagemaker/parameter_ranges.proto
#include "flyteidl/plugins/sagemaker/parameter_ranges.pb.h"
#include <algorithm>
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/extension_set.h>
#include <google/protobuf/wire_format_lite_inl.h>
#include <google/protobuf/descriptor.h>
#include <google/protobuf/generated_message_reflection.h>
#include <google/protobuf/reflection_ops.h>
#include <google/protobuf/wire_format.h>
// @@protoc_insertion_point(includes)
#include <google/protobuf/port_def.inc>
extern PROTOBUF_INTERNAL_EXPORT_flyteidl_2fplugins_2fsagemaker_2fparameter_5franges_2eproto ::google::protobuf::internal::SCCInfo<0> scc_info_CategoricalParameterRange_flyteidl_2fplugins_2fsagemaker_2fparameter_5franges_2eproto;
extern PROTOBUF_INTERNAL_EXPORT_flyteidl_2fplugins_2fsagemaker_2fparameter_5franges_2eproto ::google::protobuf::internal::SCCInfo<0> scc_info_ContinuousParameterRange_flyteidl_2fplugins_2fsagemaker_2fparameter_5franges_2eproto;
extern PROTOBUF_INTERNAL_EXPORT_flyteidl_2fplugins_2fsagemaker_2fparameter_5franges_2eproto ::google::protobuf::internal::SCCInfo<0> scc_info_IntegerParameterRange_flyteidl_2fplugins_2fsagemaker_2fparameter_5franges_2eproto;
extern PROTOBUF_INTERNAL_EXPORT_flyteidl_2fplugins_2fsagemaker_2fparameter_5franges_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_ParameterRanges_ParameterRangeMapEntry_DoNotUse_flyteidl_2fplugins_2fsagemaker_2fparameter_5franges_2eproto;
extern PROTOBUF_INTERNAL_EXPORT_flyteidl_2fplugins_2fsagemaker_2fparameter_5franges_2eproto ::google::protobuf::internal::SCCInfo<3> scc_info_ParameterRangeOneOf_flyteidl_2fplugins_2fsagemaker_2fparameter_5franges_2eproto;
namespace flyteidl {
namespace plugins {
namespace sagemaker {
class HyperparameterScalingTypeDefaultTypeInternal {
public:
::google::protobuf::internal::ExplicitlyConstructed<HyperparameterScalingType> _instance;
} _HyperparameterScalingType_default_instance_;
class ContinuousParameterRangeDefaultTypeInternal {
public:
::google::protobuf::internal::ExplicitlyConstructed<ContinuousParameterRange> _instance;
} _ContinuousParameterRange_default_instance_;
class IntegerParameterRangeDefaultTypeInternal {
public:
::google::protobuf::internal::ExplicitlyConstructed<IntegerParameterRange> _instance;
} _IntegerParameterRange_default_instance_;
class CategoricalParameterRangeDefaultTypeInternal {
public:
::google::protobuf::internal::ExplicitlyConstructed<CategoricalParameterRange> _instance;
} _CategoricalParameterRange_default_instance_;
class ParameterRangeOneOfDefaultTypeInternal {
public:
::google::protobuf::internal::ExplicitlyConstructed<ParameterRangeOneOf> _instance;
const ::flyteidl::plugins::sagemaker::ContinuousParameterRange* continuous_parameter_range_;
const ::flyteidl::plugins::sagemaker::IntegerParameterRange* integer_parameter_range_;
const ::flyteidl::plugins::sagemaker::CategoricalParameterRange* categorical_parameter_range_;
} _ParameterRangeOneOf_default_instance_;
class ParameterRanges_ParameterRangeMapEntry_DoNotUseDefaultTypeInternal {
public:
::google::protobuf::internal::ExplicitlyConstructed<ParameterRanges_ParameterRangeMapEntry_DoNotUse> _instance;
} _ParameterRanges_ParameterRangeMapEntry_DoNotUse_default_instance_;
class ParameterRangesDefaultTypeInternal {
public:
::google::protobuf::internal::ExplicitlyConstructed<ParameterRanges> _instance;
} _ParameterRanges_default_instance_;
} // namespace sagemaker
} // namespace plugins
} // namespace flyteidl
static void InitDefaultsHyperparameterScalingType_flyteidl_2fplugins_2fsagemaker_2fparameter_5franges_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
void* ptr = &::flyteidl::plugins::sagemaker::_HyperparameterScalingType_default_instance_;
new (ptr) ::flyteidl::plugins::sagemaker::HyperparameterScalingType();
::google::protobuf::internal::OnShutdownDestroyMessage(ptr);
}
::flyteidl::plugins::sagemaker::HyperparameterScalingType::InitAsDefaultInstance();
}
::google::protobuf::internal::SCCInfo<0> scc_info_HyperparameterScalingType_flyteidl_2fplugins_2fsagemaker_2fparameter_5franges_2eproto =
{{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsHyperparameterScalingType_flyteidl_2fplugins_2fsagemaker_2fparameter_5franges_2eproto}, {}};
static void InitDefaultsContinuousParameterRange_flyteidl_2fplugins_2fsagemaker_2fparameter_5franges_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
void* ptr = &::flyteidl::plugins::sagemaker::_ContinuousParameterRange_default_instance_;
new (ptr) ::flyteidl::plugins::sagemaker::ContinuousParameterRange();
::google::protobuf::internal::OnShutdownDestroyMessage(ptr);
}
::flyteidl::plugins::sagemaker::ContinuousParameterRange::InitAsDefaultInstance();
}
::google::protobuf::internal::SCCInfo<0> scc_info_ContinuousParameterRange_flyteidl_2fplugins_2fsagemaker_2fparameter_5franges_2eproto =
{{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsContinuousParameterRange_flyteidl_2fplugins_2fsagemaker_2fparameter_5franges_2eproto}, {}};
static void InitDefaultsIntegerParameterRange_flyteidl_2fplugins_2fsagemaker_2fparameter_5franges_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
void* ptr = &::flyteidl::plugins::sagemaker::_IntegerParameterRange_default_instance_;
new (ptr) ::flyteidl::plugins::sagemaker::IntegerParameterRange();
::google::protobuf::internal::OnShutdownDestroyMessage(ptr);
}
::flyteidl::plugins::sagemaker::IntegerParameterRange::InitAsDefaultInstance();
}
::google::protobuf::internal::SCCInfo<0> scc_info_IntegerParameterRange_flyteidl_2fplugins_2fsagemaker_2fparameter_5franges_2eproto =
{{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsIntegerParameterRange_flyteidl_2fplugins_2fsagemaker_2fparameter_5franges_2eproto}, {}};
static void InitDefaultsCategoricalParameterRange_flyteidl_2fplugins_2fsagemaker_2fparameter_5franges_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
void* ptr = &::flyteidl::plugins::sagemaker::_CategoricalParameterRange_default_instance_;
new (ptr) ::flyteidl::plugins::sagemaker::CategoricalParameterRange();
::google::protobuf::internal::OnShutdownDestroyMessage(ptr);
}
::flyteidl::plugins::sagemaker::CategoricalParameterRange::InitAsDefaultInstance();
}
::google::protobuf::internal::SCCInfo<0> scc_info_CategoricalParameterRange_flyteidl_2fplugins_2fsagemaker_2fparameter_5franges_2eproto =
{{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsCategoricalParameterRange_flyteidl_2fplugins_2fsagemaker_2fparameter_5franges_2eproto}, {}};
static void InitDefaultsParameterRangeOneOf_flyteidl_2fplugins_2fsagemaker_2fparameter_5franges_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
void* ptr = &::flyteidl::plugins::sagemaker::_ParameterRangeOneOf_default_instance_;
new (ptr) ::flyteidl::plugins::sagemaker::ParameterRangeOneOf();
::google::protobuf::internal::OnShutdownDestroyMessage(ptr);
}
::flyteidl::plugins::sagemaker::ParameterRangeOneOf::InitAsDefaultInstance();
}
::google::protobuf::internal::SCCInfo<3> scc_info_ParameterRangeOneOf_flyteidl_2fplugins_2fsagemaker_2fparameter_5franges_2eproto =
{{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 3, InitDefaultsParameterRangeOneOf_flyteidl_2fplugins_2fsagemaker_2fparameter_5franges_2eproto}, {
&scc_info_ContinuousParameterRange_flyteidl_2fplugins_2fsagemaker_2fparameter_5franges_2eproto.base,
&scc_info_IntegerParameterRange_flyteidl_2fplugins_2fsagemaker_2fparameter_5franges_2eproto.base,
&scc_info_CategoricalParameterRange_flyteidl_2fplugins_2fsagemaker_2fparameter_5franges_2eproto.base,}};
static void InitDefaultsParameterRanges_ParameterRangeMapEntry_DoNotUse_flyteidl_2fplugins_2fsagemaker_2fparameter_5franges_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
void* ptr = &::flyteidl::plugins::sagemaker::_ParameterRanges_ParameterRangeMapEntry_DoNotUse_default_instance_;
new (ptr) ::flyteidl::plugins::sagemaker::ParameterRanges_ParameterRangeMapEntry_DoNotUse();
}
::flyteidl::plugins::sagemaker::ParameterRanges_ParameterRangeMapEntry_DoNotUse::InitAsDefaultInstance();
}
::google::protobuf::internal::SCCInfo<1> scc_info_ParameterRanges_ParameterRangeMapEntry_DoNotUse_flyteidl_2fplugins_2fsagemaker_2fparameter_5franges_2eproto =
{{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsParameterRanges_ParameterRangeMapEntry_DoNotUse_flyteidl_2fplugins_2fsagemaker_2fparameter_5franges_2eproto}, {
&scc_info_ParameterRangeOneOf_flyteidl_2fplugins_2fsagemaker_2fparameter_5franges_2eproto.base,}};
static void InitDefaultsParameterRanges_flyteidl_2fplugins_2fsagemaker_2fparameter_5franges_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
void* ptr = &::flyteidl::plugins::sagemaker::_ParameterRanges_default_instance_;
new (ptr) ::flyteidl::plugins::sagemaker::ParameterRanges();
::google::protobuf::internal::OnShutdownDestroyMessage(ptr);
}
::flyteidl::plugins::sagemaker::ParameterRanges::InitAsDefaultInstance();
}
::google::protobuf::internal::SCCInfo<1> scc_info_ParameterRanges_flyteidl_2fplugins_2fsagemaker_2fparameter_5franges_2eproto =
{{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsParameterRanges_flyteidl_2fplugins_2fsagemaker_2fparameter_5franges_2eproto}, {
&scc_info_ParameterRanges_ParameterRangeMapEntry_DoNotUse_flyteidl_2fplugins_2fsagemaker_2fparameter_5franges_2eproto.base,}};
void InitDefaults_flyteidl_2fplugins_2fsagemaker_2fparameter_5franges_2eproto() {
::google::protobuf::internal::InitSCC(&scc_info_HyperparameterScalingType_flyteidl_2fplugins_2fsagemaker_2fparameter_5franges_2eproto.base);
::google::protobuf::internal::InitSCC(&scc_info_ContinuousParameterRange_flyteidl_2fplugins_2fsagemaker_2fparameter_5franges_2eproto.base);
::google::protobuf::internal::InitSCC(&scc_info_IntegerParameterRange_flyteidl_2fplugins_2fsagemaker_2fparameter_5franges_2eproto.base);
::google::protobuf::internal::InitSCC(&scc_info_CategoricalParameterRange_flyteidl_2fplugins_2fsagemaker_2fparameter_5franges_2eproto.base);
::google::protobuf::internal::InitSCC(&scc_info_ParameterRangeOneOf_flyteidl_2fplugins_2fsagemaker_2fparameter_5franges_2eproto.base);
::google::protobuf::internal::InitSCC(&scc_info_ParameterRanges_ParameterRangeMapEntry_DoNotUse_flyteidl_2fplugins_2fsagemaker_2fparameter_5franges_2eproto.base);
::google::protobuf::internal::InitSCC(&scc_info_ParameterRanges_flyteidl_2fplugins_2fsagemaker_2fparameter_5franges_2eproto.base);
}
::google::protobuf::Metadata file_level_metadata_flyteidl_2fplugins_2fsagemaker_2fparameter_5franges_2eproto[7];
const ::google::protobuf::EnumDescriptor* file_level_enum_descriptors_flyteidl_2fplugins_2fsagemaker_2fparameter_5franges_2eproto[1];
constexpr ::google::protobuf::ServiceDescriptor const** file_level_service_descriptors_flyteidl_2fplugins_2fsagemaker_2fparameter_5franges_2eproto = nullptr;
const ::google::protobuf::uint32 TableStruct_flyteidl_2fplugins_2fsagemaker_2fparameter_5franges_2eproto::offsets[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = {
~0u, // no _has_bits_
PROTOBUF_FIELD_OFFSET(::flyteidl::plugins::sagemaker::HyperparameterScalingType, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
~0u, // no _has_bits_
PROTOBUF_FIELD_OFFSET(::flyteidl::plugins::sagemaker::ContinuousParameterRange, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
PROTOBUF_FIELD_OFFSET(::flyteidl::plugins::sagemaker::ContinuousParameterRange, max_value_),
PROTOBUF_FIELD_OFFSET(::flyteidl::plugins::sagemaker::ContinuousParameterRange, min_value_),
PROTOBUF_FIELD_OFFSET(::flyteidl::plugins::sagemaker::ContinuousParameterRange, scaling_type_),
~0u, // no _has_bits_
PROTOBUF_FIELD_OFFSET(::flyteidl::plugins::sagemaker::IntegerParameterRange, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
PROTOBUF_FIELD_OFFSET(::flyteidl::plugins::sagemaker::IntegerParameterRange, max_value_),
PROTOBUF_FIELD_OFFSET(::flyteidl::plugins::sagemaker::IntegerParameterRange, min_value_),
PROTOBUF_FIELD_OFFSET(::flyteidl::plugins::sagemaker::IntegerParameterRange, scaling_type_),
~0u, // no _has_bits_
PROTOBUF_FIELD_OFFSET(::flyteidl::plugins::sagemaker::CategoricalParameterRange, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
PROTOBUF_FIELD_OFFSET(::flyteidl::plugins::sagemaker::CategoricalParameterRange, values_),
~0u, // no _has_bits_
PROTOBUF_FIELD_OFFSET(::flyteidl::plugins::sagemaker::ParameterRangeOneOf, _internal_metadata_),
~0u, // no _extensions_
PROTOBUF_FIELD_OFFSET(::flyteidl::plugins::sagemaker::ParameterRangeOneOf, _oneof_case_[0]),
~0u, // no _weak_field_map_
offsetof(::flyteidl::plugins::sagemaker::ParameterRangeOneOfDefaultTypeInternal, continuous_parameter_range_),
offsetof(::flyteidl::plugins::sagemaker::ParameterRangeOneOfDefaultTypeInternal, integer_parameter_range_),
offsetof(::flyteidl::plugins::sagemaker::ParameterRangeOneOfDefaultTypeInternal, categorical_parameter_range_),
PROTOBUF_FIELD_OFFSET(::flyteidl::plugins::sagemaker::ParameterRangeOneOf, parameter_range_type_),
PROTOBUF_FIELD_OFFSET(::flyteidl::plugins::sagemaker::ParameterRanges_ParameterRangeMapEntry_DoNotUse, _has_bits_),
PROTOBUF_FIELD_OFFSET(::flyteidl::plugins::sagemaker::ParameterRanges_ParameterRangeMapEntry_DoNotUse, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
PROTOBUF_FIELD_OFFSET(::flyteidl::plugins::sagemaker::ParameterRanges_ParameterRangeMapEntry_DoNotUse, key_),
PROTOBUF_FIELD_OFFSET(::flyteidl::plugins::sagemaker::ParameterRanges_ParameterRangeMapEntry_DoNotUse, value_),
0,
1,
~0u, // no _has_bits_
PROTOBUF_FIELD_OFFSET(::flyteidl::plugins::sagemaker::ParameterRanges, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
PROTOBUF_FIELD_OFFSET(::flyteidl::plugins::sagemaker::ParameterRanges, parameter_range_map_),
};
static const ::google::protobuf::internal::MigrationSchema schemas[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = {
{ 0, -1, sizeof(::flyteidl::plugins::sagemaker::HyperparameterScalingType)},
{ 5, -1, sizeof(::flyteidl::plugins::sagemaker::ContinuousParameterRange)},
{ 13, -1, sizeof(::flyteidl::plugins::sagemaker::IntegerParameterRange)},
{ 21, -1, sizeof(::flyteidl::plugins::sagemaker::CategoricalParameterRange)},
{ 27, -1, sizeof(::flyteidl::plugins::sagemaker::ParameterRangeOneOf)},
{ 36, 43, sizeof(::flyteidl::plugins::sagemaker::ParameterRanges_ParameterRangeMapEntry_DoNotUse)},
{ 45, -1, sizeof(::flyteidl::plugins::sagemaker::ParameterRanges)},
};
static ::google::protobuf::Message const * const file_default_instances[] = {
reinterpret_cast<const ::google::protobuf::Message*>(&::flyteidl::plugins::sagemaker::_HyperparameterScalingType_default_instance_),
reinterpret_cast<const ::google::protobuf::Message*>(&::flyteidl::plugins::sagemaker::_ContinuousParameterRange_default_instance_),
reinterpret_cast<const ::google::protobuf::Message*>(&::flyteidl::plugins::sagemaker::_IntegerParameterRange_default_instance_),
reinterpret_cast<const ::google::protobuf::Message*>(&::flyteidl::plugins::sagemaker::_CategoricalParameterRange_default_instance_),
reinterpret_cast<const ::google::protobuf::Message*>(&::flyteidl::plugins::sagemaker::_ParameterRangeOneOf_default_instance_),
reinterpret_cast<const ::google::protobuf::Message*>(&::flyteidl::plugins::sagemaker::_ParameterRanges_ParameterRangeMapEntry_DoNotUse_default_instance_),
reinterpret_cast<const ::google::protobuf::Message*>(&::flyteidl::plugins::sagemaker::_ParameterRanges_default_instance_),
};
::google::protobuf::internal::AssignDescriptorsTable assign_descriptors_table_flyteidl_2fplugins_2fsagemaker_2fparameter_5franges_2eproto = {
{}, AddDescriptors_flyteidl_2fplugins_2fsagemaker_2fparameter_5franges_2eproto, "flyteidl/plugins/sagemaker/parameter_ranges.proto", schemas,
file_default_instances, TableStruct_flyteidl_2fplugins_2fsagemaker_2fparameter_5franges_2eproto::offsets,
file_level_metadata_flyteidl_2fplugins_2fsagemaker_2fparameter_5franges_2eproto, 7, file_level_enum_descriptors_flyteidl_2fplugins_2fsagemaker_2fparameter_5franges_2eproto, file_level_service_descriptors_flyteidl_2fplugins_2fsagemaker_2fparameter_5franges_2eproto,
};
const char descriptor_table_protodef_flyteidl_2fplugins_2fsagemaker_2fparameter_5franges_2eproto[] =
"\n1flyteidl/plugins/sagemaker/parameter_r"
"anges.proto\022\032flyteidl.plugins.sagemaker\""
"c\n\031HyperparameterScalingType\"F\n\005Value\022\010\n"
"\004AUTO\020\000\022\n\n\006LINEAR\020\001\022\017\n\013LOGARITHMIC\020\002\022\026\n\022"
"REVERSELOGARITHMIC\020\003\"\223\001\n\030ContinuousParam"
"eterRange\022\021\n\tmax_value\030\001 \001(\001\022\021\n\tmin_valu"
"e\030\002 \001(\001\022Q\n\014scaling_type\030\003 \001(\0162;.flyteidl"
".plugins.sagemaker.HyperparameterScaling"
"Type.Value\"\220\001\n\025IntegerParameterRange\022\021\n\t"
"max_value\030\001 \001(\003\022\021\n\tmin_value\030\002 \001(\003\022Q\n\014sc"
"aling_type\030\003 \001(\0162;.flyteidl.plugins.sage"
"maker.HyperparameterScalingType.Value\"+\n"
"\031CategoricalParameterRange\022\016\n\006values\030\001 \003"
"(\t\"\275\002\n\023ParameterRangeOneOf\022Z\n\032continuous"
"_parameter_range\030\001 \001(\01324.flyteidl.plugin"
"s.sagemaker.ContinuousParameterRangeH\000\022T"
"\n\027integer_parameter_range\030\002 \001(\01321.flytei"
"dl.plugins.sagemaker.IntegerParameterRan"
"geH\000\022\\\n\033categorical_parameter_range\030\003 \001("
"\01325.flyteidl.plugins.sagemaker.Categoric"
"alParameterRangeH\000B\026\n\024parameter_range_ty"
"pe\"\335\001\n\017ParameterRanges\022_\n\023parameter_rang"
"e_map\030\001 \003(\0132B.flyteidl.plugins.sagemaker"
".ParameterRanges.ParameterRangeMapEntry\032"
"i\n\026ParameterRangeMapEntry\022\013\n\003key\030\001 \001(\t\022>"
"\n\005value\030\002 \001(\0132/.flyteidl.plugins.sagemak"
"er.ParameterRangeOneOf:\0028\001B5Z3github.com"
"/lyft/flyteidl/gen/pb-go/flyteidl/plugin"
"sb\006proto3"
;
::google::protobuf::internal::DescriptorTable descriptor_table_flyteidl_2fplugins_2fsagemaker_2fparameter_5franges_2eproto = {
false, InitDefaults_flyteidl_2fplugins_2fsagemaker_2fparameter_5franges_2eproto,
descriptor_table_protodef_flyteidl_2fplugins_2fsagemaker_2fparameter_5franges_2eproto,
"flyteidl/plugins/sagemaker/parameter_ranges.proto", &assign_descriptors_table_flyteidl_2fplugins_2fsagemaker_2fparameter_5franges_2eproto, 1129,
};
void AddDescriptors_flyteidl_2fplugins_2fsagemaker_2fparameter_5franges_2eproto() {
static constexpr ::google::protobuf::internal::InitFunc deps[1] =
{
};
::google::protobuf::internal::AddDescriptors(&descriptor_table_flyteidl_2fplugins_2fsagemaker_2fparameter_5franges_2eproto, deps, 0);
}
// Force running AddDescriptors() at dynamic initialization time.
static bool dynamic_init_dummy_flyteidl_2fplugins_2fsagemaker_2fparameter_5franges_2eproto = []() { AddDescriptors_flyteidl_2fplugins_2fsagemaker_2fparameter_5franges_2eproto(); return true; }();
namespace flyteidl {
namespace plugins {
namespace sagemaker {
const ::google::protobuf::EnumDescriptor* HyperparameterScalingType_Value_descriptor() {
::google::protobuf::internal::AssignDescriptors(&assign_descriptors_table_flyteidl_2fplugins_2fsagemaker_2fparameter_5franges_2eproto);
return file_level_enum_descriptors_flyteidl_2fplugins_2fsagemaker_2fparameter_5franges_2eproto[0];
}
bool HyperparameterScalingType_Value_IsValid(int value) {
switch (value) {
case 0:
case 1:
case 2:
case 3:
return true;
default:
return false;
}
}
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const HyperparameterScalingType_Value HyperparameterScalingType::AUTO;
const HyperparameterScalingType_Value HyperparameterScalingType::LINEAR;
const HyperparameterScalingType_Value HyperparameterScalingType::LOGARITHMIC;
const HyperparameterScalingType_Value HyperparameterScalingType::REVERSELOGARITHMIC;
const HyperparameterScalingType_Value HyperparameterScalingType::Value_MIN;
const HyperparameterScalingType_Value HyperparameterScalingType::Value_MAX;
const int HyperparameterScalingType::Value_ARRAYSIZE;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
// ===================================================================
void HyperparameterScalingType::InitAsDefaultInstance() {
}
class HyperparameterScalingType::HasBitSetters {
public:
};
#if !defined(_MSC_VER) || _MSC_VER >= 1900
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
HyperparameterScalingType::HyperparameterScalingType()
: ::google::protobuf::Message(), _internal_metadata_(nullptr) {
SharedCtor();
// @@protoc_insertion_point(constructor:flyteidl.plugins.sagemaker.HyperparameterScalingType)
}
HyperparameterScalingType::HyperparameterScalingType(const HyperparameterScalingType& from)
: ::google::protobuf::Message(),
_internal_metadata_(nullptr) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
// @@protoc_insertion_point(copy_constructor:flyteidl.plugins.sagemaker.HyperparameterScalingType)
}
void HyperparameterScalingType::SharedCtor() {
}
HyperparameterScalingType::~HyperparameterScalingType() {
// @@protoc_insertion_point(destructor:flyteidl.plugins.sagemaker.HyperparameterScalingType)
SharedDtor();
}
void HyperparameterScalingType::SharedDtor() {
}
void HyperparameterScalingType::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
const HyperparameterScalingType& HyperparameterScalingType::default_instance() {
::google::protobuf::internal::InitSCC(&::scc_info_HyperparameterScalingType_flyteidl_2fplugins_2fsagemaker_2fparameter_5franges_2eproto.base);
return *internal_default_instance();
}
void HyperparameterScalingType::Clear() {
// @@protoc_insertion_point(message_clear_start:flyteidl.plugins.sagemaker.HyperparameterScalingType)
::google::protobuf::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
_internal_metadata_.Clear();
}
#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
const char* HyperparameterScalingType::_InternalParse(const char* begin, const char* end, void* object,
::google::protobuf::internal::ParseContext* ctx) {
auto msg = static_cast<HyperparameterScalingType*>(object);
::google::protobuf::int32 size; (void)size;
int depth; (void)depth;
::google::protobuf::uint32 tag;
::google::protobuf::internal::ParseFunc parser_till_end; (void)parser_till_end;
auto ptr = begin;
while (ptr < end) {
ptr = ::google::protobuf::io::Parse32(ptr, &tag);
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
switch (tag >> 3) {
default: {
if ((tag & 7) == 4 || tag == 0) {
ctx->EndGroup(tag);
return ptr;
}
auto res = UnknownFieldParse(tag, {_InternalParse, msg},
ptr, end, msg->_internal_metadata_.mutable_unknown_fields(), ctx);
ptr = res.first;
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr != nullptr);
if (res.second) return ptr;
}
} // switch
} // while
return ptr;
}
#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
bool HyperparameterScalingType::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:flyteidl.plugins.sagemaker.HyperparameterScalingType)
for (;;) {
::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
handle_unusual:
if (tag == 0) {
goto success;
}
DO_(::google::protobuf::internal::WireFormat::SkipField(
input, tag, _internal_metadata_.mutable_unknown_fields()));
}
success:
// @@protoc_insertion_point(parse_success:flyteidl.plugins.sagemaker.HyperparameterScalingType)
return true;
failure:
// @@protoc_insertion_point(parse_failure:flyteidl.plugins.sagemaker.HyperparameterScalingType)
return false;
#undef DO_
}
#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void HyperparameterScalingType::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:flyteidl.plugins.sagemaker.HyperparameterScalingType)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
if (_internal_metadata_.have_unknown_fields()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
_internal_metadata_.unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:flyteidl.plugins.sagemaker.HyperparameterScalingType)
}
::google::protobuf::uint8* HyperparameterScalingType::InternalSerializeWithCachedSizesToArray(
::google::protobuf::uint8* target) const {
// @@protoc_insertion_point(serialize_to_array_start:flyteidl.plugins.sagemaker.HyperparameterScalingType)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
if (_internal_metadata_.have_unknown_fields()) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
_internal_metadata_.unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:flyteidl.plugins.sagemaker.HyperparameterScalingType)
return target;
}
size_t HyperparameterScalingType::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:flyteidl.plugins.sagemaker.HyperparameterScalingType)
size_t total_size = 0;
if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
_internal_metadata_.unknown_fields());
}
::google::protobuf::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
SetCachedSize(cached_size);
return total_size;
}
void HyperparameterScalingType::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:flyteidl.plugins.sagemaker.HyperparameterScalingType)
GOOGLE_DCHECK_NE(&from, this);
const HyperparameterScalingType* source =
::google::protobuf::DynamicCastToGenerated<HyperparameterScalingType>(
&from);
if (source == nullptr) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:flyteidl.plugins.sagemaker.HyperparameterScalingType)
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:flyteidl.plugins.sagemaker.HyperparameterScalingType)
MergeFrom(*source);
}
}
void HyperparameterScalingType::MergeFrom(const HyperparameterScalingType& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:flyteidl.plugins.sagemaker.HyperparameterScalingType)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
}
void HyperparameterScalingType::CopyFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:flyteidl.plugins.sagemaker.HyperparameterScalingType)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void HyperparameterScalingType::CopyFrom(const HyperparameterScalingType& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:flyteidl.plugins.sagemaker.HyperparameterScalingType)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool HyperparameterScalingType::IsInitialized() const {
return true;
}
void HyperparameterScalingType::Swap(HyperparameterScalingType* other) {
if (other == this) return;
InternalSwap(other);
}
void HyperparameterScalingType::InternalSwap(HyperparameterScalingType* other) {
using std::swap;
_internal_metadata_.Swap(&other->_internal_metadata_);
}
::google::protobuf::Metadata HyperparameterScalingType::GetMetadata() const {
::google::protobuf::internal::AssignDescriptors(&::assign_descriptors_table_flyteidl_2fplugins_2fsagemaker_2fparameter_5franges_2eproto);
return ::file_level_metadata_flyteidl_2fplugins_2fsagemaker_2fparameter_5franges_2eproto[kIndexInFileMessages];
}
// ===================================================================
void ContinuousParameterRange::InitAsDefaultInstance() {
}
class ContinuousParameterRange::HasBitSetters {
public:
};
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int ContinuousParameterRange::kMaxValueFieldNumber;
const int ContinuousParameterRange::kMinValueFieldNumber;
const int ContinuousParameterRange::kScalingTypeFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
ContinuousParameterRange::ContinuousParameterRange()
: ::google::protobuf::Message(), _internal_metadata_(nullptr) {
SharedCtor();
// @@protoc_insertion_point(constructor:flyteidl.plugins.sagemaker.ContinuousParameterRange)
}
ContinuousParameterRange::ContinuousParameterRange(const ContinuousParameterRange& from)
: ::google::protobuf::Message(),
_internal_metadata_(nullptr) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
::memcpy(&max_value_, &from.max_value_,
static_cast<size_t>(reinterpret_cast<char*>(&scaling_type_) -
reinterpret_cast<char*>(&max_value_)) + sizeof(scaling_type_));
// @@protoc_insertion_point(copy_constructor:flyteidl.plugins.sagemaker.ContinuousParameterRange)
}
void ContinuousParameterRange::SharedCtor() {
::memset(&max_value_, 0, static_cast<size_t>(
reinterpret_cast<char*>(&scaling_type_) -
reinterpret_cast<char*>(&max_value_)) + sizeof(scaling_type_));
}
ContinuousParameterRange::~ContinuousParameterRange() {
// @@protoc_insertion_point(destructor:flyteidl.plugins.sagemaker.ContinuousParameterRange)
SharedDtor();
}
void ContinuousParameterRange::SharedDtor() {
}
void ContinuousParameterRange::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
const ContinuousParameterRange& ContinuousParameterRange::default_instance() {
::google::protobuf::internal::InitSCC(&::scc_info_ContinuousParameterRange_flyteidl_2fplugins_2fsagemaker_2fparameter_5franges_2eproto.base);
return *internal_default_instance();
}
void ContinuousParameterRange::Clear() {
// @@protoc_insertion_point(message_clear_start:flyteidl.plugins.sagemaker.ContinuousParameterRange)
::google::protobuf::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
::memset(&max_value_, 0, static_cast<size_t>(
reinterpret_cast<char*>(&scaling_type_) -
reinterpret_cast<char*>(&max_value_)) + sizeof(scaling_type_));
_internal_metadata_.Clear();
}
#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
const char* ContinuousParameterRange::_InternalParse(const char* begin, const char* end, void* object,
::google::protobuf::internal::ParseContext* ctx) {
auto msg = static_cast<ContinuousParameterRange*>(object);
::google::protobuf::int32 size; (void)size;
int depth; (void)depth;
::google::protobuf::uint32 tag;
::google::protobuf::internal::ParseFunc parser_till_end; (void)parser_till_end;
auto ptr = begin;
while (ptr < end) {
ptr = ::google::protobuf::io::Parse32(ptr, &tag);
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
switch (tag >> 3) {
// double max_value = 1;
case 1: {
if (static_cast<::google::protobuf::uint8>(tag) != 9) goto handle_unusual;
msg->set_max_value(::google::protobuf::io::UnalignedLoad<double>(ptr));
ptr += sizeof(double);
break;
}
// double min_value = 2;
case 2: {
if (static_cast<::google::protobuf::uint8>(tag) != 17) goto handle_unusual;
msg->set_min_value(::google::protobuf::io::UnalignedLoad<double>(ptr));
ptr += sizeof(double);
break;
}
// .flyteidl.plugins.sagemaker.HyperparameterScalingType.Value scaling_type = 3;
case 3: {
if (static_cast<::google::protobuf::uint8>(tag) != 24) goto handle_unusual;
::google::protobuf::uint64 val = ::google::protobuf::internal::ReadVarint(&ptr);
msg->set_scaling_type(static_cast<::flyteidl::plugins::sagemaker::HyperparameterScalingType_Value>(val));
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
break;
}
default: {
handle_unusual:
if ((tag & 7) == 4 || tag == 0) {
ctx->EndGroup(tag);
return ptr;
}
auto res = UnknownFieldParse(tag, {_InternalParse, msg},
ptr, end, msg->_internal_metadata_.mutable_unknown_fields(), ctx);
ptr = res.first;
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr != nullptr);
if (res.second) return ptr;
}
} // switch
} // while
return ptr;
}
#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
bool ContinuousParameterRange::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:flyteidl.plugins.sagemaker.ContinuousParameterRange)
for (;;) {
::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// double max_value = 1;
case 1: {
if (static_cast< ::google::protobuf::uint8>(tag) == (9 & 0xFF)) {
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>(
input, &max_value_)));
} else {
goto handle_unusual;
}
break;
}
// double min_value = 2;
case 2: {
if (static_cast< ::google::protobuf::uint8>(tag) == (17 & 0xFF)) {
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>(
input, &min_value_)));
} else {
goto handle_unusual;
}
break;
}
// .flyteidl.plugins.sagemaker.HyperparameterScalingType.Value scaling_type = 3;
case 3: {
if (static_cast< ::google::protobuf::uint8>(tag) == (24 & 0xFF)) {
int value = 0;
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>(
input, &value)));
set_scaling_type(static_cast< ::flyteidl::plugins::sagemaker::HyperparameterScalingType_Value >(value));
} else {
goto handle_unusual;
}
break;
}
default: {
handle_unusual:
if (tag == 0) {
goto success;
}
DO_(::google::protobuf::internal::WireFormat::SkipField(
input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:flyteidl.plugins.sagemaker.ContinuousParameterRange)
return true;
failure:
// @@protoc_insertion_point(parse_failure:flyteidl.plugins.sagemaker.ContinuousParameterRange)
return false;
#undef DO_
}
#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void ContinuousParameterRange::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:flyteidl.plugins.sagemaker.ContinuousParameterRange)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// double max_value = 1;
if (this->max_value() != 0) {
::google::protobuf::internal::WireFormatLite::WriteDouble(1, this->max_value(), output);
}
// double min_value = 2;
if (this->min_value() != 0) {
::google::protobuf::internal::WireFormatLite::WriteDouble(2, this->min_value(), output);
}
// .flyteidl.plugins.sagemaker.HyperparameterScalingType.Value scaling_type = 3;
if (this->scaling_type() != 0) {
::google::protobuf::internal::WireFormatLite::WriteEnum(
3, this->scaling_type(), output);
}
if (_internal_metadata_.have_unknown_fields()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
_internal_metadata_.unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:flyteidl.plugins.sagemaker.ContinuousParameterRange)
}
::google::protobuf::uint8* ContinuousParameterRange::InternalSerializeWithCachedSizesToArray(
::google::protobuf::uint8* target) const {
// @@protoc_insertion_point(serialize_to_array_start:flyteidl.plugins.sagemaker.ContinuousParameterRange)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// double max_value = 1;
if (this->max_value() != 0) {
target = ::google::protobuf::internal::WireFormatLite::WriteDoubleToArray(1, this->max_value(), target);
}
// double min_value = 2;
if (this->min_value() != 0) {
target = ::google::protobuf::internal::WireFormatLite::WriteDoubleToArray(2, this->min_value(), target);
}
// .flyteidl.plugins.sagemaker.HyperparameterScalingType.Value scaling_type = 3;
if (this->scaling_type() != 0) {
target = ::google::protobuf::internal::WireFormatLite::WriteEnumToArray(
3, this->scaling_type(), target);
}
if (_internal_metadata_.have_unknown_fields()) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
_internal_metadata_.unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:flyteidl.plugins.sagemaker.ContinuousParameterRange)
return target;
}
size_t ContinuousParameterRange::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:flyteidl.plugins.sagemaker.ContinuousParameterRange)
size_t total_size = 0;
if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
_internal_metadata_.unknown_fields());
}
::google::protobuf::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
// double max_value = 1;
if (this->max_value() != 0) {
total_size += 1 + 8;
}
// double min_value = 2;
if (this->min_value() != 0) {
total_size += 1 + 8;
}
// .flyteidl.plugins.sagemaker.HyperparameterScalingType.Value scaling_type = 3;
if (this->scaling_type() != 0) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::EnumSize(this->scaling_type());
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
SetCachedSize(cached_size);
return total_size;
}
void ContinuousParameterRange::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:flyteidl.plugins.sagemaker.ContinuousParameterRange)
GOOGLE_DCHECK_NE(&from, this);
const ContinuousParameterRange* source =
::google::protobuf::DynamicCastToGenerated<ContinuousParameterRange>(
&from);
if (source == nullptr) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:flyteidl.plugins.sagemaker.ContinuousParameterRange)
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:flyteidl.plugins.sagemaker.ContinuousParameterRange)
MergeFrom(*source);
}
}
void ContinuousParameterRange::MergeFrom(const ContinuousParameterRange& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:flyteidl.plugins.sagemaker.ContinuousParameterRange)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
if (from.max_value() != 0) {
set_max_value(from.max_value());
}
if (from.min_value() != 0) {
set_min_value(from.min_value());
}
if (from.scaling_type() != 0) {
set_scaling_type(from.scaling_type());
}
}
void ContinuousParameterRange::CopyFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:flyteidl.plugins.sagemaker.ContinuousParameterRange)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void ContinuousParameterRange::CopyFrom(const ContinuousParameterRange& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:flyteidl.plugins.sagemaker.ContinuousParameterRange)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool ContinuousParameterRange::IsInitialized() const {
return true;
}
void ContinuousParameterRange::Swap(ContinuousParameterRange* other) {
if (other == this) return;
InternalSwap(other);
}
void ContinuousParameterRange::InternalSwap(ContinuousParameterRange* other) {
using std::swap;
_internal_metadata_.Swap(&other->_internal_metadata_);
swap(max_value_, other->max_value_);
swap(min_value_, other->min_value_);
swap(scaling_type_, other->scaling_type_);
}
::google::protobuf::Metadata ContinuousParameterRange::GetMetadata() const {
::google::protobuf::internal::AssignDescriptors(&::assign_descriptors_table_flyteidl_2fplugins_2fsagemaker_2fparameter_5franges_2eproto);
return ::file_level_metadata_flyteidl_2fplugins_2fsagemaker_2fparameter_5franges_2eproto[kIndexInFileMessages];
}
// ===================================================================
void IntegerParameterRange::InitAsDefaultInstance() {
}
class IntegerParameterRange::HasBitSetters {
public:
};
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int IntegerParameterRange::kMaxValueFieldNumber;
const int IntegerParameterRange::kMinValueFieldNumber;
const int IntegerParameterRange::kScalingTypeFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
IntegerParameterRange::IntegerParameterRange()
: ::google::protobuf::Message(), _internal_metadata_(nullptr) {
SharedCtor();
// @@protoc_insertion_point(constructor:flyteidl.plugins.sagemaker.IntegerParameterRange)
}
IntegerParameterRange::IntegerParameterRange(const IntegerParameterRange& from)
: ::google::protobuf::Message(),
_internal_metadata_(nullptr) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
::memcpy(&max_value_, &from.max_value_,
static_cast<size_t>(reinterpret_cast<char*>(&scaling_type_) -
reinterpret_cast<char*>(&max_value_)) + sizeof(scaling_type_));
// @@protoc_insertion_point(copy_constructor:flyteidl.plugins.sagemaker.IntegerParameterRange)
}
void IntegerParameterRange::SharedCtor() {
::memset(&max_value_, 0, static_cast<size_t>(
reinterpret_cast<char*>(&scaling_type_) -
reinterpret_cast<char*>(&max_value_)) + sizeof(scaling_type_));
}
IntegerParameterRange::~IntegerParameterRange() {
// @@protoc_insertion_point(destructor:flyteidl.plugins.sagemaker.IntegerParameterRange)
SharedDtor();
}
void IntegerParameterRange::SharedDtor() {
}
void IntegerParameterRange::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
const IntegerParameterRange& IntegerParameterRange::default_instance() {
::google::protobuf::internal::InitSCC(&::scc_info_IntegerParameterRange_flyteidl_2fplugins_2fsagemaker_2fparameter_5franges_2eproto.base);
return *internal_default_instance();
}
void IntegerParameterRange::Clear() {
// @@protoc_insertion_point(message_clear_start:flyteidl.plugins.sagemaker.IntegerParameterRange)
::google::protobuf::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
::memset(&max_value_, 0, static_cast<size_t>(
reinterpret_cast<char*>(&scaling_type_) -
reinterpret_cast<char*>(&max_value_)) + sizeof(scaling_type_));
_internal_metadata_.Clear();
}
#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
const char* IntegerParameterRange::_InternalParse(const char* begin, const char* end, void* object,
::google::protobuf::internal::ParseContext* ctx) {
auto msg = static_cast<IntegerParameterRange*>(object);
::google::protobuf::int32 size; (void)size;
int depth; (void)depth;
::google::protobuf::uint32 tag;
::google::protobuf::internal::ParseFunc parser_till_end; (void)parser_till_end;
auto ptr = begin;
while (ptr < end) {
ptr = ::google::protobuf::io::Parse32(ptr, &tag);
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
switch (tag >> 3) {
// int64 max_value = 1;
case 1: {
if (static_cast<::google::protobuf::uint8>(tag) != 8) goto handle_unusual;
msg->set_max_value(::google::protobuf::internal::ReadVarint(&ptr));
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
break;
}
// int64 min_value = 2;
case 2: {
if (static_cast<::google::protobuf::uint8>(tag) != 16) goto handle_unusual;
msg->set_min_value(::google::protobuf::internal::ReadVarint(&ptr));
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
break;
}
// .flyteidl.plugins.sagemaker.HyperparameterScalingType.Value scaling_type = 3;
case 3: {
if (static_cast<::google::protobuf::uint8>(tag) != 24) goto handle_unusual;
::google::protobuf::uint64 val = ::google::protobuf::internal::ReadVarint(&ptr);
msg->set_scaling_type(static_cast<::flyteidl::plugins::sagemaker::HyperparameterScalingType_Value>(val));
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
break;
}
default: {
handle_unusual:
if ((tag & 7) == 4 || tag == 0) {
ctx->EndGroup(tag);
return ptr;
}
auto res = UnknownFieldParse(tag, {_InternalParse, msg},
ptr, end, msg->_internal_metadata_.mutable_unknown_fields(), ctx);
ptr = res.first;
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr != nullptr);
if (res.second) return ptr;
}
} // switch
} // while
return ptr;
}
#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
bool IntegerParameterRange::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:flyteidl.plugins.sagemaker.IntegerParameterRange)
for (;;) {
::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// int64 max_value = 1;
case 1: {
if (static_cast< ::google::protobuf::uint8>(tag) == (8 & 0xFF)) {
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>(
input, &max_value_)));
} else {
goto handle_unusual;
}
break;
}
// int64 min_value = 2;
case 2: {
if (static_cast< ::google::protobuf::uint8>(tag) == (16 & 0xFF)) {
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>(
input, &min_value_)));
} else {
goto handle_unusual;
}
break;
}
// .flyteidl.plugins.sagemaker.HyperparameterScalingType.Value scaling_type = 3;
case 3: {
if (static_cast< ::google::protobuf::uint8>(tag) == (24 & 0xFF)) {
int value = 0;
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>(
input, &value)));
set_scaling_type(static_cast< ::flyteidl::plugins::sagemaker::HyperparameterScalingType_Value >(value));
} else {
goto handle_unusual;
}
break;
}
default: {
handle_unusual:
if (tag == 0) {
goto success;
}
DO_(::google::protobuf::internal::WireFormat::SkipField(
input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:flyteidl.plugins.sagemaker.IntegerParameterRange)
return true;
failure:
// @@protoc_insertion_point(parse_failure:flyteidl.plugins.sagemaker.IntegerParameterRange)
return false;
#undef DO_
}
#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void IntegerParameterRange::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:flyteidl.plugins.sagemaker.IntegerParameterRange)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// int64 max_value = 1;
if (this->max_value() != 0) {
::google::protobuf::internal::WireFormatLite::WriteInt64(1, this->max_value(), output);
}
// int64 min_value = 2;
if (this->min_value() != 0) {
::google::protobuf::internal::WireFormatLite::WriteInt64(2, this->min_value(), output);
}
// .flyteidl.plugins.sagemaker.HyperparameterScalingType.Value scaling_type = 3;
if (this->scaling_type() != 0) {
::google::protobuf::internal::WireFormatLite::WriteEnum(
3, this->scaling_type(), output);
}
if (_internal_metadata_.have_unknown_fields()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
_internal_metadata_.unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:flyteidl.plugins.sagemaker.IntegerParameterRange)
}
::google::protobuf::uint8* IntegerParameterRange::InternalSerializeWithCachedSizesToArray(
::google::protobuf::uint8* target) const {
// @@protoc_insertion_point(serialize_to_array_start:flyteidl.plugins.sagemaker.IntegerParameterRange)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// int64 max_value = 1;
if (this->max_value() != 0) {
target = ::google::protobuf::internal::WireFormatLite::WriteInt64ToArray(1, this->max_value(), target);
}
// int64 min_value = 2;
if (this->min_value() != 0) {
target = ::google::protobuf::internal::WireFormatLite::WriteInt64ToArray(2, this->min_value(), target);
}
// .flyteidl.plugins.sagemaker.HyperparameterScalingType.Value scaling_type = 3;
if (this->scaling_type() != 0) {
target = ::google::protobuf::internal::WireFormatLite::WriteEnumToArray(
3, this->scaling_type(), target);
}
if (_internal_metadata_.have_unknown_fields()) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
_internal_metadata_.unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:flyteidl.plugins.sagemaker.IntegerParameterRange)
return target;
}
size_t IntegerParameterRange::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:flyteidl.plugins.sagemaker.IntegerParameterRange)
size_t total_size = 0;
if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
_internal_metadata_.unknown_fields());
}
::google::protobuf::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
// int64 max_value = 1;
if (this->max_value() != 0) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::Int64Size(
this->max_value());
}
// int64 min_value = 2;
if (this->min_value() != 0) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::Int64Size(
this->min_value());
}
// .flyteidl.plugins.sagemaker.HyperparameterScalingType.Value scaling_type = 3;
if (this->scaling_type() != 0) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::EnumSize(this->scaling_type());
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
SetCachedSize(cached_size);
return total_size;
}
void IntegerParameterRange::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:flyteidl.plugins.sagemaker.IntegerParameterRange)
GOOGLE_DCHECK_NE(&from, this);
const IntegerParameterRange* source =
::google::protobuf::DynamicCastToGenerated<IntegerParameterRange>(
&from);
if (source == nullptr) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:flyteidl.plugins.sagemaker.IntegerParameterRange)
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:flyteidl.plugins.sagemaker.IntegerParameterRange)
MergeFrom(*source);
}
}
void IntegerParameterRange::MergeFrom(const IntegerParameterRange& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:flyteidl.plugins.sagemaker.IntegerParameterRange)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
if (from.max_value() != 0) {
set_max_value(from.max_value());
}
if (from.min_value() != 0) {
set_min_value(from.min_value());
}
if (from.scaling_type() != 0) {
set_scaling_type(from.scaling_type());
}
}
void IntegerParameterRange::CopyFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:flyteidl.plugins.sagemaker.IntegerParameterRange)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void IntegerParameterRange::CopyFrom(const IntegerParameterRange& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:flyteidl.plugins.sagemaker.IntegerParameterRange)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool IntegerParameterRange::IsInitialized() const {
return true;
}
void IntegerParameterRange::Swap(IntegerParameterRange* other) {
if (other == this) return;
InternalSwap(other);
}
void IntegerParameterRange::InternalSwap(IntegerParameterRange* other) {
using std::swap;
_internal_metadata_.Swap(&other->_internal_metadata_);
swap(max_value_, other->max_value_);
swap(min_value_, other->min_value_);
swap(scaling_type_, other->scaling_type_);
}
::google::protobuf::Metadata IntegerParameterRange::GetMetadata() const {
::google::protobuf::internal::AssignDescriptors(&::assign_descriptors_table_flyteidl_2fplugins_2fsagemaker_2fparameter_5franges_2eproto);
return ::file_level_metadata_flyteidl_2fplugins_2fsagemaker_2fparameter_5franges_2eproto[kIndexInFileMessages];
}
// ===================================================================
void CategoricalParameterRange::InitAsDefaultInstance() {
}
class CategoricalParameterRange::HasBitSetters {
public:
};
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int CategoricalParameterRange::kValuesFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
CategoricalParameterRange::CategoricalParameterRange()
: ::google::protobuf::Message(), _internal_metadata_(nullptr) {
SharedCtor();
// @@protoc_insertion_point(constructor:flyteidl.plugins.sagemaker.CategoricalParameterRange)
}
CategoricalParameterRange::CategoricalParameterRange(const CategoricalParameterRange& from)
: ::google::protobuf::Message(),
_internal_metadata_(nullptr),
values_(from.values_) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
// @@protoc_insertion_point(copy_constructor:flyteidl.plugins.sagemaker.CategoricalParameterRange)
}
void CategoricalParameterRange::SharedCtor() {
::google::protobuf::internal::InitSCC(
&scc_info_CategoricalParameterRange_flyteidl_2fplugins_2fsagemaker_2fparameter_5franges_2eproto.base);
}
CategoricalParameterRange::~CategoricalParameterRange() {
// @@protoc_insertion_point(destructor:flyteidl.plugins.sagemaker.CategoricalParameterRange)
SharedDtor();
}
void CategoricalParameterRange::SharedDtor() {
}
void CategoricalParameterRange::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
const CategoricalParameterRange& CategoricalParameterRange::default_instance() {
::google::protobuf::internal::InitSCC(&::scc_info_CategoricalParameterRange_flyteidl_2fplugins_2fsagemaker_2fparameter_5franges_2eproto.base);
return *internal_default_instance();
}
void CategoricalParameterRange::Clear() {
// @@protoc_insertion_point(message_clear_start:flyteidl.plugins.sagemaker.CategoricalParameterRange)
::google::protobuf::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
values_.Clear();
_internal_metadata_.Clear();
}
#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
const char* CategoricalParameterRange::_InternalParse(const char* begin, const char* end, void* object,
::google::protobuf::internal::ParseContext* ctx) {
auto msg = static_cast<CategoricalParameterRange*>(object);
::google::protobuf::int32 size; (void)size;
int depth; (void)depth;
::google::protobuf::uint32 tag;
::google::protobuf::internal::ParseFunc parser_till_end; (void)parser_till_end;
auto ptr = begin;
while (ptr < end) {
ptr = ::google::protobuf::io::Parse32(ptr, &tag);
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
switch (tag >> 3) {
// repeated string values = 1;
case 1: {
if (static_cast<::google::protobuf::uint8>(tag) != 10) goto handle_unusual;
do {
ptr = ::google::protobuf::io::ReadSize(ptr, &size);
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
ctx->extra_parse_data().SetFieldName("flyteidl.plugins.sagemaker.CategoricalParameterRange.values");
object = msg->add_values();
if (size > end - ptr + ::google::protobuf::internal::ParseContext::kSlopBytes) {
parser_till_end = ::google::protobuf::internal::GreedyStringParserUTF8;
goto string_till_end;
}
GOOGLE_PROTOBUF_PARSER_ASSERT(::google::protobuf::internal::StringCheckUTF8(ptr, size, ctx));
::google::protobuf::internal::InlineGreedyStringParser(object, ptr, size, ctx);
ptr += size;
if (ptr >= end) break;
} while ((::google::protobuf::io::UnalignedLoad<::google::protobuf::uint64>(ptr) & 255) == 10 && (ptr += 1));
break;
}
default: {
handle_unusual:
if ((tag & 7) == 4 || tag == 0) {
ctx->EndGroup(tag);
return ptr;
}
auto res = UnknownFieldParse(tag, {_InternalParse, msg},
ptr, end, msg->_internal_metadata_.mutable_unknown_fields(), ctx);
ptr = res.first;
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr != nullptr);
if (res.second) return ptr;
}
} // switch
} // while
return ptr;
string_till_end:
static_cast<::std::string*>(object)->clear();
static_cast<::std::string*>(object)->reserve(size);
goto len_delim_till_end;
len_delim_till_end:
return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg},
{parser_till_end, object}, size);
}
#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
bool CategoricalParameterRange::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:flyteidl.plugins.sagemaker.CategoricalParameterRange)
for (;;) {
::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// repeated string values = 1;
case 1: {
if (static_cast< ::google::protobuf::uint8>(tag) == (10 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->add_values()));
DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->values(this->values_size() - 1).data(),
static_cast<int>(this->values(this->values_size() - 1).length()),
::google::protobuf::internal::WireFormatLite::PARSE,
"flyteidl.plugins.sagemaker.CategoricalParameterRange.values"));
} else {
goto handle_unusual;
}
break;
}
default: {
handle_unusual:
if (tag == 0) {
goto success;
}
DO_(::google::protobuf::internal::WireFormat::SkipField(
input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:flyteidl.plugins.sagemaker.CategoricalParameterRange)
return true;
failure:
// @@protoc_insertion_point(parse_failure:flyteidl.plugins.sagemaker.CategoricalParameterRange)
return false;
#undef DO_
}
#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void CategoricalParameterRange::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:flyteidl.plugins.sagemaker.CategoricalParameterRange)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// repeated string values = 1;
for (int i = 0, n = this->values_size(); i < n; i++) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->values(i).data(), static_cast<int>(this->values(i).length()),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"flyteidl.plugins.sagemaker.CategoricalParameterRange.values");
::google::protobuf::internal::WireFormatLite::WriteString(
1, this->values(i), output);
}
if (_internal_metadata_.have_unknown_fields()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
_internal_metadata_.unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:flyteidl.plugins.sagemaker.CategoricalParameterRange)
}
::google::protobuf::uint8* CategoricalParameterRange::InternalSerializeWithCachedSizesToArray(
::google::protobuf::uint8* target) const {
// @@protoc_insertion_point(serialize_to_array_start:flyteidl.plugins.sagemaker.CategoricalParameterRange)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// repeated string values = 1;
for (int i = 0, n = this->values_size(); i < n; i++) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->values(i).data(), static_cast<int>(this->values(i).length()),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"flyteidl.plugins.sagemaker.CategoricalParameterRange.values");
target = ::google::protobuf::internal::WireFormatLite::
WriteStringToArray(1, this->values(i), target);
}
if (_internal_metadata_.have_unknown_fields()) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
_internal_metadata_.unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:flyteidl.plugins.sagemaker.CategoricalParameterRange)
return target;
}
size_t CategoricalParameterRange::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:flyteidl.plugins.sagemaker.CategoricalParameterRange)
size_t total_size = 0;
if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
_internal_metadata_.unknown_fields());
}
::google::protobuf::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
// repeated string values = 1;
total_size += 1 *
::google::protobuf::internal::FromIntSize(this->values_size());
for (int i = 0, n = this->values_size(); i < n; i++) {
total_size += ::google::protobuf::internal::WireFormatLite::StringSize(
this->values(i));
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
SetCachedSize(cached_size);
return total_size;
}
void CategoricalParameterRange::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:flyteidl.plugins.sagemaker.CategoricalParameterRange)
GOOGLE_DCHECK_NE(&from, this);
const CategoricalParameterRange* source =
::google::protobuf::DynamicCastToGenerated<CategoricalParameterRange>(
&from);
if (source == nullptr) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:flyteidl.plugins.sagemaker.CategoricalParameterRange)
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:flyteidl.plugins.sagemaker.CategoricalParameterRange)
MergeFrom(*source);
}
}
void CategoricalParameterRange::MergeFrom(const CategoricalParameterRange& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:flyteidl.plugins.sagemaker.CategoricalParameterRange)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
values_.MergeFrom(from.values_);
}
void CategoricalParameterRange::CopyFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:flyteidl.plugins.sagemaker.CategoricalParameterRange)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void CategoricalParameterRange::CopyFrom(const CategoricalParameterRange& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:flyteidl.plugins.sagemaker.CategoricalParameterRange)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool CategoricalParameterRange::IsInitialized() const {
return true;
}
void CategoricalParameterRange::Swap(CategoricalParameterRange* other) {
if (other == this) return;
InternalSwap(other);
}
void CategoricalParameterRange::InternalSwap(CategoricalParameterRange* other) {
using std::swap;
_internal_metadata_.Swap(&other->_internal_metadata_);
values_.InternalSwap(CastToBase(&other->values_));
}
::google::protobuf::Metadata CategoricalParameterRange::GetMetadata() const {
::google::protobuf::internal::AssignDescriptors(&::assign_descriptors_table_flyteidl_2fplugins_2fsagemaker_2fparameter_5franges_2eproto);
return ::file_level_metadata_flyteidl_2fplugins_2fsagemaker_2fparameter_5franges_2eproto[kIndexInFileMessages];
}
// ===================================================================
void ParameterRangeOneOf::InitAsDefaultInstance() {
::flyteidl::plugins::sagemaker::_ParameterRangeOneOf_default_instance_.continuous_parameter_range_ = const_cast< ::flyteidl::plugins::sagemaker::ContinuousParameterRange*>(
::flyteidl::plugins::sagemaker::ContinuousParameterRange::internal_default_instance());
::flyteidl::plugins::sagemaker::_ParameterRangeOneOf_default_instance_.integer_parameter_range_ = const_cast< ::flyteidl::plugins::sagemaker::IntegerParameterRange*>(
::flyteidl::plugins::sagemaker::IntegerParameterRange::internal_default_instance());
::flyteidl::plugins::sagemaker::_ParameterRangeOneOf_default_instance_.categorical_parameter_range_ = const_cast< ::flyteidl::plugins::sagemaker::CategoricalParameterRange*>(
::flyteidl::plugins::sagemaker::CategoricalParameterRange::internal_default_instance());
}
class ParameterRangeOneOf::HasBitSetters {
public:
static const ::flyteidl::plugins::sagemaker::ContinuousParameterRange& continuous_parameter_range(const ParameterRangeOneOf* msg);
static const ::flyteidl::plugins::sagemaker::IntegerParameterRange& integer_parameter_range(const ParameterRangeOneOf* msg);
static const ::flyteidl::plugins::sagemaker::CategoricalParameterRange& categorical_parameter_range(const ParameterRangeOneOf* msg);
};
const ::flyteidl::plugins::sagemaker::ContinuousParameterRange&
ParameterRangeOneOf::HasBitSetters::continuous_parameter_range(const ParameterRangeOneOf* msg) {
return *msg->parameter_range_type_.continuous_parameter_range_;
}
const ::flyteidl::plugins::sagemaker::IntegerParameterRange&
ParameterRangeOneOf::HasBitSetters::integer_parameter_range(const ParameterRangeOneOf* msg) {
return *msg->parameter_range_type_.integer_parameter_range_;
}
const ::flyteidl::plugins::sagemaker::CategoricalParameterRange&
ParameterRangeOneOf::HasBitSetters::categorical_parameter_range(const ParameterRangeOneOf* msg) {
return *msg->parameter_range_type_.categorical_parameter_range_;
}
void ParameterRangeOneOf::set_allocated_continuous_parameter_range(::flyteidl::plugins::sagemaker::ContinuousParameterRange* continuous_parameter_range) {
::google::protobuf::Arena* message_arena = GetArenaNoVirtual();
clear_parameter_range_type();
if (continuous_parameter_range) {
::google::protobuf::Arena* submessage_arena = nullptr;
if (message_arena != submessage_arena) {
continuous_parameter_range = ::google::protobuf::internal::GetOwnedMessage(
message_arena, continuous_parameter_range, submessage_arena);
}
set_has_continuous_parameter_range();
parameter_range_type_.continuous_parameter_range_ = continuous_parameter_range;
}
// @@protoc_insertion_point(field_set_allocated:flyteidl.plugins.sagemaker.ParameterRangeOneOf.continuous_parameter_range)
}
void ParameterRangeOneOf::set_allocated_integer_parameter_range(::flyteidl::plugins::sagemaker::IntegerParameterRange* integer_parameter_range) {
::google::protobuf::Arena* message_arena = GetArenaNoVirtual();
clear_parameter_range_type();
if (integer_parameter_range) {
::google::protobuf::Arena* submessage_arena = nullptr;
if (message_arena != submessage_arena) {
integer_parameter_range = ::google::protobuf::internal::GetOwnedMessage(
message_arena, integer_parameter_range, submessage_arena);
}
set_has_integer_parameter_range();
parameter_range_type_.integer_parameter_range_ = integer_parameter_range;
}
// @@protoc_insertion_point(field_set_allocated:flyteidl.plugins.sagemaker.ParameterRangeOneOf.integer_parameter_range)
}
void ParameterRangeOneOf::set_allocated_categorical_parameter_range(::flyteidl::plugins::sagemaker::CategoricalParameterRange* categorical_parameter_range) {
::google::protobuf::Arena* message_arena = GetArenaNoVirtual();
clear_parameter_range_type();
if (categorical_parameter_range) {
::google::protobuf::Arena* submessage_arena = nullptr;
if (message_arena != submessage_arena) {
categorical_parameter_range = ::google::protobuf::internal::GetOwnedMessage(
message_arena, categorical_parameter_range, submessage_arena);
}
set_has_categorical_parameter_range();
parameter_range_type_.categorical_parameter_range_ = categorical_parameter_range;
}
// @@protoc_insertion_point(field_set_allocated:flyteidl.plugins.sagemaker.ParameterRangeOneOf.categorical_parameter_range)
}
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int ParameterRangeOneOf::kContinuousParameterRangeFieldNumber;
const int ParameterRangeOneOf::kIntegerParameterRangeFieldNumber;
const int ParameterRangeOneOf::kCategoricalParameterRangeFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
ParameterRangeOneOf::ParameterRangeOneOf()
: ::google::protobuf::Message(), _internal_metadata_(nullptr) {
SharedCtor();
// @@protoc_insertion_point(constructor:flyteidl.plugins.sagemaker.ParameterRangeOneOf)
}
ParameterRangeOneOf::ParameterRangeOneOf(const ParameterRangeOneOf& from)
: ::google::protobuf::Message(),
_internal_metadata_(nullptr) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
clear_has_parameter_range_type();
switch (from.parameter_range_type_case()) {
case kContinuousParameterRange: {
mutable_continuous_parameter_range()->::flyteidl::plugins::sagemaker::ContinuousParameterRange::MergeFrom(from.continuous_parameter_range());
break;
}
case kIntegerParameterRange: {
mutable_integer_parameter_range()->::flyteidl::plugins::sagemaker::IntegerParameterRange::MergeFrom(from.integer_parameter_range());
break;
}
case kCategoricalParameterRange: {
mutable_categorical_parameter_range()->::flyteidl::plugins::sagemaker::CategoricalParameterRange::MergeFrom(from.categorical_parameter_range());
break;
}
case PARAMETER_RANGE_TYPE_NOT_SET: {
break;
}
}
// @@protoc_insertion_point(copy_constructor:flyteidl.plugins.sagemaker.ParameterRangeOneOf)
}
void ParameterRangeOneOf::SharedCtor() {
::google::protobuf::internal::InitSCC(
&scc_info_ParameterRangeOneOf_flyteidl_2fplugins_2fsagemaker_2fparameter_5franges_2eproto.base);
clear_has_parameter_range_type();
}
ParameterRangeOneOf::~ParameterRangeOneOf() {
// @@protoc_insertion_point(destructor:flyteidl.plugins.sagemaker.ParameterRangeOneOf)
SharedDtor();
}
void ParameterRangeOneOf::SharedDtor() {
if (has_parameter_range_type()) {
clear_parameter_range_type();
}
}
void ParameterRangeOneOf::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
const ParameterRangeOneOf& ParameterRangeOneOf::default_instance() {
::google::protobuf::internal::InitSCC(&::scc_info_ParameterRangeOneOf_flyteidl_2fplugins_2fsagemaker_2fparameter_5franges_2eproto.base);
return *internal_default_instance();
}
void ParameterRangeOneOf::clear_parameter_range_type() {
// @@protoc_insertion_point(one_of_clear_start:flyteidl.plugins.sagemaker.ParameterRangeOneOf)
switch (parameter_range_type_case()) {
case kContinuousParameterRange: {
delete parameter_range_type_.continuous_parameter_range_;
break;
}
case kIntegerParameterRange: {
delete parameter_range_type_.integer_parameter_range_;
break;
}
case kCategoricalParameterRange: {
delete parameter_range_type_.categorical_parameter_range_;
break;
}
case PARAMETER_RANGE_TYPE_NOT_SET: {
break;
}
}
_oneof_case_[0] = PARAMETER_RANGE_TYPE_NOT_SET;
}
void ParameterRangeOneOf::Clear() {
// @@protoc_insertion_point(message_clear_start:flyteidl.plugins.sagemaker.ParameterRangeOneOf)
::google::protobuf::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
clear_parameter_range_type();
_internal_metadata_.Clear();
}
#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
const char* ParameterRangeOneOf::_InternalParse(const char* begin, const char* end, void* object,
::google::protobuf::internal::ParseContext* ctx) {
auto msg = static_cast<ParameterRangeOneOf*>(object);
::google::protobuf::int32 size; (void)size;
int depth; (void)depth;
::google::protobuf::uint32 tag;
::google::protobuf::internal::ParseFunc parser_till_end; (void)parser_till_end;
auto ptr = begin;
while (ptr < end) {
ptr = ::google::protobuf::io::Parse32(ptr, &tag);
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
switch (tag >> 3) {
// .flyteidl.plugins.sagemaker.ContinuousParameterRange continuous_parameter_range = 1;
case 1: {
if (static_cast<::google::protobuf::uint8>(tag) != 10) goto handle_unusual;
ptr = ::google::protobuf::io::ReadSize(ptr, &size);
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
parser_till_end = ::flyteidl::plugins::sagemaker::ContinuousParameterRange::_InternalParse;
object = msg->mutable_continuous_parameter_range();
if (size > end - ptr) goto len_delim_till_end;
ptr += size;
GOOGLE_PROTOBUF_PARSER_ASSERT(ctx->ParseExactRange(
{parser_till_end, object}, ptr - size, ptr));
break;
}
// .flyteidl.plugins.sagemaker.IntegerParameterRange integer_parameter_range = 2;
case 2: {
if (static_cast<::google::protobuf::uint8>(tag) != 18) goto handle_unusual;
ptr = ::google::protobuf::io::ReadSize(ptr, &size);
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
parser_till_end = ::flyteidl::plugins::sagemaker::IntegerParameterRange::_InternalParse;
object = msg->mutable_integer_parameter_range();
if (size > end - ptr) goto len_delim_till_end;
ptr += size;
GOOGLE_PROTOBUF_PARSER_ASSERT(ctx->ParseExactRange(
{parser_till_end, object}, ptr - size, ptr));
break;
}
// .flyteidl.plugins.sagemaker.CategoricalParameterRange categorical_parameter_range = 3;
case 3: {
if (static_cast<::google::protobuf::uint8>(tag) != 26) goto handle_unusual;
ptr = ::google::protobuf::io::ReadSize(ptr, &size);
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
parser_till_end = ::flyteidl::plugins::sagemaker::CategoricalParameterRange::_InternalParse;
object = msg->mutable_categorical_parameter_range();
if (size > end - ptr) goto len_delim_till_end;
ptr += size;
GOOGLE_PROTOBUF_PARSER_ASSERT(ctx->ParseExactRange(
{parser_till_end, object}, ptr - size, ptr));
break;
}
default: {
handle_unusual:
if ((tag & 7) == 4 || tag == 0) {
ctx->EndGroup(tag);
return ptr;
}
auto res = UnknownFieldParse(tag, {_InternalParse, msg},
ptr, end, msg->_internal_metadata_.mutable_unknown_fields(), ctx);
ptr = res.first;
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr != nullptr);
if (res.second) return ptr;
}
} // switch
} // while
return ptr;
len_delim_till_end:
return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg},
{parser_till_end, object}, size);
}
#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
bool ParameterRangeOneOf::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:flyteidl.plugins.sagemaker.ParameterRangeOneOf)
for (;;) {
::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// .flyteidl.plugins.sagemaker.ContinuousParameterRange continuous_parameter_range = 1;
case 1: {
if (static_cast< ::google::protobuf::uint8>(tag) == (10 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
input, mutable_continuous_parameter_range()));
} else {
goto handle_unusual;
}
break;
}
// .flyteidl.plugins.sagemaker.IntegerParameterRange integer_parameter_range = 2;
case 2: {
if (static_cast< ::google::protobuf::uint8>(tag) == (18 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
input, mutable_integer_parameter_range()));
} else {
goto handle_unusual;
}
break;
}
// .flyteidl.plugins.sagemaker.CategoricalParameterRange categorical_parameter_range = 3;
case 3: {
if (static_cast< ::google::protobuf::uint8>(tag) == (26 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
input, mutable_categorical_parameter_range()));
} else {
goto handle_unusual;
}
break;
}
default: {
handle_unusual:
if (tag == 0) {
goto success;
}
DO_(::google::protobuf::internal::WireFormat::SkipField(
input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:flyteidl.plugins.sagemaker.ParameterRangeOneOf)
return true;
failure:
// @@protoc_insertion_point(parse_failure:flyteidl.plugins.sagemaker.ParameterRangeOneOf)
return false;
#undef DO_
}
#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void ParameterRangeOneOf::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:flyteidl.plugins.sagemaker.ParameterRangeOneOf)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// .flyteidl.plugins.sagemaker.ContinuousParameterRange continuous_parameter_range = 1;
if (has_continuous_parameter_range()) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
1, HasBitSetters::continuous_parameter_range(this), output);
}
// .flyteidl.plugins.sagemaker.IntegerParameterRange integer_parameter_range = 2;
if (has_integer_parameter_range()) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
2, HasBitSetters::integer_parameter_range(this), output);
}
// .flyteidl.plugins.sagemaker.CategoricalParameterRange categorical_parameter_range = 3;
if (has_categorical_parameter_range()) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
3, HasBitSetters::categorical_parameter_range(this), output);
}
if (_internal_metadata_.have_unknown_fields()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
_internal_metadata_.unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:flyteidl.plugins.sagemaker.ParameterRangeOneOf)
}
::google::protobuf::uint8* ParameterRangeOneOf::InternalSerializeWithCachedSizesToArray(
::google::protobuf::uint8* target) const {
// @@protoc_insertion_point(serialize_to_array_start:flyteidl.plugins.sagemaker.ParameterRangeOneOf)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// .flyteidl.plugins.sagemaker.ContinuousParameterRange continuous_parameter_range = 1;
if (has_continuous_parameter_range()) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageToArray(
1, HasBitSetters::continuous_parameter_range(this), target);
}
// .flyteidl.plugins.sagemaker.IntegerParameterRange integer_parameter_range = 2;
if (has_integer_parameter_range()) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageToArray(
2, HasBitSetters::integer_parameter_range(this), target);
}
// .flyteidl.plugins.sagemaker.CategoricalParameterRange categorical_parameter_range = 3;
if (has_categorical_parameter_range()) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageToArray(
3, HasBitSetters::categorical_parameter_range(this), target);
}
if (_internal_metadata_.have_unknown_fields()) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
_internal_metadata_.unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:flyteidl.plugins.sagemaker.ParameterRangeOneOf)
return target;
}
size_t ParameterRangeOneOf::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:flyteidl.plugins.sagemaker.ParameterRangeOneOf)
size_t total_size = 0;
if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
_internal_metadata_.unknown_fields());
}
::google::protobuf::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
switch (parameter_range_type_case()) {
// .flyteidl.plugins.sagemaker.ContinuousParameterRange continuous_parameter_range = 1;
case kContinuousParameterRange: {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::MessageSize(
*parameter_range_type_.continuous_parameter_range_);
break;
}
// .flyteidl.plugins.sagemaker.IntegerParameterRange integer_parameter_range = 2;
case kIntegerParameterRange: {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::MessageSize(
*parameter_range_type_.integer_parameter_range_);
break;
}
// .flyteidl.plugins.sagemaker.CategoricalParameterRange categorical_parameter_range = 3;
case kCategoricalParameterRange: {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::MessageSize(
*parameter_range_type_.categorical_parameter_range_);
break;
}
case PARAMETER_RANGE_TYPE_NOT_SET: {
break;
}
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
SetCachedSize(cached_size);
return total_size;
}
void ParameterRangeOneOf::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:flyteidl.plugins.sagemaker.ParameterRangeOneOf)
GOOGLE_DCHECK_NE(&from, this);
const ParameterRangeOneOf* source =
::google::protobuf::DynamicCastToGenerated<ParameterRangeOneOf>(
&from);
if (source == nullptr) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:flyteidl.plugins.sagemaker.ParameterRangeOneOf)
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:flyteidl.plugins.sagemaker.ParameterRangeOneOf)
MergeFrom(*source);
}
}
void ParameterRangeOneOf::MergeFrom(const ParameterRangeOneOf& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:flyteidl.plugins.sagemaker.ParameterRangeOneOf)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
switch (from.parameter_range_type_case()) {
case kContinuousParameterRange: {
mutable_continuous_parameter_range()->::flyteidl::plugins::sagemaker::ContinuousParameterRange::MergeFrom(from.continuous_parameter_range());
break;
}
case kIntegerParameterRange: {
mutable_integer_parameter_range()->::flyteidl::plugins::sagemaker::IntegerParameterRange::MergeFrom(from.integer_parameter_range());
break;
}
case kCategoricalParameterRange: {
mutable_categorical_parameter_range()->::flyteidl::plugins::sagemaker::CategoricalParameterRange::MergeFrom(from.categorical_parameter_range());
break;
}
case PARAMETER_RANGE_TYPE_NOT_SET: {
break;
}
}
}
void ParameterRangeOneOf::CopyFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:flyteidl.plugins.sagemaker.ParameterRangeOneOf)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void ParameterRangeOneOf::CopyFrom(const ParameterRangeOneOf& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:flyteidl.plugins.sagemaker.ParameterRangeOneOf)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool ParameterRangeOneOf::IsInitialized() const {
return true;
}
void ParameterRangeOneOf::Swap(ParameterRangeOneOf* other) {
if (other == this) return;
InternalSwap(other);
}
void ParameterRangeOneOf::InternalSwap(ParameterRangeOneOf* other) {
using std::swap;
_internal_metadata_.Swap(&other->_internal_metadata_);
swap(parameter_range_type_, other->parameter_range_type_);
swap(_oneof_case_[0], other->_oneof_case_[0]);
}
::google::protobuf::Metadata ParameterRangeOneOf::GetMetadata() const {
::google::protobuf::internal::AssignDescriptors(&::assign_descriptors_table_flyteidl_2fplugins_2fsagemaker_2fparameter_5franges_2eproto);
return ::file_level_metadata_flyteidl_2fplugins_2fsagemaker_2fparameter_5franges_2eproto[kIndexInFileMessages];
}
// ===================================================================
ParameterRanges_ParameterRangeMapEntry_DoNotUse::ParameterRanges_ParameterRangeMapEntry_DoNotUse() {}
ParameterRanges_ParameterRangeMapEntry_DoNotUse::ParameterRanges_ParameterRangeMapEntry_DoNotUse(::google::protobuf::Arena* arena)
: SuperType(arena) {}
void ParameterRanges_ParameterRangeMapEntry_DoNotUse::MergeFrom(const ParameterRanges_ParameterRangeMapEntry_DoNotUse& other) {
MergeFromInternal(other);
}
::google::protobuf::Metadata ParameterRanges_ParameterRangeMapEntry_DoNotUse::GetMetadata() const {
::google::protobuf::internal::AssignDescriptors(&::assign_descriptors_table_flyteidl_2fplugins_2fsagemaker_2fparameter_5franges_2eproto);
return ::file_level_metadata_flyteidl_2fplugins_2fsagemaker_2fparameter_5franges_2eproto[5];
}
void ParameterRanges_ParameterRangeMapEntry_DoNotUse::MergeFrom(
const ::google::protobuf::Message& other) {
::google::protobuf::Message::MergeFrom(other);
}
#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
bool ParameterRanges_ParameterRangeMapEntry_DoNotUse::_ParseMap(const char* begin, const char* end, void* object, ::google::protobuf::internal::ParseContext* ctx) {
using MF = ::google::protobuf::internal::MapField<
ParameterRanges_ParameterRangeMapEntry_DoNotUse, EntryKeyType, EntryValueType,
kEntryKeyFieldType, kEntryValueFieldType,
kEntryDefaultEnumValue>;
auto mf = static_cast<MF*>(object);
Parser<MF, ::google::protobuf::Map<EntryKeyType, EntryValueType>> parser(mf);
#define DO_(x) if (!(x)) return false
DO_(parser.ParseMap(begin, end));
DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
parser.key().data(), static_cast<int>(parser.key().length()),
::google::protobuf::internal::WireFormatLite::PARSE,
"flyteidl.plugins.sagemaker.ParameterRanges.ParameterRangeMapEntry.key"));
#undef DO_
return true;
}
#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
// ===================================================================
void ParameterRanges::InitAsDefaultInstance() {
}
class ParameterRanges::HasBitSetters {
public:
};
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int ParameterRanges::kParameterRangeMapFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
ParameterRanges::ParameterRanges()
: ::google::protobuf::Message(), _internal_metadata_(nullptr) {
SharedCtor();
// @@protoc_insertion_point(constructor:flyteidl.plugins.sagemaker.ParameterRanges)
}
ParameterRanges::ParameterRanges(const ParameterRanges& from)
: ::google::protobuf::Message(),
_internal_metadata_(nullptr) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
parameter_range_map_.MergeFrom(from.parameter_range_map_);
// @@protoc_insertion_point(copy_constructor:flyteidl.plugins.sagemaker.ParameterRanges)
}
void ParameterRanges::SharedCtor() {
::google::protobuf::internal::InitSCC(
&scc_info_ParameterRanges_flyteidl_2fplugins_2fsagemaker_2fparameter_5franges_2eproto.base);
}
ParameterRanges::~ParameterRanges() {
// @@protoc_insertion_point(destructor:flyteidl.plugins.sagemaker.ParameterRanges)
SharedDtor();
}
void ParameterRanges::SharedDtor() {
}
void ParameterRanges::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
const ParameterRanges& ParameterRanges::default_instance() {
::google::protobuf::internal::InitSCC(&::scc_info_ParameterRanges_flyteidl_2fplugins_2fsagemaker_2fparameter_5franges_2eproto.base);
return *internal_default_instance();
}
void ParameterRanges::Clear() {
// @@protoc_insertion_point(message_clear_start:flyteidl.plugins.sagemaker.ParameterRanges)
::google::protobuf::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
parameter_range_map_.Clear();
_internal_metadata_.Clear();
}
#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
const char* ParameterRanges::_InternalParse(const char* begin, const char* end, void* object,
::google::protobuf::internal::ParseContext* ctx) {
auto msg = static_cast<ParameterRanges*>(object);
::google::protobuf::int32 size; (void)size;
int depth; (void)depth;
::google::protobuf::uint32 tag;
::google::protobuf::internal::ParseFunc parser_till_end; (void)parser_till_end;
auto ptr = begin;
while (ptr < end) {
ptr = ::google::protobuf::io::Parse32(ptr, &tag);
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
switch (tag >> 3) {
// map<string, .flyteidl.plugins.sagemaker.ParameterRangeOneOf> parameter_range_map = 1;
case 1: {
if (static_cast<::google::protobuf::uint8>(tag) != 10) goto handle_unusual;
do {
ptr = ::google::protobuf::io::ReadSize(ptr, &size);
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
parser_till_end = ::google::protobuf::internal::SlowMapEntryParser;
auto parse_map = ::flyteidl::plugins::sagemaker::ParameterRanges_ParameterRangeMapEntry_DoNotUse::_ParseMap;
ctx->extra_parse_data().payload.clear();
ctx->extra_parse_data().parse_map = parse_map;
object = &msg->parameter_range_map_;
if (size > end - ptr) goto len_delim_till_end;
auto newend = ptr + size;
GOOGLE_PROTOBUF_PARSER_ASSERT(parse_map(ptr, newend, object, ctx));
ptr = newend;
if (ptr >= end) break;
} while ((::google::protobuf::io::UnalignedLoad<::google::protobuf::uint64>(ptr) & 255) == 10 && (ptr += 1));
break;
}
default: {
handle_unusual:
if ((tag & 7) == 4 || tag == 0) {
ctx->EndGroup(tag);
return ptr;
}
auto res = UnknownFieldParse(tag, {_InternalParse, msg},
ptr, end, msg->_internal_metadata_.mutable_unknown_fields(), ctx);
ptr = res.first;
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr != nullptr);
if (res.second) return ptr;
}
} // switch
} // while
return ptr;
len_delim_till_end:
return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg},
{parser_till_end, object}, size);
}
#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
bool ParameterRanges::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:flyteidl.plugins.sagemaker.ParameterRanges)
for (;;) {
::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// map<string, .flyteidl.plugins.sagemaker.ParameterRangeOneOf> parameter_range_map = 1;
case 1: {
if (static_cast< ::google::protobuf::uint8>(tag) == (10 & 0xFF)) {
ParameterRanges_ParameterRangeMapEntry_DoNotUse::Parser< ::google::protobuf::internal::MapField<
ParameterRanges_ParameterRangeMapEntry_DoNotUse,
::std::string, ::flyteidl::plugins::sagemaker::ParameterRangeOneOf,
::google::protobuf::internal::WireFormatLite::TYPE_STRING,
::google::protobuf::internal::WireFormatLite::TYPE_MESSAGE,
0 >,
::google::protobuf::Map< ::std::string, ::flyteidl::plugins::sagemaker::ParameterRangeOneOf > > parser(¶meter_range_map_);
DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(
input, &parser));
DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
parser.key().data(), static_cast<int>(parser.key().length()),
::google::protobuf::internal::WireFormatLite::PARSE,
"flyteidl.plugins.sagemaker.ParameterRanges.ParameterRangeMapEntry.key"));
} else {
goto handle_unusual;
}
break;
}
default: {
handle_unusual:
if (tag == 0) {
goto success;
}
DO_(::google::protobuf::internal::WireFormat::SkipField(
input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:flyteidl.plugins.sagemaker.ParameterRanges)
return true;
failure:
// @@protoc_insertion_point(parse_failure:flyteidl.plugins.sagemaker.ParameterRanges)
return false;
#undef DO_
}
#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void ParameterRanges::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:flyteidl.plugins.sagemaker.ParameterRanges)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// map<string, .flyteidl.plugins.sagemaker.ParameterRangeOneOf> parameter_range_map = 1;
if (!this->parameter_range_map().empty()) {
typedef ::google::protobuf::Map< ::std::string, ::flyteidl::plugins::sagemaker::ParameterRangeOneOf >::const_pointer
ConstPtr;
typedef ConstPtr SortItem;
typedef ::google::protobuf::internal::CompareByDerefFirst<SortItem> Less;
struct Utf8Check {
static void Check(ConstPtr p) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
p->first.data(), static_cast<int>(p->first.length()),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"flyteidl.plugins.sagemaker.ParameterRanges.ParameterRangeMapEntry.key");
}
};
if (output->IsSerializationDeterministic() &&
this->parameter_range_map().size() > 1) {
::std::unique_ptr<SortItem[]> items(
new SortItem[this->parameter_range_map().size()]);
typedef ::google::protobuf::Map< ::std::string, ::flyteidl::plugins::sagemaker::ParameterRangeOneOf >::size_type size_type;
size_type n = 0;
for (::google::protobuf::Map< ::std::string, ::flyteidl::plugins::sagemaker::ParameterRangeOneOf >::const_iterator
it = this->parameter_range_map().begin();
it != this->parameter_range_map().end(); ++it, ++n) {
items[static_cast<ptrdiff_t>(n)] = SortItem(&*it);
}
::std::sort(&items[0], &items[static_cast<ptrdiff_t>(n)], Less());
::std::unique_ptr<ParameterRanges_ParameterRangeMapEntry_DoNotUse> entry;
for (size_type i = 0; i < n; i++) {
entry.reset(parameter_range_map_.NewEntryWrapper(items[static_cast<ptrdiff_t>(i)]->first, items[static_cast<ptrdiff_t>(i)]->second));
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(1, *entry, output);
Utf8Check::Check(&(*items[static_cast<ptrdiff_t>(i)]));
}
} else {
::std::unique_ptr<ParameterRanges_ParameterRangeMapEntry_DoNotUse> entry;
for (::google::protobuf::Map< ::std::string, ::flyteidl::plugins::sagemaker::ParameterRangeOneOf >::const_iterator
it = this->parameter_range_map().begin();
it != this->parameter_range_map().end(); ++it) {
entry.reset(parameter_range_map_.NewEntryWrapper(it->first, it->second));
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(1, *entry, output);
Utf8Check::Check(&(*it));
}
}
}
if (_internal_metadata_.have_unknown_fields()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
_internal_metadata_.unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:flyteidl.plugins.sagemaker.ParameterRanges)
}
::google::protobuf::uint8* ParameterRanges::InternalSerializeWithCachedSizesToArray(
::google::protobuf::uint8* target) const {
// @@protoc_insertion_point(serialize_to_array_start:flyteidl.plugins.sagemaker.ParameterRanges)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// map<string, .flyteidl.plugins.sagemaker.ParameterRangeOneOf> parameter_range_map = 1;
if (!this->parameter_range_map().empty()) {
typedef ::google::protobuf::Map< ::std::string, ::flyteidl::plugins::sagemaker::ParameterRangeOneOf >::const_pointer
ConstPtr;
typedef ConstPtr SortItem;
typedef ::google::protobuf::internal::CompareByDerefFirst<SortItem> Less;
struct Utf8Check {
static void Check(ConstPtr p) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
p->first.data(), static_cast<int>(p->first.length()),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"flyteidl.plugins.sagemaker.ParameterRanges.ParameterRangeMapEntry.key");
}
};
if (false &&
this->parameter_range_map().size() > 1) {
::std::unique_ptr<SortItem[]> items(
new SortItem[this->parameter_range_map().size()]);
typedef ::google::protobuf::Map< ::std::string, ::flyteidl::plugins::sagemaker::ParameterRangeOneOf >::size_type size_type;
size_type n = 0;
for (::google::protobuf::Map< ::std::string, ::flyteidl::plugins::sagemaker::ParameterRangeOneOf >::const_iterator
it = this->parameter_range_map().begin();
it != this->parameter_range_map().end(); ++it, ++n) {
items[static_cast<ptrdiff_t>(n)] = SortItem(&*it);
}
::std::sort(&items[0], &items[static_cast<ptrdiff_t>(n)], Less());
::std::unique_ptr<ParameterRanges_ParameterRangeMapEntry_DoNotUse> entry;
for (size_type i = 0; i < n; i++) {
entry.reset(parameter_range_map_.NewEntryWrapper(items[static_cast<ptrdiff_t>(i)]->first, items[static_cast<ptrdiff_t>(i)]->second));
target = ::google::protobuf::internal::WireFormatLite::InternalWriteMessageNoVirtualToArray(1, *entry, target);
Utf8Check::Check(&(*items[static_cast<ptrdiff_t>(i)]));
}
} else {
::std::unique_ptr<ParameterRanges_ParameterRangeMapEntry_DoNotUse> entry;
for (::google::protobuf::Map< ::std::string, ::flyteidl::plugins::sagemaker::ParameterRangeOneOf >::const_iterator
it = this->parameter_range_map().begin();
it != this->parameter_range_map().end(); ++it) {
entry.reset(parameter_range_map_.NewEntryWrapper(it->first, it->second));
target = ::google::protobuf::internal::WireFormatLite::InternalWriteMessageNoVirtualToArray(1, *entry, target);
Utf8Check::Check(&(*it));
}
}
}
if (_internal_metadata_.have_unknown_fields()) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
_internal_metadata_.unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:flyteidl.plugins.sagemaker.ParameterRanges)
return target;
}
size_t ParameterRanges::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:flyteidl.plugins.sagemaker.ParameterRanges)
size_t total_size = 0;
if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
_internal_metadata_.unknown_fields());
}
::google::protobuf::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
// map<string, .flyteidl.plugins.sagemaker.ParameterRangeOneOf> parameter_range_map = 1;
total_size += 1 *
::google::protobuf::internal::FromIntSize(this->parameter_range_map_size());
{
::std::unique_ptr<ParameterRanges_ParameterRangeMapEntry_DoNotUse> entry;
for (::google::protobuf::Map< ::std::string, ::flyteidl::plugins::sagemaker::ParameterRangeOneOf >::const_iterator
it = this->parameter_range_map().begin();
it != this->parameter_range_map().end(); ++it) {
entry.reset(parameter_range_map_.NewEntryWrapper(it->first, it->second));
total_size += ::google::protobuf::internal::WireFormatLite::
MessageSizeNoVirtual(*entry);
}
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
SetCachedSize(cached_size);
return total_size;
}
void ParameterRanges::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:flyteidl.plugins.sagemaker.ParameterRanges)
GOOGLE_DCHECK_NE(&from, this);
const ParameterRanges* source =
::google::protobuf::DynamicCastToGenerated<ParameterRanges>(
&from);
if (source == nullptr) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:flyteidl.plugins.sagemaker.ParameterRanges)
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:flyteidl.plugins.sagemaker.ParameterRanges)
MergeFrom(*source);
}
}
void ParameterRanges::MergeFrom(const ParameterRanges& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:flyteidl.plugins.sagemaker.ParameterRanges)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
parameter_range_map_.MergeFrom(from.parameter_range_map_);
}
void ParameterRanges::CopyFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:flyteidl.plugins.sagemaker.ParameterRanges)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void ParameterRanges::CopyFrom(const ParameterRanges& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:flyteidl.plugins.sagemaker.ParameterRanges)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool ParameterRanges::IsInitialized() const {
return true;
}
void ParameterRanges::Swap(ParameterRanges* other) {
if (other == this) return;
InternalSwap(other);
}
void ParameterRanges::InternalSwap(ParameterRanges* other) {
using std::swap;
_internal_metadata_.Swap(&other->_internal_metadata_);
parameter_range_map_.Swap(&other->parameter_range_map_);
}
::google::protobuf::Metadata ParameterRanges::GetMetadata() const {
::google::protobuf::internal::AssignDescriptors(&::assign_descriptors_table_flyteidl_2fplugins_2fsagemaker_2fparameter_5franges_2eproto);
return ::file_level_metadata_flyteidl_2fplugins_2fsagemaker_2fparameter_5franges_2eproto[kIndexInFileMessages];
}
// @@protoc_insertion_point(namespace_scope)
} // namespace sagemaker
} // namespace plugins
} // namespace flyteidl
namespace google {
namespace protobuf {
template<> PROTOBUF_NOINLINE ::flyteidl::plugins::sagemaker::HyperparameterScalingType* Arena::CreateMaybeMessage< ::flyteidl::plugins::sagemaker::HyperparameterScalingType >(Arena* arena) {
return Arena::CreateInternal< ::flyteidl::plugins::sagemaker::HyperparameterScalingType >(arena);
}
template<> PROTOBUF_NOINLINE ::flyteidl::plugins::sagemaker::ContinuousParameterRange* Arena::CreateMaybeMessage< ::flyteidl::plugins::sagemaker::ContinuousParameterRange >(Arena* arena) {
return Arena::CreateInternal< ::flyteidl::plugins::sagemaker::ContinuousParameterRange >(arena);
}
template<> PROTOBUF_NOINLINE ::flyteidl::plugins::sagemaker::IntegerParameterRange* Arena::CreateMaybeMessage< ::flyteidl::plugins::sagemaker::IntegerParameterRange >(Arena* arena) {
return Arena::CreateInternal< ::flyteidl::plugins::sagemaker::IntegerParameterRange >(arena);
}
template<> PROTOBUF_NOINLINE ::flyteidl::plugins::sagemaker::CategoricalParameterRange* Arena::CreateMaybeMessage< ::flyteidl::plugins::sagemaker::CategoricalParameterRange >(Arena* arena) {
return Arena::CreateInternal< ::flyteidl::plugins::sagemaker::CategoricalParameterRange >(arena);
}
template<> PROTOBUF_NOINLINE ::flyteidl::plugins::sagemaker::ParameterRangeOneOf* Arena::CreateMaybeMessage< ::flyteidl::plugins::sagemaker::ParameterRangeOneOf >(Arena* arena) {
return Arena::CreateInternal< ::flyteidl::plugins::sagemaker::ParameterRangeOneOf >(arena);
}
template<> PROTOBUF_NOINLINE ::flyteidl::plugins::sagemaker::ParameterRanges_ParameterRangeMapEntry_DoNotUse* Arena::CreateMaybeMessage< ::flyteidl::plugins::sagemaker::ParameterRanges_ParameterRangeMapEntry_DoNotUse >(Arena* arena) {
return Arena::CreateInternal< ::flyteidl::plugins::sagemaker::ParameterRanges_ParameterRangeMapEntry_DoNotUse >(arena);
}
template<> PROTOBUF_NOINLINE ::flyteidl::plugins::sagemaker::ParameterRanges* Arena::CreateMaybeMessage< ::flyteidl::plugins::sagemaker::ParameterRanges >(Arena* arena) {
return Arena::CreateInternal< ::flyteidl::plugins::sagemaker::ParameterRanges >(arena);
}
} // namespace protobuf
} // namespace google
// @@protoc_insertion_point(global_scope)
#include <google/protobuf/port_undef.inc>
| 44.329134 | 266 | 0.7461 | [
"object"
] |
ee37ea1591cc141566a35054de297a0b8ebcaecc | 1,627 | hpp | C++ | dependence/fc/include/fc/network/http/server.hpp | tiaotiao00/HSR00qianbao | a88afebeb98e786389f369447bcf9c3a2a352cfa | [
"MIT"
] | 66 | 2017-09-29T07:09:59.000Z | 2020-01-12T06:45:08.000Z | dependence/fc/include/fc/network/http/server.hpp | tiaotiao00/HSR00qianbao | a88afebeb98e786389f369447bcf9c3a2a352cfa | [
"MIT"
] | 5 | 2017-12-13T13:12:05.000Z | 2018-01-18T10:34:02.000Z | dependence/fc/include/fc/network/http/server.hpp | tiaotiao00/HSR00qianbao | a88afebeb98e786389f369447bcf9c3a2a352cfa | [
"MIT"
] | 11 | 2017-12-05T07:02:05.000Z | 2018-01-28T02:52:50.000Z | #pragma once
#include <fc/network/http/connection.hpp>
#include <fc/shared_ptr.hpp>
#include <functional>
#include <memory>
namespace fc { namespace http {
/**
* Listens on a given port for incomming http
* connections and then calls a user provided callback
* function for every http request.
*
*/
class server
{
public:
server();
server( uint16_t port );
server( server&& s );
~server();
server& operator=(server&& s);
class response
{
public:
class impl;
response();
response( const fc::shared_ptr<impl>& my);
response( const response& r);
response( response&& r );
~response();
response& operator=(const response& );
response& operator=( response&& );
void add_header( const fc::string& key, const fc::string& val )const;
void set_status( const http::reply::status_code& s )const;
void set_length( uint64_t s )const;
void write( const char* data, uint64_t len )const;
private:
fc::shared_ptr<impl> my;
};
void listen( const fc::ip::endpoint& p, std::vector<std::string>allow_ips = std::vector<std::string>());
fc::ip::endpoint get_local_endpoint() const;
/**
* Set the callback to be called for every http request made.
*/
void on_request( const std::function<void(const http::request&, const server::response& s )>& cb );
private:
class impl;
std::unique_ptr<impl> my;
};
typedef std::shared_ptr<server> server_ptr;
} }
| 25.030769 | 110 | 0.588814 | [
"vector"
] |
ee3be4eb0ca7b5b7b8e62a4f47bbc69e07e3cb8f | 33,094 | cpp | C++ | test/timeparser/EnTimeParser.cpp | CuSO4Gem/jrm | 8ad1e5c785b193cd917e08d55f3edb068e007304 | [
"Apache-2.0"
] | null | null | null | test/timeparser/EnTimeParser.cpp | CuSO4Gem/jrm | 8ad1e5c785b193cd917e08d55f3edb068e007304 | [
"Apache-2.0"
] | null | null | null | test/timeparser/EnTimeParser.cpp | CuSO4Gem/jrm | 8ad1e5c785b193cd917e08d55f3edb068e007304 | [
"Apache-2.0"
] | null | null | null | /*
Copyright 2022 Zorn Link
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 <algorithm>
#include <regex>
#include <list>
#include <stdio.h>
#include <time.h>
#include "date.h"
#include "EnTimeParser.h"
using namespace ec;
using namespace std;
#define ALL_SHORT_MONTH_REGEX "(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)"
char monthShortName[][4] = {
"jan",
"feb",
"mar",
"apr",
"may",
"jun",
"jul",
"aug",
"sep",
"oct",
"nov",
"dec"
};
char weekShortName[][4] = {
"mon",
"the",
"wed",
"thu",
"fir",
"sat",
"sun"
};
typedef struct vmInst {
char cmd[2];
bool haveNumber;
int32_t number;
} vmInst_t;
constexpr int32_t TWOCC(const char *s)
{
return (unsigned char)*(s)|
(unsigned char)*(s+1)<<8;
}
inline bool isNumChar(const char ch)
{
return '0'<=ch && ch<='9';
}
inline bool isLetter(const char ch)
{
return ('a'<=ch && ch<='z') || ('A'<=ch && ch<='Z');
}
inline bool isLetterOnly(const string &str)
{
size_t i;
if (str.length()==0)
return false;
for (i = 0; i < str.length(); i++)
{
if(!isLetter(str[i]))
break;
}
if (i==str.length())
return true;
//some word may have '.', such as, Feb.
else if (i==str.length()-1 && str[i]=='.')
return true;
else
return false;
}
inline uint32_t lastBitOrder(uint32_t b)
{
int i;
if (b==0)
return 0;
else
{
i=0;
while ((b&0x1)==0)
{
b=b>>1;
i++;
}
}
return i;
}
/**
* @brief 找到从pos开始的下一个单词开头(不计算开通的空格)
* @return size_t 下一个单词的开头
*/
size_t nextWord(const string &str, size_t pos)
{
if (pos>=str.length())
{
return string::npos;
}
/*skip space in front*/
while (str[pos]==' ' && pos<str.length())
{
pos++;
}
if (pos>=str.length())
return string::npos;
/*skip the first word*/
while (pos<str.length())
{
if (str[pos]==' ')
break;
pos++;
}
if (pos>=str.length())
return string::npos;
/*skip space*/
while (str[pos]==' ' && pos<str.length())
{
pos++;
}
if (pos>=str.length())
return string::npos;
if (pos>=str.length())
return string::npos;
else
return pos;
}
/**
* @brief 获取字符串的第一个单词
*
* @param str
* @return string 第一个单词
*/
string getWord(const string &str)
{
size_t pos = 0;
/*skip space in front*/
while (str[pos]==' ' && pos<str.length())
{
pos++;
}
if (pos>=str.length())
return string("");
size_t begin = pos;
while (str[pos]!=' ' && pos<str.length())
{
pos++;
}
size_t end = pos;
return str.substr(begin, end-begin);
}
void eraseWrod(string &str)
{
size_t pos = nextWord(str, 0);
if(pos==string::npos)
str.clear();
else if (pos>=0)
str.erase(0, pos);
else
return;
}
void printVmInst(vector<vmInst_t> &instVector)
{
for (auto &it:instVector)
{
printf("|%c%c", it.cmd[0], it.cmd[1]);
if (it.haveNumber)
printf("%d", it.number);
}
printf("\n");
}
class Parser
{
public:
Parser(const string &intStr);
timeParserRet getTime();
private:
int32_t mEstimation;
string mInStr;
string mRemainStr;
vector<vmInst_t> mVmInst;
Date mParseResult;
uint32_t mParseFlag;
void instSrot(vector<vmInst_t> &instVector);
Date parseVM(vector<vmInst_t> &vmInst, uint32_t *resultFlag, int32_t *estimation);
void prepare();
void parseAmPm(string &words);
size_t parseSampleUnit(string &words, vector<vmInst_t> &instVector);
void parseFormat(string &words, vector<vmInst_t> &instVector);
void parsePhrase(string &words, vector<vmInst_t> &instVector);
bool setDateForce(Date &dst, uint32_t *dstFlag, Date &src, const uint32_t *srcFlag);
bool setDateWeek(Date &dst, uint32_t *dstFlag, Date &src, const uint32_t *srcFlag);
void removeMultipleSpaces(string &str);
};
Parser::Parser(const string &intStr)
{
mEstimation = 5;
mInStr = intStr;
transform(mInStr.begin(), mInStr.end(), mInStr.begin(), ::tolower);
mRemainStr = "";
}
timeParserRet Parser::getTime()
{
timeParserRet tRet;
prepare();
list<vector<vmInst_t>> instHolder;
parseAmPm(mRemainStr);
parseFormat(mRemainStr, mVmInst);
parsePhrase(mRemainStr, mVmInst);
string word;
bool wordLastFlag = false;
while ((word=getWord(mRemainStr)).length() != 0)
{
smatch regexResult;
bool haveNumber = false;
bool haveLetter = false;
bool haveOtherChar = false;
// bool havePointChar = false;
for (size_t i = 0; i < word.length(); i++)
{
if (isNumChar(word[i]))
haveNumber = true;
else if (isLetter(word[i]))
haveLetter = true;
//some word end with '.'
else if (i==word.length()-1 && word[i]=='.')
;
else
{
haveOtherChar = true;
break;
}
}
if (word==string("last"))
{
wordLastFlag = true;
eraseWrod(mRemainStr);
continue;
}
if (word==string("ago") && !instHolder.empty())
{
vector<vmInst_t> &lastInst = *(prev(instHolder.end()));
size_t i=0;
for (auto &it:lastInst)
{
if (it.haveNumber)
{
it.number = -abs(it.number);
}
}
}
/* 4 number, maybe year*/
if (!haveLetter && haveNumber && !haveOtherChar && word.length()==4)
{
/* can not "last yyyy" in sentence*/
if (wordLastFlag)
{
wordLastFlag = false;
mEstimation = min(mEstimation, TIME_PARSE_PARTLY_SUCCESS);
}
vector<vmInst_t> instVector;
instVector.push_back(vmInst_t{'y', 'y', true, std::atoi(word.c_str())});
instHolder.push_back(instVector);
eraseWrod(mRemainStr);
continue;
}
if(word==string("today"))
{
/* can not "last today" in sentence*/
if (wordLastFlag)
{
wordLastFlag = false;
mEstimation = min(mEstimation, TIME_PARSE_PARTLY_SUCCESS);
}
vector<vmInst_t> instVector;
instVector.push_back(vmInst_t{'d', 'd', false, 0});
instHolder.push_back(instVector);
eraseWrod(mRemainStr);
continue;
}
if(word==string("yesterday"))
{
/* can not "last yesterday" in sentence*/
if (wordLastFlag)
{
wordLastFlag = false;
mEstimation = min(mEstimation, TIME_PARSE_PARTLY_SUCCESS);
}
vector<vmInst_t> instVector;
instVector.push_back(vmInst_t{'d', 'd', true, -1});
instHolder.push_back(instVector);
eraseWrod(mRemainStr);
continue;
}
if(regex_search(word, regexResult, regex("(\\d{1,2})(st|nd|rd|th)")))
{
vector<vmInst_t> instVector;
instVector.push_back(vmInst_t{'m', 'd', true, std::atoi(word.c_str())});
instHolder.push_back(instVector);
eraseWrod(mRemainStr);
continue;
}
if(!haveOtherChar)
{
vector<vmInst_t> instVector;
size_t readSize = parseSampleUnit(mRemainStr, instVector);
if (readSize>0 && !instVector.empty())
{
mRemainStr.erase(0, readSize);
if (wordLastFlag)
{
wordLastFlag = false;
for (auto &it:instVector)
{
/**
* 在单词last后面时,haveNumber==fale也是可以的,
* 如:last year。这个时候,parseSampleUnit接续出来
* number应该是1
*/
it.haveNumber = true;
if (it.number>0)
it.number = -abs(it.number);
}
}
instHolder.push_back(instVector);
continue;
}
}
/*to do estimate*/
eraseWrod(mRemainStr);
}
for (auto &holderIt:instHolder)
{
for (auto &it:holderIt)
{
mVmInst.push_back(it);
}
}
instSrot(mVmInst);
mParseResult = parseVM(mVmInst, &mParseFlag, &mEstimation);
tRet.estimation = mEstimation;
tRet.flag = mParseFlag;
tRet.year = mParseResult.year();
tRet.month = mParseResult.month();
tRet.day = mParseResult.day();
tRet.hour = mParseResult.hour();
tRet.minute = mParseResult.minute();
tRet.second = mParseResult.second();
return tRet;
}
Date Parser::parseVM(vector<vmInst_t> &vmInst, uint32_t *resultFlag, int32_t *estimation)
{
Time ecTime;
Date nowDate = ecTime.toDate();
Date resultDate = ecTime.toDate();
uint32_t flagOut = 0, flagWeekOut = 0;
bool pm = false;
for (auto &it:vmInst)
{
Date tmpDate = resultDate;
uint32_t flag = 0, flagWeek = 0;
int weekDay;
switch (TWOCC(it.cmd))
{
case TWOCC("am"):
pm = false;
break;
case TWOCC("pm"):
pm = true;
break;
case TWOCC("dd"):
tmpDate.set(nowDate.year(), nowDate.month(), nowDate.day(), 9, 0, 0);
if (it.haveNumber && it.number<=0)
tmpDate = tmpDate.toTime().addDay(it.number);
else if (it.haveNumber && it.number>0)
{
*estimation = min(TIME_PARSE_PARTLY_SUCCESS, *estimation);
break;
}
flag = YEAR_FLAG|MONTH_FLGA|DAY_FLAG;
if (setDateForce(resultDate, &flagOut, tmpDate, &flag))
{
*estimation = min(TIME_PARSE_PARTLY_SUCCESS, *estimation);
}
flagOut |= flag;
break;
case TWOCC("yy"):
tmpDate = resultDate;
if (!it.haveNumber)
tmpDate.setYear(nowDate.year());
else if (0==it.number)
tmpDate.setYear(nowDate.year());
else if (it.number<0 && tmpDate.year()+it.number>1970)
tmpDate.addYear(it.number);
else if (it.number>1970)
tmpDate.setYear(it.number);
else
{
*estimation = min(TIME_PARSE_PARTLY_SUCCESS, *estimation);
break;
}
flag = YEAR_FLAG;
if (setDateForce(resultDate, &flagOut, tmpDate, &flag))
{
*estimation = min(TIME_PARSE_PARTLY_SUCCESS, *estimation);
}
flagOut |= flag;
break;
case TWOCC("mo"):
tmpDate = resultDate;
flag = MONTH_FLGA;
if (!it.haveNumber)
tmpDate.setMonth(nowDate.month());
else if (it.haveNumber==0)
tmpDate.setMonth(nowDate.month());
else if (1<=it.number && it.number<=12)
tmpDate.setMonth(it.number);
else if (-12<=it.number && it.number<=-1)
{
/*mo < 0 means that last xxx, sach as, "last may"*/
tmpDate.setMonth(abs(it.number));
tmpDate.setYear(resultDate.year()-1);
flag |= YEAR_FLAG;
}
else
{
*estimation = min(TIME_PARSE_PARTLY_SUCCESS, *estimation);
break;
}
if (setDateForce(resultDate, &flagOut, tmpDate, &flag))
{
*estimation = min(TIME_PARSE_PARTLY_SUCCESS, *estimation);
}
flagOut |= flag;
break;
case TWOCC("mn"):
if (!it.haveNumber)
;
else if (it.number=0)
;
else if (it.number<0)
tmpDate.addMonth(it.number);
else
{
*estimation = min(TIME_PARSE_PARTLY_SUCCESS, *estimation);
break;
}
flag = YEAR_FLAG|MONTH_FLGA;
if (setDateForce(resultDate, &flagOut, tmpDate, &flag))
{
*estimation = min(TIME_PARSE_PARTLY_SUCCESS, *estimation);
}
flagOut |= flag;
break;
case TWOCC("md"):
tmpDate = resultDate;
if(it.haveNumber && 1<=it.number && it.number<=31)
{
tmpDate.setDay(it.number);
if (tmpDate.month() != resultDate.month())
{
*estimation = min(TIME_PARSE_PARTLY_SUCCESS, *estimation);
break;
}
}
else
{
*estimation = min(TIME_PARSE_PARTLY_SUCCESS, *estimation);
break;
}
flag = DAY_FLAG;
if (setDateForce(resultDate, &flagOut, tmpDate, &flag))
{
*estimation = min(TIME_PARSE_PARTLY_SUCCESS, *estimation);
}
flagOut |= flag;
break;
case TWOCC("ww"):
tmpDate = resultDate;
weekDay = resultDate.week();
if (!it.haveNumber)
{
if (weekDay != 1)
{
tmpDate = tmpDate.toTime().addDay(-(weekDay-1));
}
}
else if (it.number==0)
{
if (weekDay != 1)
{
tmpDate = tmpDate.toTime().addDay(-(weekDay-1));
}
}
else if (it.number<0)
{
tmpDate = tmpDate.toTime().addDay(-(weekDay-1 + 7*it.number));
}
else
{
*estimation = min(TIME_PARSE_PARTLY_SUCCESS, *estimation);
break;
}
flagWeek = YEAR_FLAG|MONTH_FLGA|DAY_FLAG;
setDateWeek(resultDate, &flagOut, tmpDate, &flagWeek);
flagWeekOut |= flagWeek;
break;
case TWOCC("wd"):
tmpDate = resultDate;
if (!it.haveNumber)
break;
else if (it.number>0)
{
int dayOffast = resultDate.week() - it.number;
resultDate = resultDate.toTime().addDay(dayOffast).toDate();
if (nowDate<resultDate)
{
resultDate.toTime().addDay(-7).toDate();
}
}
else if (it.number<0)
{
int dayOffast = resultDate.week() - abs(it.number);
resultDate = resultDate.toTime().addDay(dayOffast - 7).toDate();
}
else
{
*estimation = min(TIME_PARSE_PARTLY_SUCCESS, *estimation);
break;
}
flagOut |= YEAR_FLAG|MONTH_FLGA|DAY_FLAG;
break;
case TWOCC("hh"):
if (!it.haveNumber)
break;
else if (it.number>=0)
{
if (pm && it.number<=12)
tmpDate.setHour((it.number+12)%24);
else
tmpDate.setHour(it.number%24);
}
else if (it.number<0)
{
tmpDate.toTime().addHour(it.number);
}
else
break;
flag = HOUR_FLAG;
if (setDateForce(resultDate, &flagOut, tmpDate, &flag))
{
*estimation = min(TIME_PARSE_PARTLY_SUCCESS, *estimation);
}
flagOut |= flag;
break;
case TWOCC("mi"):
if (!it.haveNumber)
break;
else if (it.number>=0)
{
tmpDate.setMinute(it.number);
}
else if (it.number<0)
{
tmpDate.toTime().addMinute(it.number);
}
else
break;
flag = MINUTE_FLAG;
if (setDateForce(resultDate, &flagOut, tmpDate, &flag))
{
*estimation = min(TIME_PARSE_PARTLY_SUCCESS, *estimation);
}
flagOut |= flag;
break;
case TWOCC("ss"):
if (!it.haveNumber)
break;
else if (it.number>=0)
{
tmpDate.setSecond(it.number);
}
else if (it.number<0)
{
tmpDate.toTime().setSeconds(it.number);
}
else
break;
flag = SECOND_FLAG;
if (setDateForce(resultDate, &flagOut, tmpDate, &flag))
{
*estimation = min(TIME_PARSE_PARTLY_SUCCESS, *estimation);
}
flagOut |= flag;
break;
case TWOCC("hn"):
if (((flagOut|flagWeek)&(HOUR_FLAG|MINUTE_FLAG|SECOND_FLAG))!=0)
break;
else if (it.haveNumber && it.number<=24)
{
resultDate.setHour(it.number%24);
resultDate.setMinute(0);
resultDate.setSecond(0);
flagWeek |= HOUR_FLAG|MINUTE_FLAG|SECOND_FLAG;
}
else
{
*estimation = min(TIME_PARSE_PARTLY_SUCCESS, *estimation);
break;
}
break;
default:
break;
}
}
if (resultDate.year()<1970)
{
*estimation = min(TIME_PARSE_LITTLE_SUCCESS, *estimation);
}
*resultFlag = flagOut|flagWeekOut;
/*如果日期不是今天了,且没有设置 时分秒,那么就设置在早上9点*/
bool dayChange = true;
if (nowDate.year()==resultDate.year() &&
nowDate.month()==resultDate.month() &&
nowDate.day()==resultDate.day())
{
dayChange = false;
}
if (dayChange && (*resultFlag&(HOUR_FLAG|MINUTE_FLAG|SECOND_FLAG))==0)
{
resultDate.setHour(9);
resultDate.setMinute(0);
resultDate.setSecond(0);
}
return resultDate;
}
void Parser::instSrot(vector<vmInst_t> &instVector)
{
char orderTable[][2] = {
{'a', 'm'},
{'p', 'm'},
{'d', 'd'},
{'y', 'y'},
{'m', 'o'},
{'m', 'n'},
{'m', 'd'}
};
int32_t notOrderNumb=0;
int32_t scanNumb;
int32_t orderNumb;
for (orderNumb = 0; orderNumb < sizeof(orderTable); orderNumb++)
{
for (scanNumb=notOrderNumb; scanNumb<instVector.size(); scanNumb++)
{
if (instVector[scanNumb].cmd[0]==orderTable[orderNumb][0] &&
instVector[scanNumb].cmd[1]==orderTable[orderNumb][1] )
{
swap(instVector[notOrderNumb], instVector[scanNumb]);
notOrderNumb++;
}
}
}
}
/*
字符预处理
in,on,at -> in
删除多余的空格
*/
void Parser::prepare()
{
uint32_t spaceAccount=0;
char *strBuffer = (char *)malloc(mInStr.length() + 1);
size_t j=0;
for (size_t i = 0; i < mInStr.length(); i++)
{
char ch;
if (mInStr[i]==' ' || mInStr[i]=='\t')
spaceAccount++;
else
spaceAccount=0;
if (spaceAccount>1 || mInStr[i]=='|')
continue;
else if (mInStr[i]=='\t')
ch = ' ';
else
ch = mInStr[i];
strBuffer[j] = ch;
j++;
}
strBuffer[j] = '\0';
mRemainStr = string(strBuffer);
free(strBuffer);
while (mRemainStr.find("on ")!=string::npos)
{
mRemainStr.replace(mRemainStr.find("on "), 2, "in");
}
while (mRemainStr.find("at ")!=string::npos)
{
mRemainStr.replace(mRemainStr.find("at "), 2, "in");
}
}
void Parser::parseAmPm(string &words)
{
if (words.length()==0)
return;
int pos=0;
while ( (pos=words.find("am", pos))!=string::npos )
{
//一个合格的am,前后应该只有空格或者数字
if ((pos==0 || isNumChar(words[pos-1]) || words[pos-1]==' ') &&
(words[pos+2]=='\0' || isNumChar(words[pos+2]) || words[pos+2]==' '))
{
vmInst_t inst = {{'a', 'm'}, false, 0};
mVmInst.push_back(inst);
words.replace(pos, 2, " ");
}
else
pos++;
}
pos=0;
while ( (pos=words.find("pm", pos))!=string::npos )
{
//一个合格的pm,前后应该只有空格或者数字
if ((pos==0 || isNumChar(words[pos-1]) || words[pos-1]==' ') &&
(words[pos+2]=='\0' || isNumChar(words[pos+2]) || words[pos+2]==' '))
{
vmInst_t inst = {{'p', 'm'}, false, 0};
mVmInst.push_back(inst);
words.replace(pos, 2, " ");
}
else
pos++;
}
removeMultipleSpaces(words);
}
/**
* @brief 尝试解析简单带单位时间表示
*
* @param words
* @param instVector 返回的命令
* @return size_t 读取长度
*/
size_t Parser::parseSampleUnit(string &words, vector<vmInst_t> &instVector)
{
if (words.length()==0)
return -1;
/*一个合格的单位应该只有字母*/
size_t unitBegin = 0;
string unit = getWord(words);
if (unit.length()==0)
return -1;
/*如果第一个单词不是纯字母,考虑看看第二个,因为前一个可能是数字*/
if (!isLetterOnly(unit))
{
unitBegin = nextWord(words, unitBegin);
if (unitBegin == string::npos)
return -1;
unit = getWord( words.substr(unitBegin, words.length()-unitBegin) );
if (unit.length()==0)
return -1;
}
if (!isLetterOnly(unit))
{
return -1;
}
size_t unitEnd=unitBegin;
while(unitEnd < words.length())
{
if (isLetter(words[unitEnd]))
unitEnd++;
else
break;
}
size_t numberBegin = 0;
int32_t number=-1;
while (numberBegin<words.length() && numberBegin<unitBegin)
{
if (isNumChar(words[numberBegin]))
{
number = atoi(words.c_str()+numberBegin);
break;
}
numberBegin++;
}
if (unit==string("year") || unit==string("years"))
{
instVector.push_back(vmInst_t {{'y', 'y'}, number>-1, number>-1 ? number : 1});
return unitEnd;
}
if (unit==string("month") || unit==string("month"))
{
instVector.push_back(vmInst_t {{'m', 'n'}, number>-1, number>-1 ? number : 1});
return unitEnd;
}
for (int32_t i = 0; i < 12; i++)
{
if (unit.find(monthShortName[i])!=string::npos)
{
instVector.push_back(vmInst_t {{'m', 'o'}, true, i+1});
if (number>0)
{
instVector.push_back(vmInst_t {{'m', 'd'}, true, number});
}
return unitEnd;
}
}
if (unit==string("weekend"))
{
instVector.push_back(vmInst_t {{'w', 'n'}, false, 1});
return unitEnd;
}
if (unit==string("week"))
{
instVector.push_back(vmInst_t {{'w', 'w'}, number>-1, number>-1 ? number : 1});
return unitEnd;
}
for (int32_t i = 0; i < 7; i++)
{
if (unit.find(weekShortName[i])!=string::npos)
{
instVector.push_back(vmInst_t {{'w', 'd'}, true, i+1});
return unitEnd;
}
}
if (unit==string("day") || unit==string("days"))
{
instVector.push_back(vmInst_t {{'d', 'd'}, number>-1, number>-1 ? number : 1});
return unitEnd;
}
if (unit==string("morning"))
{
instVector.push_back(vmInst_t {{'h', 'n'}, true, 9});
return unitEnd;
}
if (unit==string("noon"))
{
instVector.push_back(vmInst_t {{'h', 'n'}, true, 12});
return unitEnd;
}
if (unit==string("afternoon"))
{
instVector.push_back(vmInst_t {{'h', 'n'}, true, 14});
return unitEnd;
}
if (unit==string("night"))
{
instVector.push_back(vmInst_t {{'h', 'n'}, true, 21});
return unitEnd;
}
if (unit==string("midnight"))
{
instVector.push_back(vmInst_t {{'h', 'n'}, true, 24});
return unitEnd;
}
if (unit==string("hour") || unit==string("hours"))
{
instVector.push_back(vmInst_t {{'h', 'h'}, number>-1, number>-1 ? number : 1});
return unitEnd;
}
if (unit==string("minute") || unit==string("minutes"))
{
instVector.push_back(vmInst_t {{'m', 'i'}, number>-1, number>-1 ? number : 1});
return unitEnd;
}
if (unit==string("second") || unit==string("seconds"))
{
instVector.push_back(vmInst_t {{'s', 'i'}, number>-1, number>-1 ? number : 1});
return unitEnd;
}
return unitEnd;
}
/**
* @brief 解析常见的格式化时间表达,并在原文中擦除
*
* @param words
* @param instVector 输出的命令
*/
void Parser::parseFormat(string &words, vector<vmInst_t> &instVector)
{
if (words.length()==0)
return;
smatch regexResult;
//YYY-MM-DD
regex pattern = regex("(\\d{4})[^:]{1,1}(\\d{1,2})[^:]{1,1}(\\d{1,2})");
if (regex_search(words, regexResult, pattern) &&
atoi(regexResult.str(1).c_str())>=1970 &&
atoi(regexResult.str(2).c_str())<=12 &&
atoi(regexResult.str(3).c_str())<=31)
{
instVector.push_back(vmInst_t {{'y', 'y'}, true, atoi(regexResult.str(1).c_str())});
instVector.push_back(vmInst_t {{'m', 'o'}, true, atoi(regexResult.str(2).c_str())});
instVector.push_back(vmInst_t {{'m', 'd'}, true, atoi(regexResult.str(3).c_str())});
words = regex_replace(words, pattern, "");
}
//DD-MM-YYYY
pattern = regex("(\\d{1,2})[^:]{1}(\\d{1,2})[^:]{1}(\\d{4})");
if (regex_search(words, regexResult, pattern) &&
atoi(regexResult.str(1).c_str())<=31 &&
atoi(regexResult.str(2).c_str())<=12 &&
atoi(regexResult.str(3).c_str())>=1970)
{
instVector.push_back(vmInst_t {{'m', 'd'}, true, atoi(regexResult.str(1).c_str())});
instVector.push_back(vmInst_t {{'m', 'o'}, true, atoi(regexResult.str(2).c_str())});
instVector.push_back(vmInst_t {{'y', 'y'}, true, atoi(regexResult.str(3).c_str())});
words = regex_replace(words, pattern, "");
}
//YY-MM
pattern = regex("(\\d{4})[^:]{1}(\\d{1,2})");
if (regex_search(words, regexResult, pattern) &&
atoi(regexResult.str(2).c_str())<=31)
{
instVector.push_back(vmInst_t {{'y', 'y'}, true, atoi(regexResult.str(1).c_str())});
instVector.push_back(vmInst_t {{'m', 'o'}, true, atoi(regexResult.str(2).c_str())});
words = regex_replace(words, pattern, "");
}
//hh:mm:ss
pattern = regex("(\\d{1,2}):(\\d{1,2}):(\\d{1,2})");
if (regex_search(words, regexResult, pattern) &&
atoi(regexResult.str(1).c_str())<=24 &&
atoi(regexResult.str(2).c_str())<=60 &&
atoi(regexResult.str(3).c_str())<=60)
{
instVector.push_back(vmInst_t {{'h', 'h'}, true, atoi(regexResult.str(1).c_str())});
instVector.push_back(vmInst_t {{'m', 'i'}, true, atoi(regexResult.str(2).c_str())});
instVector.push_back(vmInst_t {{'s', 's'}, true, atoi(regexResult.str(3).c_str())});
words = regex_replace(words, pattern, "");
}
//hh:mm
pattern = regex("(\\d{1,2}):(\\d{1,2})");
if (regex_search(words, regexResult, pattern) &&
atoi(regexResult.str(1).c_str())<=24 &&
atoi(regexResult.str(2).c_str())<=60)
{
instVector.push_back(vmInst_t {{'h', 'h'}, true, atoi(regexResult.str(1).c_str())});
instVector.push_back(vmInst_t {{'m', 'i'}, true, atoi(regexResult.str(2).c_str())});
words = regex_replace(words, pattern, "");
}
removeMultipleSpaces(words);
}
/**
* @brief 在words中找到常见词组,解析成命令并将解析过的词组擦除。
*
* @param words
* @param instVector 输出的命令
*/
void Parser::parsePhrase(string &words, vector<vmInst_t> &instVector)
{
string strFind;
strFind = string("the year before last year");
if(words.find(strFind)!=string::npos)
{
words.replace(words.find(strFind), strFind.length(), "");
instVector.push_back(vmInst_t {{'y', 'y'}, true, -2});
}
strFind = string("the month before last month");
if(words.find(strFind)!=string::npos)
{
words.replace(words.find(strFind), strFind.length(), "");
instVector.push_back(vmInst_t {{'m', 'o'}, true, -2});
}
strFind = string("the day before yesterday");
if(words.find(strFind)!=string::npos)
{
words.replace(words.find(strFind), strFind.length(), "");
instVector.push_back(vmInst_t {{'d', 'd'}, true, -2});
}
removeMultipleSpaces(words);
return;
}
void Parser::removeMultipleSpaces(string &str){
uint32_t i=0;
uint32_t gotSpace=0;
while (i<str.length())
{
if (str[i]==' ')
gotSpace++;
else
gotSpace=0;
if (gotSpace>1)
{
str.erase(i,1);
}
else
{
i++;
}
}
}
/**
* @brief 设置时间并检测冲突,无论有没有冲突都会设置时间
*
* @param dst 目标时间
* @param dstFlag 目标时间有效的标记
* @param src 源时间
* @param srcFlag 希望设置目标时间的部分
* @return true 设置时间时发现有冲突
* @return false 设置时间时没发现冲突
*/
bool Parser::setDateForce(Date &dst, uint32_t *dstFlag, Date &src, const uint32_t *srcFlag)
{
bool conflict = false;
if (lastBitOrder(*srcFlag)<=lastBitOrder(YEAR_FLAG))
{
if ((*dstFlag&YEAR_FLAG) && dst.year()!=src.year())
conflict = true;
dst.setYear(src.year());
}
if (lastBitOrder(*srcFlag)<=lastBitOrder(MONTH_FLGA))
{
if ((*dstFlag&MONTH_FLGA) && dst.month()!=src.month())
conflict = true;
dst.setMonth(src.month());
}
if (lastBitOrder(*srcFlag)<=lastBitOrder(DAY_FLAG))
{
if ((*dstFlag&DAY_FLAG) && dst.day()!=src.day())
conflict = true;
dst.setDay(src.day());
}
if (lastBitOrder(*srcFlag)<=lastBitOrder(HOUR_FLAG))
{
if ((*dstFlag&HOUR_FLAG) && dst.hour()!=src.hour())
conflict = true;
dst.setHour(src.hour());
}
if (lastBitOrder(*srcFlag)<=lastBitOrder(MINUTE_FLAG))
{
if ((*dstFlag&MINUTE_FLAG) && dst.minute()!=src.minute())
conflict = true;
dst.setMinute(src.minute());
}
if (lastBitOrder(*srcFlag)<=lastBitOrder(SECOND_FLAG))
{
if ((*dstFlag&SECOND_FLAG) && dst.second()!=src.second())
conflict = true;
dst.setSecond(src.second());
}
return conflict;
}
bool Parser::setDateWeek(Date &dst, uint32_t *dstFlag, Date &src, const uint32_t *srcFlag)
{
bool conflict = false;
if (lastBitOrder(*srcFlag)>=YEAR_FLAG)
{
if ((*dstFlag&YEAR_FLAG) && dst.year()!=src.year())
conflict = true;
else
dst.setYear(src.year());
}
if (lastBitOrder(*srcFlag)>=MONTH_FLGA)
{
if ((*dstFlag&MONTH_FLGA) && dst.month()!=src.month())
conflict = true;
else
dst.setMonth(src.month());
}
if (lastBitOrder(*srcFlag)>=DAY_FLAG)
{
if ((*dstFlag&DAY_FLAG) && dst.day()!=src.day())
conflict = true;
else
dst.setDay(src.day());
}
if (lastBitOrder(*srcFlag)>=HOUR_FLAG)
{
if ((*dstFlag&HOUR_FLAG) && dst.hour()!=src.hour())
conflict = true;
else
dst.setHour(src.hour());
}
if (lastBitOrder(*srcFlag)>=MINUTE_FLAG)
{
if ((*dstFlag&MINUTE_FLAG) && dst.minute()!=src.minute())
conflict = true;
else
dst.setMinute(src.minute());
}
if (lastBitOrder(*srcFlag)>=SECOND_FLAG)
{
if ((*dstFlag&SECOND_FLAG) && dst.second()!=src.second())
conflict = true;
else
dst.setSecond(src.second());
}
return conflict;
}
timeParserRet EnTimeParser::parse(string description)
{
Time nowTime;
Parser timeParser(description);
return timeParser.getTime();;
} | 27.373036 | 92 | 0.502266 | [
"vector",
"transform"
] |
ee3c5f6bd6063f87354618c2d2b3fc2bcb4a4999 | 9,872 | cpp | C++ | cpp/src/main.cpp | SamuelMarks/oauth2 | 801a2c8027ca58a536aa326ad2412595be49cf06 | [
"MIT"
] | 3 | 2020-12-22T16:21:33.000Z | 2021-04-22T19:22:12.000Z | cpp/src/main.cpp | SamuelMarks/oauth2 | 801a2c8027ca58a536aa326ad2412595be49cf06 | [
"MIT"
] | 1 | 2021-04-21T10:19:04.000Z | 2021-04-23T02:51:16.000Z | cpp/src/main.cpp | SamuelMarks/oauth2 | 801a2c8027ca58a536aa326ad2412595be49cf06 | [
"MIT"
] | 3 | 2020-12-22T16:22:27.000Z | 2021-04-21T08:11:20.000Z | /**
* OAuth2 in C/C++
* Go straight for flow that uses Serverless version
* to get information about the login
*/
#include "url.h"
#include "tiny_web_client.h"
#include "random_string.h"
#include "json_parser.h"
#include "open_browser.h"
#include "tiny_web_server.h"
int main()
{
std::cout << "==============================================\n"
<< "(Public API call) GetApplicationEndpoint\n"
<< "==============================================" << std::endl;
const URL target(static_cast<const std::ostringstream&>(
std::ostringstream() << "https://" << API_HOST
<< API_APPLICATION_ENDPOINT_PATH).str());
Request request = make_request(target);
Response response;
const auto resp = http_send(request, response);
if ( resp != 0 ) {
std::cerr << "resp: " << resp << std::endl;
throw std::runtime_error("request failed");
}
std::cout << "Body: " << response.body << '\n';
const std::string temporary_secret_state = generate_random_string(5);
std::cout << "Generated secret state: " << temporary_secret_state << std::endl;
const JsonItem metadata = json_create_from_string(response.body);
#ifdef TEST_JSON
json_pretty_print(metadata);
#endif
const auto openid_json = metadata.object.find("openid");
std::cout << "OpenID: " << openid_json->second.text << "\n"
<< "==============================================\n"
<< "(Public API call) OpenID Metadata Call\n"
<< "==============================================" << std::endl;
Request openid_request = make_request(URL(openid_json->second.text));
Response openid_response;
if ( http_send(openid_request, openid_response) != 0 ) {
throw std::runtime_error("request failed");
}
const JsonItem openid_metadata = json_create_from_string(openid_response.body);
#ifdef TEST_JSON
json_pretty_print(openid_metadata);
#endif
const auto authorization_endpoint_json = openid_metadata.object.find("authorization_endpoint");
const std::string authorization_endpoint = authorization_endpoint_json->second.text;
std::cout << "==============================================\n"
<< "Send user to browser\n"
<< "==============================================" << std::endl;
const std::string redirect_uri = static_cast<const std::ostringstream&>(
std::ostringstream() << "http://" << SERVER_HOST << ':'
<< PORT_TO_BIND << EXPECTED_PATH).str();
URL authorization_url = URL(authorization_endpoint);
authorization_url.add_param("response_type", "code");
authorization_url.add_param("client_id", metadata.object.find("clientId")->second.text);
authorization_url.add_param("redirect_uri", redirect_uri);
authorization_url.add_param("state", temporary_secret_state);
authorization_url.add_param("scope", "openid");
open_browser(authorization_url);
// we then need to start our web server and block
// until we get the appropriate response
// TODO make details no longer macros
std::cout << "==============================================\n"
<< "Await response to be passed from browser to local web server\n"
<< "==============================================" << std::endl;
const AuthenticationResponse oauth_response = wait_for_oauth2_redirect();
// GET /ibm/cloud/appid/callback?code=fVTDrC7Dt8KyG2jCv8OQEMOCTS4TWsK9AULCmx7Dl8KXw5wKJAjDv1rDiMKCw6TCncOkIC95KFfCpDMrGmzCusOCwrB4ZcKTZSFCwrc1wrPClwVtwpzDg3knw57DoMKvwoLDrsOfWcONB8OHwprDvcKzesKTVsOSdCrCindIw4RFOTnCgjzDrwvCq15EwrZJUMK5PsOaNks8F8KVw7fCi3pCwpQEdSYGLGNAwrzDoMO5KRw2w7HDkiIIA8OtNyTDrcKOwrvCv8Otw5jDksODBcKeB3XDtcKCfcK2wr7ChHXChkDCkGDDi2XDjsO7w6DDj8KDw5hFw5jDqGoMw7LDmhnCiMKUwo4Cw5QSw4HDoy5hFklqwpJ4wo_CsRxXNw&state=3otgw HTTP/1.1
// Host: localhost:3000
// User-Agent: Mozilla/5.0 (X11; Fedora; Linux x86_64; rv:83.0) Gecko/20100101 Firefox/83.0
// Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
// Accept-Language: en-GB,en;q=0.5
// Accept-Encoding: gzip, deflate
// Connection: keep-alive
// Cookie: .AspNetCore.Cookies=CfDJ8PB0mYqBkIZEkM1UBJ7BKURUGzbrmg4MKt5wi0WeBMuIpuUXjfgi-vrBRPaTOi4_d4h6s7z8_x7Kv78YpMdXABnUh2OGRNN456SoqIPkOknw9KCwvthbVXb3fQfBSTD47BRcplqTFmZSZ9T4EgcqEm8Y2oCaVsZTjRlCcijipQkPP0JsOCc241xiVWZXwqRtrj_pSFSl1DDjyTDmaQ75iUwEibnwXI6vOtSeb8G010ZVXQZs5xbugFJuNjm1SCILqrwMigVkuAmNxCzkULyFkpriLBlS6q9fVx50YAu4vPRZGtJE83nTiv5R_Y1DV1g2Qvo1ZeUpUzAo8Kt5PwVKR-A2rXQKnOJoccY4zrbe4lRG2qZ-RlZ4iBzf167TS1mAjxuAOrIvyofVr__fG-XkHnCCLD9r5gnr6BPnm374SoOGr3e_1iTxoc7Bk0a0-xTrLPaGZhzyL-s1Nz8ZKHk3BqXmeecoLwbDt2gTjxeS-hnsdrC4qT7_2bljAnMtU3BQ9iIoXQi9Yv-P_GhzaqlsBvq_TRcjiD2DJHT6yV7GI8yJetVwY7NNXFrmPrznkMl90QuA6wMc0C-XbHYNFc-6EsoImC1_f2aq7VgkBEp2wf8Ij0ZWSvgqdJ88T3WiK4GtXB55v_JDM-6c6I0smY9cYi0-HArlHPljUOS6_KacBetsbl49bKhU6NxZKnKgNRQVlrTXMmrBwt-h2f8b-pXuj0bkZgO-lpBUTI2FEaJnRfAOFykmylT-Ov4dLqYAkFGBFtbMKs6ppxDu0462-cKg0unuwBxriw8tXYNXzXrh6b33wdpns-Rwgeh7X_R9f3sPFSDCUk0qxv9JDr3C6HHcglsTQdcXCmmpxeSinjY6Fi9k2aIc-xIiZDkyjMDo10HirUiY9MuNKVkrj9C66pliYL5u-xVmvF1f51heRkGf1LSFxlhzijAyX_WB9siwGRU54aUBdMA_ww7cn0zks-PnsjH-RTRKBek98oOm_uJ5G2yPW-EAuKZdMl8V0xYJBF3b_iPWqCQ06rkTKpYN8rHR2pADH2idcUIkT374UuZ_ptY0-tO7UoiNfDs89eYLhEjpeuotnM6sCwLdTO9kF6QEaVuXtzg4ivAdGu42msRdu40SjhTsoCd1DCPPmqPNHf23RHPHUB1fOfdoSKLRmT9UHuSDAxqKFHWb1o1iQABtrpUS6N02tHGn92_-zT_tF0xb8l9QAQDj2YSzAnx0UjpceEIAVGhRRMNulWO-Tzgu8GcLTVQ1T2PpJYtRJsSabVjI6plGF3bKlZUeWG9DHdtvCSdwqYZoWHQjw7YaMFFPcYMTa9GqmkXsAEg6_aVID56WY4Pnkj7TU6N4tpdTl6MOL-P1lHUKtWJHsda44MtVGc5x4C8C8k7whEOJ0vWtDEBTlHODluP6ce16IZOG8Gi3dIcRg1MF7t3pKg6I0PN3ygFVMf7u05KeNq5A8NO9xtzfsLzEiaK0DMgmhnz4msDu3VtoZHl-fU-gmVNPwLMs962dUvHUms9i_sDdXwjuASNZvzorLzrfRNmhHYAVaTYCZdalAtXMkHZv3Hh3WJ-VXn5Y4eevX_VC88cNGSM9s5zYajZTUZ0LTaA7seYVFoxFKk80Vd5d_7sal7jJI7hTQAqSlwumr_GzBhsq9OD6NjlLrwYw0DthGO0V-CskAhJJ6rvQ0KhsVgbOzEPxDsdp_8iQhqxbuaQejxE_5WMmNUWDIUsJ0BHUDMdxpXZdIdH2n6s; connect.sid=s%3Anl3r6kNI5uoXAAnd2fF340b18GEMuP00.n%2Fi%2F41RWdj%2B76wNAVr%2B41slPZrEQEhKg3NXJXicgbxo
// Upgrade-Insecure-Requests: 1
// we still need to parse out the code and state secret.
std::cout << oauth_response.raw << '\n'
<< oauth_response.code << '\n'
<< oauth_response.secret << std::endl;
if ( oauth_response.secret != temporary_secret_state ) {
throw std::runtime_error(static_cast<const std::ostringstream&>(
std::ostringstream() <<"oauth2 redirect contained the wrong secret state ("
<< oauth_response.secret << ","
<< "expected " << temporary_secret_state << '\n').str());
} else {
std::cout << "Secret state was successfully retrieved from redirect url.\n";
}
// get the access token
std::cout << "==============================================\n"
<< "(Public API+secret) GetAccessToken\n"
<< "==============================================" << std::endl;
const URL token_url = URL(
static_cast<const std::ostringstream&>(
std::ostringstream() << "https://" << API_HOST << API_GET_ACCESS_TOKEN_PATH).str());
const std::map<std::string, std::string> post_fields {
std::make_pair("grant_type", "authorization_code"),
std::make_pair("code", oauth_response.code),
std::make_pair("redirect_uri", redirect_uri),
std::make_pair("client_id", metadata.object.find("clientId")->second.text)
};
Request token_request = make_request(token_url, "POST");
Response token_response;
if ( http_send(token_request, token_response, post_fields) != 0 ) {
throw std::runtime_error("request failed to get token");
}
std::cout << token_response.raw << std::endl;
const JsonItem access_json = json_create_from_string(token_response.body);
const std::string access_token = access_json.object.find("access_token")->second.text;
std::cout << "Access Token: " << access_token << '\n';
// get user details to prove we are looked and show
// how to pass bearer token
std::cout << "==============================================\n"
<< "(Published Private API) UserInfo\n"
<< "==============================================" << std::endl;
const auto userinfo_endpoint_json = openid_metadata.object.find("userinfo_endpoint");
const std::string userinfo_endpoint = userinfo_endpoint_json->second.text;
const URL userinfo_url = URL(userinfo_endpoint);
Request userinfo_request = make_request(userinfo_url);
userinfo_request.headers.emplace_back("Content-type: application/json");
userinfo_request.headers.push_back("Authorization: Bearer " + access_token);
Response userinfo_response;
if ( http_send(userinfo_request, userinfo_response) ) {
throw std::runtime_error("request failed to get userinfo");
}
std::cout << userinfo_response.raw << '\n';
// Get contents of a private url
std::cout << "==============================================\n"
<< "(Our Private API) Hello\n"
<< "==============================================" << std::endl;
Request private_request = make_request(URL("https://31f5ff35.eu-gb.apigw.appdomain.cloud/private-authtest/Hello"));
private_request.headers.emplace_back("Content-type: application/json");
private_request.headers.push_back("Authorization: Bearer " + access_token);
Response private_response;
if ( http_send(private_request, private_response) ) {
throw std::runtime_error("request failed to get userinfo");
}
std::cout << private_response.raw << '\n';
}
| 61.31677 | 1,892 | 0.672002 | [
"object"
] |
ee3c8bcf8c88fa0a47eadfd0e731884124ee67e8 | 5,264 | cpp | C++ | C++/STL/algorithm.cpp | tanishq1g/cp_codes | 80b8ccc9e195a66d6d317076fdd54a02cd21275b | [
"MIT"
] | null | null | null | C++/STL/algorithm.cpp | tanishq1g/cp_codes | 80b8ccc9e195a66d6d317076fdd54a02cd21275b | [
"MIT"
] | null | null | null | C++/STL/algorithm.cpp | tanishq1g/cp_codes | 80b8ccc9e195a66d6d317076fdd54a02cd21275b | [
"MIT"
] | null | null | null | #include <algorithm>
#include <unordered_map>
using namespace std;
int main() {
min(x,y)
// x and y can only be integers and not overloaded functions
max(x,y)
sort(first_iterator, last_iterator) //To sort the given vector.
reverse(first_iterator, last_iterator) //To reverse a vector.
*max_element (first_iterator, last_iterator)// To find the maximum element of a vector.
*min_element (first_iterator, last_iterator)// To find the minimum element of a vector.
accumulate(first_iterator, last_iterator, initial value of sum)// Does the summation of vector elements
// Initializing vector with array values
int arr[] = {10, 20, 5, 23 ,42 , 15};
int n = sizeof(arr)/sizeof(arr[0]);
vector<int> vect(arr, arr+n);
cout << "Vector is: ";
for (int i=0; i<n; i++)
cout << vect[i] << " ";
// Sorting the Vector in Ascending order
sort(vect.begin(), vect.end());
// Sorting the Vector in descending order
sort(vect.begin(), vect.end(), greater<int>());
bool cmp(vector<int> v1, vector<int> v2){
return v1[0] < v2[0];
}
vector<vector<int>> v(n, vector<int> (2, 0));
sort(v.begin(), v.end(), cmp);
// Reversing the Vector
reverse(vect.begin(), vect.end());
cout << "\nVector after reversing is: ";
for (int i=0; i<6; i++)
cout << vect[i] << " ";
cout << "\nMaximum element of vector is: ";
cout << *max_element(vect.begin(), vect.end());
cout << "\nMinimum element of vector is: ";
cout << *min_element(vect.begin(), vect.end());
// Starting the summation from 0
cout << "\nThe summation of vector elements is: ";
cout << accumulate(vect.begin(), vect.end(), 0);
result = pow(base, exponent);
double x = 10.25, result;
result = sqrt(x)
// sorting strings
sort(str.begin(), sort.end());
//sorting based on comparator
static bool comparator( vector<int>& a, vector<int>& b )
{
return a[0] < b[0];
}
vector<vector<int>>& intervals
//Sort the inetrvals first based on the start of interval
sort( intervals.begin(), intervals.end(), comparator );
// find
Returns an iterator to the first element in the range [first,last) that compares equal to val. If no such element is found, the function returns last.
// using find with vector and iterator:
vector<int> myvector { 10, 20, 30, 40 };
vector<int>::iterator it;
it = find (myvector.begin(), myvector.end(), 30);
if (it != myvector.end())
cout << "Element found in myvector: " << *it << '\n';
else
cout << "Element not found in myvector\n";
//binary search
// Parameters
// first, last
Forward iterators to the initial and final positions of a sorted (or properly partitioned) sequence. The range used is [first,last), which contains all the elements between first and last, including the element pointed by first but not the element pointed by last.
// val
Value to search for in the range.
For (1), T shall be a type supporting being compared with elements of the range [first,last) as either operand of operator<.
// comp
Binary function that accepts two arguments of the type pointed by ForwardIterator (and of type T), and returns a value convertible to bool. The value returned indicates whether the first argument is considered to go before the second.
The function shall not modify any of its arguments.
This can either be a function pointer or a function object.
// Return value
true if an element equivalent to val is found, and false otherwise.
// Complexity
On average, logarithmic in the distance between first and last: Performs approximately log2(N)+2 element comparisons (where N is this distance).
binary_search (v.begin(), v.end(), 3)
// upper bound , lower bound - works on sorted arrays
parameters same as above
// Return value for upper_bound
An iterator to the upper bound position for val in the range.
If no element in the range compares greater than val, the function returns last.
// Return value for lower_bound
An iterator to the lower bound of val in the range.
If all the element in the range compare less than val, the function returns last.
// 10 10 10 20 20 20 30 30
std::vector<int>::iterator low,up;
low=std::lower_bound (v.begin(), v.end(), 20); // 3
up= std::upper_bound (v.begin(), v.end(), 20); // 6
Performs approximately log2(N)+1 element comparisons (where N is this distance).
// lexicographical_compare
https://en.cppreference.com/w/cpp/algorithm/lexicographical_compare
bool lexicographical_compare(iter1 beg1, iter1 end1, iter2 beg2, iter2 end2)
Checks if the first range [first1, last1) is lexicographically less than the second range [first2, last2).
char one[] = "geeksforgeeks";
char two[] = "gfg";
// using lexicographical_compare for checking
// is "one" is less than "two"
if( lexicographical_compare(one, one+13, two, two+3)) {
cout << "geeksforgeeks is lexicographically less than gfg";
}
else{
cout << "geeksforgeeks is not lexicographically less than gfg";
}
Output:
geeksforgeeks is lexicographically less than gfg | 37.333333 | 268 | 0.667363 | [
"object",
"vector"
] |
ee40859bb2f1f237a9e2e26a42f2d7372b34816c | 2,288 | cpp | C++ | essential/udacity-cpp-nano/Projects/Intro_to_Concurrency/Mutex_and_Lock/dead_lock_ex_2.cpp | disono/cp-cheat-sheet | 02edee3d822f56770e1a1a3cc4db6be3691a7a38 | [
"MIT"
] | null | null | null | essential/udacity-cpp-nano/Projects/Intro_to_Concurrency/Mutex_and_Lock/dead_lock_ex_2.cpp | disono/cp-cheat-sheet | 02edee3d822f56770e1a1a3cc4db6be3691a7a38 | [
"MIT"
] | null | null | null | essential/udacity-cpp-nano/Projects/Intro_to_Concurrency/Mutex_and_Lock/dead_lock_ex_2.cpp | disono/cp-cheat-sheet | 02edee3d822f56770e1a1a3cc4db6be3691a7a38 | [
"MIT"
] | null | null | null | /**
* [Description]
* Using mutexes can significantly reduce the risk of data races as seen in the example above.
* But imagine what would happen if an exception was thrown while executing code in the
* critical section, i.e. between lock and unlock. In such a case, the mutex would remain
* locked indefinitely and no other thread could unlock it - the program would most likely freeze.
* */
#include <iostream>
#include <thread>
#include <vector>
#include <future>
#include <algorithm>
#include <mutex>
std::mutex mtx;
double result;
void printResult(int denom)
{
std::cout << "for denom = " << denom << ", the result is " << result << std::endl;
}
void divideByNumber(double num, double denom)
{
mtx.lock();
try
{
// devide num by denom but throw an exception if division by zero is attempted
if (denom != 0)
{
result = num / denom;
std::this_thread::sleep_for( std::chrono::milliseconds(1) );
printResult(denom);
}
else
{
throw std::invalid_argument("Execption from thread: Division by zero!");
}
}
catch(const std::invalid_argument& e)
{
// notify the user about the exception and return
std::cout << e.what() << std::endl;
return;
}
mtx.unlock();
}
int main()
{
// create a number of threads which execute the function "divideByNumber" with varying parameters
std::vector<std::future<void>> futures;
for (double i = -5; i <= +5; i++)
{
futures.emplace_back( std::async(std::launch::async, divideByNumber, 50.0, i) );
}
// wait for the results
std::for_each( futures.begin(), futures.end(), [](std::future<void>& ftr) {
ftr.wait();
} );
return 0;
}
/**
* [Output]
*
* for denom = -5, the result is -10
* for denom = -4, the result is -12.5
* for denom = -3, the result is -16.6667
* for denom = -2, the result is -25
* for denom = -1, the result is -50
* Execption from thread: Division by zero!
* ^C
*
* [Explain]
* The problem you have just seen is one type of deadlock, which causes a program to freeze because
* one thread does not release the lock on the mutex while all other threads are waiting for access indefinitely.
*/ | 27.902439 | 113 | 0.625 | [
"vector"
] |
ee47d69dfdb57eee68613dd779e5104a9bb92f19 | 3,260 | cpp | C++ | src/qt/setrecovery.cpp | maxmaxj/ipchain | 99c1943ca65fd4acdef5b4eb5e75c4bee3d59365 | [
"MIT"
] | 34 | 2018-01-25T10:29:35.000Z | 2021-04-22T18:40:40.000Z | src/qt/setrecovery.cpp | joshuabond/ipchain | 5bd6792b1754890fae6648bec9d60519b55406cd | [
"MIT"
] | 9 | 2018-07-25T09:41:40.000Z | 2021-03-05T16:13:01.000Z | src/qt/setrecovery.cpp | joshuabond/ipchain | 5bd6792b1754890fae6648bec9d60519b55406cd | [
"MIT"
] | 11 | 2018-01-28T03:02:44.000Z | 2022-01-09T04:26:23.000Z | #include "setrecovery.h"
#include "ui_setrecovery.h"
#include <QFileInfo>
#include <QFileDialog>
#include "walletmodel.h"
#include "log/log.h"
#include "intro.h"
#include <QMessageBox>
QString g_CreateWalletFromPath;
SetRecovery::SetRecovery(QWidget *parent) :
QWidget(parent),
ui(new Ui::SetRecovery),walletModel(NULL)
{
ui->setupUi(this);
ui->lineEdit_pwd->hide();
ui->label_pwd->hide();
ui->frame->hide();
ui->label_error->setText(tr(""));
}
SetRecovery::~SetRecovery()
{
delete ui;
}
void SetRecovery::on_pushButton_back_pressed()
{
Q_EMIT back();
}
void SetRecovery::on_pushButton_select_pressed()
{
ui->label_error->setText(tr(""));
QString file_full, file_name, file_path;
QFileInfo fi;
file_full = QFileDialog::getOpenFileName(this);
if(file_full == "")
{
return;
}
fi = QFileInfo(file_full);
file_name = fi.fileName();
file_path = fi.absolutePath();
m_file_path = file_path;
m_file_full = file_full;
ui->label_filename->setText(file_name);
}
void SetRecovery::on_pushButton_import_pressed()
{
if(m_file_full.isEmpty())return;
std::cout<<m_file_full.toStdString()<<" "<<m_desPath.toStdString()<<std::endl;
if(!copyFileToPath(m_file_full,m_desPath,1))
{
QLocale locale;
if( locale.language() != QLocale::Chinese )
{
QMessageBox::information(NULL, "IPC", "recovery failed.", QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes);
}
else{
QMessageBox::information(NULL, "IPC", "恢复失败.", QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes);
}
}else{
g_CreateWalletFromPath = m_file_full;
QString unionpath = QString(Intro::m_datapath.c_str());
unionpath+="/unionaddress.ini";
m_file_path+="/unionaddress.ini";
copyFileToPath(m_file_path,unionpath,1);
Q_EMIT next();
}
}
void SetRecovery::setWalletModel(WalletModel * model)
{
walletModel = model;
}
bool SetRecovery::copyFileToPath(QString sourceDir ,QString toDir, bool coverFileIfExist)
{
toDir.replace("\\","/");
if (sourceDir == toDir){
printf("sourceDir == toDir\n");
return true;
}
if (!QFile::exists(sourceDir)){
printf("exists\n");
return false;
}
QDir *createfile = new QDir;
bool exist = createfile->exists(toDir);
if (exist){
if(coverFileIfExist){
createfile->remove(toDir);
}
}
printf("%s %s \n",sourceDir.toStdString().c_str(),toDir.toStdString().c_str());
if(!QFile::copy(sourceDir, toDir))
{
printf("false\n");
return false;
}
return true;
}
bool SetRecovery::isDirExist(QString fullPath)
{
QDir dir(fullPath);
if(dir.exists())
{
return true;
}
else
{
bool ok = dir.mkdir(fullPath);
return ok;
}
}
void SetRecovery::setDestSourcePath(QString path)
{
m_desPath = path;
isDirExist(m_desPath);
if("IPChain" != m_desPath.right(7))
m_desPath += "/IPChain";
isDirExist(m_desPath);
if(Intro::m_clienttype == "test"){
m_desPath+="/testnet3";
isDirExist(m_desPath);
}
m_desPath += "/wallet.dat";
}
| 23.120567 | 124 | 0.621166 | [
"model"
] |
ee49da506c36cab9a610da795298f9631403b285 | 14,076 | hpp | C++ | include/SSDK/Archive/fileinfo.hpp | djc80s/c-cpp_study | 3ea8289c358a2b732524ab391aa87c4a8fc0b6a7 | [
"BSD-2-Clause"
] | null | null | null | include/SSDK/Archive/fileinfo.hpp | djc80s/c-cpp_study | 3ea8289c358a2b732524ab391aa87c4a8fc0b6a7 | [
"BSD-2-Clause"
] | null | null | null | include/SSDK/Archive/fileinfo.hpp | djc80s/c-cpp_study | 3ea8289c358a2b732524ab391aa87c4a8fc0b6a7 | [
"BSD-2-Clause"
] | null | null | null | #ifndef FILEINFO_HPP
#define FILEINFO_HPP
#include <string>
#include <vector>
#include <qfileinfo.h>
#include <QFile>
#include <QString>
#include <QDir>
#include "../Exception/customexception.hpp"
namespace SSDK
{
namespace Archive
{
/**
* @brief FileInfo类为工具类
* 参考:
* 参照QFileInfo,QDir,QFile封装为FileInfo
*
* FileInfo基本操作:
* 1.获取文件当前文件或目录信息
* (1).获取当前路径类型,可以获得是文件类型,文件夹类型,链接文件,不合法的路径
* (2).判断当前路径所代表的文件或目录是否正确,意味着路径是否正确
* (3).获取当前路径
* (4).获取父目录路径
* (5).获取当前路径下带扩展名的文件名称
* (6).获取当前路径下不带扩展名的文件名称
* (7).获得绝对路径静态方法
* (8).获取相对路径静态方法
* (9).判断当前文件是否被其它对象进行I/O操作
* 2.获取子文件信息
* (1).获取文件夹内的所有子文件和文件夹信息(不包括子文件夹内的文件信息)
* (2).获取当前文件夹内的所有文件及文件夹信息,可以迭代获取子文件夹内的文件信息
* 3.文件或目录操作方法
* (1).删除文件和文件夹,至于哪一种,依据是当前路径是文件还是目录
* (2).拷贝操作,将当前的文件或者文件夹拷贝到指定目录下
*
*
* @author vincent
* @version 1.00 2017-05-09 vincent
* note: done
*/
class FileInfo
{
public:
//>>>----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//enum
/**
* @brief The FileInfoType enum
* 文件信息类型,有文件,文件夹,链接文件,非法路径
*/
enum FileInfoType
{
FILE,
DIRECTORY,
SYMLINK,
ILLEGAL
};
//<<<----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//>>>----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//constructor & deconstructor
/**
* @brief FileInfo
* 构造函数
* @param srcPath
* 传入一个地址字符串
*/
FileInfo(const std::string& srcPath) ;
FileInfo(const QString& srcPath) ;
/**
* @brief FileInfo
* 拷贝构造函数,拷贝FileInfo类型对象
* @param fileInfo
* 一个FileInfo类型对象
*/
FileInfo(const FileInfo& fileInfo);
/**
* @brief FileInfo
* 右值拷贝构造函数
* @param fileInfo
*/
FileInfo(FileInfo &&fileInfo);
/**
* @brief FileInfo
* 析构函数
*/
virtual~FileInfo();
//<<<----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//>>>----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//operator override functions
/**
* @brief operator =
* 重载"="
* @param fileInfo
* 一个FileInfo类型对象
* @return
* 返回FileInfo类型
*/
FileInfo& operator =(const FileInfo& fileInfo);
/**
* @brief operator =
* 右值重载"="
* @param fileInfo
* 一个FileInfo类型对象
* @return
* 返回FileInfo类型
*/
FileInfo& operator =(FileInfo&& fileInfo);
//<<<----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//>>>----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//get file information functions
/**
* @brief fileInfoType
* 判断是文件,目录,链接还是一个不合法路径, 具体见FileInfoType的定义
*
* @return
* 返回类型枚举
*/
FileInfoType fileInfoType() const;
static FileInfoType fileInfoType(const std::string& srcPath) ;
static FileInfoType fileInfoType(const QString& srcPath) ;
/**
* @brief exists
* 判断当前路径目录或文件是否存在
* @return
* 返回true为存在,反之无
*/
bool exists() const;
static bool exists(const std::string& srcPath) ;
static bool exists(const QString& srcPath) ;
/**
* @brief isUsed
* 判断当前文件是否正在进行I/O操作
* @return
* 返回false为没有被占用,返回true为正在进行I/O操作
*/
bool isUsed() const;
static bool isUsed(const std::string& srcPath) ;
static bool isUsed(const QString& srcPath) ;
/**
*注意:
* 1.因为该类返回的所有路径都是通过内部调用QFileInfo获取的, 其返回的都是QString类型, 如果这里的函数返回
* string的话, 一旦外部需要QString类型的, 又要转一道影响效率, 所以该类返回所有路径全是QString类型, 如果
* 外部需要string的话, 自己调用toStdString()函数
*
* 2.除非是像getAbsolutePath/getRelativePath这类明确要求绝对路径还是相对路径的函, 否则的话全部根据构造的
* 时候传入的路径类型确定, 传入的路径是相对路径返回就是相对路径, 传入的是绝对路径就返回绝对路径
*/
/**
* @brief path
* 获取当前路径
* @return
* 返回值为QString类型,且不可修改
*/
const QString path() const;
/**
* @brief getParentFileInfoPath
* 获取父目录路径
* @return
* 返回值QString类型,且不可修改
*/
const QString getParentPath()const;
/**
* @brief getNameWithExtension
* 获取带扩展名的文件名称,如路径为/home/vincent/bin/a.txt,将返回a.txt
* @return
* 返回值为string类型,且不可修改
*/
const QString getNameWithExtension()const;
/**
* @brief getNameWithoutExtension
* 得到不带扩展名的文件名
* @return
* 返回string类型,且不可修改
*/
const QString getNameWithoutExtension()const;
/**
* @brief getAbsolutePath
* 获取绝对路径的静态方法
* @param srcPath
* 待转换的源路径
* @return
*/
static const QString getAbsolutePath(const std::string &srcPath);
/**
* @brief getAbsolutePath
* 重载getAbsolutePath方法,实现对传入QString的支持
* @param srcPath
* 待转换的源路径
* @return
*/
static const QString getAbsolutePath(const QString &srcPath);
/**
* @brief getRelativePath
* 获取相对路径的静态方法
* @param srcPath
* 待转换的源路径
* @return
*/
static const QString getRelativePath(const std::string &srcPath);
/**
* @brief getRelativePath
* 重载getRelativePath,实现对传入QString的支持
* @param srcPath
* 待转换的源路径
* @return
*/
static const QString getRelativePath(const QString &srcPath);
//<<<----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//>>>----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//traverse children fileInfo functions
/**
* @brief getChildren
* 获得当前目录下的所有子文件及子目录
* @return
* 返回一个FileInfo*类型的vector容器
*/
const std::vector<FileInfo>& getChildren();
/**
* @brief getChildrenRecursively
* 获取当前目录下的所有文件和文件夹,包括子目录下的文件
* 迭代获取所有文件
* @return
* 返回一个FileInfo*类型的vector容器
*/
const std::vector<FileInfo> getChildrenRecursively();
//<<<----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//>>>----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// operation functions
/**
* @brief remove
* 移除当前文件或者文件夹
* @return
* 返回true为移除成功,反之无
*/
bool remove() const;
/**
* @brief copyTo
* 将当前文件copy到指定路径
* @param destDir
* 目标文件路径,或者是目录
* @param isCover
* true为覆盖目标文件,false是不执行覆盖操作
* @return
* 返回true为复制成功,返回false将复制失败
*/
bool copyTo(std::string destDir,bool isCover);
//<<<----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
private:
//>>>----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//member variant
/**
* @brief m_childrenFileInfo
* 所有的子对象
* 1.如果当前路径目录的话,那么获取仅仅在该目录下的子目录及对应的文件
* 2.如果当前路径是文件的话,返回为空
* 3.带目录结构的vector
*/
std::vector<FileInfo> m_childrenFileInfo;
/**
*FileInfo内部调用了一些Qt中关于QFileInfo的函数, 所有这里封装了QFileInfo的嵌入实例对象
*/
QFileInfo m_qFileinfo;//涉及到路径的获取, 是否存在的判断, 扩展名等信息
//<<<----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//>>>----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//traverse children fileinfo functions
/**
* @brief getFileList
* 内部调用函数,获得当前目录下的文件列表
* @param srcPath
* srcPath为QString类型,目录路径
* @return
* 返回值为一个FileInfo指针类型的vector容器的向量表
*/
void setFileList(const QString& srcPath);
/**
* @brief getFileListRescursively
* 内部调用函数,迭代获取目录及文件
* @param srcPath
* srcPath为文件夹路径
* @return
*/
QFileInfoList getFileListRescursively(QString &srcPath);
//<<<----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//>>>----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// operation functions
/**
* @brief copySimpleFile
* 内调用的拷贝单个文件方法
* @param destPath
* 要拷贝到目录下的目标路径
* @param isCover
* 选择是否被覆盖,true为选择覆盖,false为不覆盖
* @return
* 返回true复制文件成功,反之失败
*/
bool copyFileTo(const QString& destPath, bool isCover) const;
/**
* @brief copyDir
* 内部调用的拷贝目录方法
* @param srcDirPath
* 原目录路径
* @param destDirPath
* 目标目录的路径
* @param isCover
* 选择是否覆盖,true为选择覆盖,false为不覆盖
* @return
* 返回true为复制成功,false复制失败
*/
bool copyDirTo(const QString &srcDirPath,const QString &destDirPath,bool isCover) const;
//<<<----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
};//End of class FileInfo
}//End of namespace Archive
}//End of namespace SSDK
#endif // FILEINFO_HPP
| 37.940701 | 225 | 0.305485 | [
"vector"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.