hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
109
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
48.5k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
c761106c64a8403db0b6e91db714072e0e971750
53
cpp
C++
swimps-test/benchmark/source/swimps-benchmark-test.cpp
OMGtechy/swimps
5ad9643eb94347042aa2d29d834543c3df3732aa
[ "MIT" ]
null
null
null
swimps-test/benchmark/source/swimps-benchmark-test.cpp
OMGtechy/swimps
5ad9643eb94347042aa2d29d834543c3df3732aa
[ "MIT" ]
43
2020-05-29T22:33:50.000Z
2021-05-05T23:22:33.000Z
swimps-test/benchmark/source/swimps-benchmark-test.cpp
OMGtechy/swimps
5ad9643eb94347042aa2d29d834543c3df3732aa
[ "MIT" ]
2
2020-05-29T20:50:47.000Z
2020-11-15T18:50:55.000Z
#include "swimps-benchmark-test.h" BENCHMARK_MAIN();
17.666667
34
0.773585
OMGtechy
c7614542eea1aa3765544a873af7c4bef129aa9a
1,048
cpp
C++
src/CaseCreator/UIComponents/LocationTab/LocationZoomedViewsPage.cpp
Thisisderpys/my-little-investigations
0689f2ca3e808ba39864f024280abd2e77f8ad20
[ "MIT" ]
41
2015-01-24T17:33:16.000Z
2022-01-08T19:36:40.000Z
src/CaseCreator/UIComponents/LocationTab/LocationZoomedViewsPage.cpp
Thisisderpys/my-little-investigations
0689f2ca3e808ba39864f024280abd2e77f8ad20
[ "MIT" ]
15
2015-01-05T21:00:41.000Z
2016-10-18T14:37:03.000Z
src/CaseCreator/UIComponents/LocationTab/LocationZoomedViewsPage.cpp
Thisisderpys/my-little-investigations
0689f2ca3e808ba39864f024280abd2e77f8ad20
[ "MIT" ]
6
2016-01-14T21:07:22.000Z
2020-11-28T09:51:15.000Z
#include "LocationZoomedViewsPage.h" #include <QVBoxLayout> LocationZoomedViewsPage::LocationZoomedViewsPage(QWidget *parent) : Page<Location>(parent) { isActive = false; QVBoxLayout *pMainLayout = new QVBoxLayout(); pZoomedViewManipulator = new ListManipulator<ZoomedView>(); pMainLayout->addWidget(pZoomedViewManipulator); setLayout(pMainLayout); } void LocationZoomedViewsPage::Init(Location *pObject) { Page<Location>::Init(pObject); pZoomedViewManipulator->SetParentObject(pObject); } void LocationZoomedViewsPage::Reset() { pZoomedViewManipulator->Reset(); } bool LocationZoomedViewsPage::Undo() { return pZoomedViewManipulator->Undo(); } bool LocationZoomedViewsPage::Redo() { return pZoomedViewManipulator->Redo(); } bool LocationZoomedViewsPage::GetIsActive() { return isActive; } void LocationZoomedViewsPage::SetIsActive(bool isActive) { if (this->isActive != isActive) { this->isActive = isActive; pZoomedViewManipulator->SetIsActive(isActive); } }
20.153846
65
0.734733
Thisisderpys
c7662bee86679f84f906ba38088b6d8038cffbb2
17,218
cpp
C++
Misc/UnusedCode/RSLibAndTests/RSLibTests/Code/Experiments/Misc/PlotterExperiments.cpp
RobinSchmidt/RS-MET-Preliminary
6c01cbaad7cce3daa3293c444dd9e4b74e5ebfbe
[ "FTL" ]
34
2017-04-19T18:26:02.000Z
2022-02-15T17:47:26.000Z
Misc/UnusedCode/RSLibAndTests/RSLibTests/Code/Experiments/Misc/PlotterExperiments.cpp
RobinSchmidt/RS-MET-Preliminary
6c01cbaad7cce3daa3293c444dd9e4b74e5ebfbe
[ "FTL" ]
307
2017-05-04T21:45:01.000Z
2022-02-03T00:59:01.000Z
Misc/UnusedCode/RSLibAndTests/RSLibTests/Code/Experiments/Misc/PlotterExperiments.cpp
RobinSchmidt/RS-MET-Preliminary
6c01cbaad7cce3daa3293c444dd9e4b74e5ebfbe
[ "FTL" ]
4
2017-09-05T17:04:31.000Z
2021-12-15T21:24:28.000Z
//// code has become obsolete - delete soon // //#include "PlotterExperiments.h" // //void createDataFiveFunctions(int N, double xMin, double xMax, double *x, double *y1, double *y2, // double *y3, double *y4, double *y5) //{ // rsFillWithRangeLinear(x, N, xMin, xMax); // for(int n = 0; n < N; n++) // { // y1[n] = sin(x[n]); // y2[n] = cos(x[n]); // y3[n] = y1[n] + y2[n]; // y4[n] = tanh(x[n]); // y5[n] = 1 / (1 + x[n]*x[n]); // } //} // //void testDataPlot2() //{ // // a simple plot of 5 datasets representing functions using the default settings // // // create data: // static const int N = 200; // number of data points // double x[N], y1[N], y2[N], y3[N], y4[N], y5[N]; // createDataFiveFunctions(N, -10, +10, x, y1, y2, y3, y4, y5); // // // plot data: // GNUPlotter p; // p.addData(N, x, y1, y2, y3, y4, y5); // p.plot(); // // write convenience function, so we can do this with one line // // int dummy = 0; //} // //void testIntVector() //{ // // create the Fibonacci sequence in y, write the index into x: // int N = 10; // vector<int> x, y; // x.resize(N); // y.resize(N); // x[0] = y[0] = 0; // x[1] = y[1] = 1; // for(int i = 2; i < N; i++) // { // x[i] = i; // y[i] = y[i-1] + y[i-2]; // } // // GNUPlotter p; // //p.addData(x, y); // p.addData(y); // p.setGraphStyles("points pt 7 ps 1"); // p.setGrid(); // p.plot(); // // int dummy = 0; //} // //void testStyleSetup2() //{ // // create data: // static const int N = 35; // number of data points per set // double x[N], y1[N], y2[N], y3[N], y4[N], y5[N]; // createDataFiveFunctions(N, -5, +5, x, y1, y2, y3, y4, y5); // // // create plotter object, pass the data: // GNUPlotter p; // p.addData(N, x, y1, y2, y3, y4, y5); // // // set up the plotter: // p.setLegends("sin(x)", "cos(x)", "sin(x)+cos(x)"); // graphs 1,2,3 have legends // p.setGraphColors("800000", "008000", "000080"); // 3 colors, used cyclically // p.setGraphStyles("lines lw 2", "points pt 6 ps 2"); // styles for graphs 1 and 2 // p.addGraphStyles("impulses lw 2", "boxes lw 1.5"); // styles for graphs 3 and 4 // p.addGraphStyles("linespoints pt 7 ps 1"); // style for graph 5 // p.setSize(800, 400); // pixel size for plot // p.setRange(-4, +4, -1.6, +1.6); // range for x- and y-axis // p.setAxisLabels("x-axis", "y-axis"); // labels for the axes // p.setTitle("Plotter Demo"); // caption for the plot // p.setGrid(true, false, false, true); // // the fine grid does not yet work - maybe the tics must be specified before? via // // set x2tics, etc. // //p.setRange(0.1, 5, 0.1, +1.6); p.setLogScale("xy", 2); // test // // // plot: // p.plot(); //} // //void testMultiColumn2() //{ // static const int N = 30; // maximum number of datapoints // double d[17][N]; // data - columns of N values // // double a = 0.3; // multplier for the sine's argument // double b = 1.0; // y-axis offset between datasets // // // create the data for the datasets: // int i; // for(i = 0; i < N; i++) // { // double x = i; // double y = sin(a*x); // // d[0][i] = x; // x for all datasets (except 1-column which has implicit x) // // d[1][i] = y; // y for 1-column dataset // // y += b; // d[2][i] = y; // y for 2-column dataset // // y += b; // d[3][i] = y; // y for 3-column dataset (for yerrorlines) // d[4][i] = 0.3; // y-delta // // y += b; // d[5][i] = y; // y for 4-column dataset (for yerrorlines) // d[6][i] = y - 0.4; // y min // d[7][i] = y + 0.2; // y max // // y += b; // d[8][i] = y; // box min for 5-column dataset (for candlesticks) // d[9][i] = y - 0.2; // whisker min // d[10][i] = y + 0.4; // whisker max // d[11][i] = y + 0.2; // box max // // y += b; // d[12][i] = y; // y for 6-column dataset (for xyerrorlines) // d[13][i] = x - 0.4; // x min // d[14][i] = x + 0.5; // x max // d[15][i] = y - 0.2; // y min // d[16][i] = y + 0.3; // y max // } // // // Create plotter and add datasets. We add the 1, 2 and 3 column datasets at once with a single // // call and then add the 4, 5 and6 column datasets each seperately with their own call. Note that // // the datasets need not have the same length (i.e. the same number of rows). This is // // demonstrated by shortening the 3-column dataset by 5 rows: // GNUPlotter p; // //p.addDataMultiColumn(N, 1, d[1], N, 2, d[0], d[2], N-5, 3, d[0], d[3], d[4], 0); // 1,2,3 columns // //p.addDataMultiColumn(N, 4, d[0], d[5], d[6], d[7], 0); // 4 columns // //p.addDataMultiColumn(N, 5, d[0], d[8], d[9], d[10], d[11], 0); // 5 columns // //p.addDataMultiColumn(N, 6, d[0], d[12], d[13], d[14], d[15], d[16], 0); // 6 columns // // p.addDataMultiColumn(N, 1, d[1]); // 1 column // p.addDataMultiColumn(N, 2, d[0], d[2]); // 2 columns // p.addDataMultiColumn(N, 3, d[0], d[3], d[4]); // 3 columns // p.addDataMultiColumn(N, 4, d[0], d[5], d[6], d[7]); // 4 columns // p.addDataMultiColumn(N, 5, d[0], d[8], d[9], d[10], d[11]); // 5 columns // p.addDataMultiColumn(N, 6, d[0], d[12], d[13], d[14], d[15], d[16]); // 6 columns // // // // set up styles and plot: // p.setRange(0, 30, -2, 7); // //p.setGraphStyles("lines", "lines", "yerrorlines", "yerrorlines", "candlesticks", // // "xyerrorlines", 0); // // p.setLegends("lines", "linespoints", "yerrorlines", "yerrorlines", "candlesticks", // "xyerrorlines"); // // try to place that bottom right // // p.setGraphStyles("lines", "linespoints", "yerrorlines", "yerrorlines", "candlesticks", // "xyerrorlines"); // p.plot(); //} // //void testSurface2() //{ // static const int Nx = 41; // number of x-values // static const int Ny = 41; // number of y-values // // double xMin = -10; // double xMax = +10; // double yMin = -10; // double yMax = +10; // // double x[Nx]; // double y[Ny]; // double z1[Nx][Ny], z2[Nx][Ny]; // // int i, j; // double xi, yj; // double *z1p[Nx], *z2p[Nx]; // for(i = 0; i < Nx; i++) // { // z1p[i] = &z1[i][0]; // z2p[i] = &z2[i][0]; // } // // for(i = 0; i < Nx; i++) x[i] = xMin + i*(xMax-xMin)/(Nx-1); // for(j = 0; j < Ny; j++) y[j] = yMin + j*(yMax-yMin)/(Ny-1); // for(i = 0; i < Nx; i++) // { // xi = x[i]; // for(j = 0; j < Ny; j++) // { // yj = y[j]; // z1[i][j] = exp(-0.03*(xi*xi+yj*yj)); // 2D Gaussian bell // z2[i][j] = 2 + 1 / (1+0.1*(xi*xi+yj*yj)); // 2D Butterworth bell shifted // } // } // // GNUPlotter p; // p.addDataSurface(Nx, Ny, x, y, z1p); // //p.addDataSurface(Nx, Ny, x, y, z2p); // works, but doesn't look nice // // p.setGrid(); // p.addCommand("set hidden3d"); // add function removeHiddenLines or setHiddenLineRemoval // p.plot(true); // // // todo check out how to do contour lines (or maybe fills), etc. //} // // //// here is a good tutorial: //// http://lowrank.net/gnuplot/index-e.html // //// demo for various line styles: //// http://gnuplot.sourceforge.net/demo_4.6/dashcolor.html // //// for polar grids //// http://stackoverflow.com/questions/6772135/how-to-get-a-radialpolar-plot-using-gnu-plot // //// for 3D plot, manual, pages 65,115,184 //// http://lowrank.net/gnuplot/datafile-e.html // // //// for example plots: //// -Integer plot: fibonacci sequence (or prime numbers) - maybe we can have a special int plot //// that writes the values above the datapoints (centered) - but maybe this is something for a //// subclass that deals specifically with integer plots //// -Gaussian bells with diffent mu, sigma - also demonstrates how to use greek letters //// -square and/or saw wave with linear, cubic and sinc interploation - use points and impulses for //// the discrete time data, lines of different colors for the interpolants //// -pole/zero plot of an elliptic bandpass in the z-domain //// -for log/log plots: familiy of Butterworth magnitude responses //// -maybe with phase-plots in the same plot (angles written on right y-axis, we need an expression //// for the (unwrapped) phase //// -3D: 2D Gaussian, z- or s-domain pole/zero "landscapes", clouds of points (maybe using gaussian //// distributions) //// -spectrogram-plots, phasogram-plots // // ////================================================================================================= //// old: // //std::vector<std::string> charPointersToStringVector(int numStrings, ...) //{ // std::vector<std::string> v; // va_list argList; // va_start(argList, numStrings); // for(int i = 0; i < numStrings; i++) // v.push_back(va_arg(argList, const char*)); // va_end(argList); // return v; //} // //std::vector<std::string> stringList(int numStrings, const char *string1, ...) //{ // std::vector<std::string> v; // v.push_back(string1); // va_list argList; // va_start(argList, numStrings); // for(int i = 1; i < numStrings; i++) // v.push_back(va_arg(argList, const char*)); // va_end(argList); // return v; //} // //void testVariableArgumentList() //{ // //std::vector<std::string> v = charPointersToStringVector(3, "s1", "s2", "s3"); // // std::vector<std::string> v = stringList(3, "s1", "s2", "s3"); // int dummy = 0; //} // //void testDataPlot1() //{ // // a simple plot of 5 datasets representing functions using the default settings // // // create data: // static const int N = 1000; // number of data points // double x[N], y1[N], y2[N], y3[N], y4[N], y5[N]; // createDataFiveFunctions(N, -10, +10, x, y1, y2, y3, y4, y5); // // // plot data: // Plotter::plotFunctionData(5, N, x, y1, y2, y3, y4, y5); //} // //void testColorSetup() //{ // // a simple plot of 5 datasets representing functions using custom colors // // // create data: // static const int N = 1000; // number of data points // double x[N], y1[N], y2[N], y3[N], y4[N], y5[N]; // createDataFiveFunctions(N, -10, +10, x, y1, y2, y3, y4, y5); // // // create plotter object, pass the data: // Plotter plt; // plt.setFunctionData(5, N, x, y1, y2, y3, y4, y5); // // // set up the colors (we specify only 3 colors but have 5 datasets, so we will see how the // // defined colors will be used cyclically): // std::vector<std::string> colors; // colors.push_back("770000"); // colors.push_back("007700"); // colors.push_back("000077"); // plt.setGraphColors(colors); // // // alternatively to the code above, we could use the more convenient form: // plt.setGraphColors(3, "770000", "007700", "000077"); // // // plot: // plt.plot(); //} // //void testStyleSetup() //{ // // rename function to demoPlotterSetup (or similar) // // // create data: // static const int N = 35; // number of data points per set // double x[N], y1[N], y2[N], y3[N], y4[N], y5[N]; // createDataFiveFunctions(N, -5, +5, x, y1, y2, y3, y4, y5); // // // create plotter object, pass the data: // Plotter p; // p.setFunctionData(5, N, x, y1, y2, y3, y4, y5); // // // set up the plotter: // p.setSize(800, 400); // p.setRange(-4, +4, -1.6, +1.6); // p.setGraphColors(3, "770000", "007700", "000077"); // p.setGraphStyles(5, "lines lw 2", "points pt 6 ps 2", "impulses lw 2", "boxes lw 1.5", // "linespoints pt 7 ps 1"); // p.setGraphTitles(2, 1, "sin(x)", 3, "sin(x)+cos(x)"); // p.setAxisLabels("x", "y"); // p.setTitle("Plotter Demo"); // // // to do: // // p.addAnnotation("set arrow from 1,1 to 0.5,0.5"); // // p.addAnnotation("set label \"Label 1\" at 2,1"); // // // // plot: // p.plot(); // // // move to function testPointTypes // //plt.setGraphStyles(5, "points pt 1", "points pt 2", "points pt 3", "points pt 4", "points pt 5"); // //plt.setGraphStyles(5, "points pt 6", "points pt 7", "points pt 8", "points pt 9", "points pt 10"); // // // pointtypes: 1: +, 2: crosses, 3: *, 4: squares, 5: filled squares, 6: circles, // // 7: filled circles, 8: triangle up, 9: filled triangle up, 10: triangle down, // // // move to function testLineStyles: // //plt.setGraphStyles(4, "lines", "lines lw 2", "points pt 6 ps 2", "linespoints pt 7 ps 1"); // //plt.setGraphStyles(5, "lines", "points pt 2", "impulses", "boxes", "linespoints pt 7 ps 1"); // //plt.setGraphStyles(4, "lines lt 1", "lines lt 2", "lines lt 3", "lines lt 3"); // // should create dashed lines but doesn't work //} // //void testMultiColumn() //{ // // We create datasets with different numbers of columns 1...6 and plot each dataset with a // // style that is appropriate for that number of columns. The datasets will be offsetted sine // // functions plus some "error tolerances" where applicable. // // static const int numSets = 6; // number of data sets // int numPoints[numSets] = { 25, 20, 30, 23, 27, 28 }; // number of data points per set // double a = 0.3; // multplier for the sine's argument // double offset = 1.0; // y-axis offset between datasets // int i, j, k; // loop indices // double x, y, z1, z2, z3, z4; // coordinates // // // create data vector and set up the dimensionalities: // std::vector<std::vector<std::vector<double>>> data; // data.resize(numSets); // for(i = 0; i < numSets; i++) // { // data[i].resize(numPoints[i]); // for(j = 0; j < data[i].size(); j++) // data[i][j].resize(i+1); // } // // // create dataset 1 (for plot with lines): // for(j = 0; j < data[0].size(); j++) // { // x = j; // x (implicit - not stored in dataset) // y = sin(a*x); // y // data[0][j][0] = y; // } // // // create dataset 2 (for plot with lines): // for(j = 0; j < data[1].size(); j++) // { // x = j; // x // y = sin(a*x) + 1*offset; // y // data[1][j][0] = x; // data[1][j][1] = y; // } // // // create dataset 3 (for plot with yerrorlines): // for(j = 0; j < data[2].size(); j++) // { // x = j; // x // y = sin(a*x) + 2*offset; // y // z1 = 0.2; // y delta // data[2][j][0] = x; // data[2][j][1] = y; // data[2][j][2] = z1; // } // // // create dataset 4 (for plot with yerrorlines): // for(j = 0; j < data[3].size(); j++) // { // x = j; // x // y = sin(a*x) + 3*offset; // y // z1 = y - 0.3; // y min // z2 = y + 0.2; // y max // data[3][j][0] = x; // data[3][j][1] = y; // data[3][j][2] = z1; // data[3][j][3] = z2; // } // // // create dataset 5 (for plot with candlesticks): // for(j = 0; j < data[4].size(); j++) // { // x = j; // x // y = sin(a*x) + 4*offset; // box min // z1 = y - 0.2; // whisker min // z2 = y + 0.4; // whisker max // z3 = y + 0.2; // box max // data[4][j][0] = x; // data[4][j][1] = y; // data[4][j][2] = z1; // data[4][j][3] = z2; // data[4][j][4] = z3; // } // // // create dataset 5 (for plot with xyerrorlines): // for(j = 0; j < data[5].size(); j++) // { // x = j; // x // y = sin(a*x) + 5*offset; // y // z1 = x - 0.4; // x min // z2 = x + 0.5; // x max // z3 = y - 0.2; // y min // z4 = y + 0.3; // y max // data[5][j][0] = x; // data[5][j][1] = y; // data[5][j][2] = z1; // data[5][j][3] = z2; // data[5][j][4] = z3; // data[5][j][5] = z4; // } // // // create plotter, set up styles, pass the data and plot: // Plotter p; // p.setRange(0, 30, -2, 7); // p.setGraphStyles(6, "lines", "lines", "yerrorlines", "yerrorlines", "candlesticks", // "xyerrorlines"); // p.setData(data); // p.plot(); //} // // //void testSurface() //{ // // does not yet work - see comment below // // static const int Nx = 10; // number of x-values // static const int Ny = 15; // number of y-values // static const int N = Nx*Ny; // number of datapoints // // double xMin = -10; // double xMax = +10; // double yMin = -10; // double yMax = +10; // // int i, j, k; // double x, y, z; // // std::vector<std::vector<std::vector<double>>> data; // data.resize(1); // data[0].resize(N); // for(j = 0; j < data[0].size(); j++) // data[0][j].resize(3); // // for(j = 0; j < Nx; j++) // { // x = j; // ...later scale // // for(k = 0; k < Ny; k++) // { // y = k; // //z = 1 / (1+x*y*x*y); // z = 1 / (1+x*x+y*y); // i = j*Ny+k; // index for x value // data[0][i][0] = x; // data[0][i][1] = y; // data[0][i][2] = z; // // int dummy = 0; // } // } // // int dummy = 0; // // // for a 3D plot, we must seperate the blocks of data (for one particular x value) by single // // blank lines // // introduce a blockSizes array for blocking the data inside each dataset // // Plotter p; // p.setSurfaceMode(true); // //p.addCommand("set contour"); // p.setData(data); // p.plot(); //} // // //
32.671727
104
0.52387
RobinSchmidt
c768dcac9a2dec0d965eae3c4b319b028ec14f9d
2,640
cpp
C++
src/Emulators/nestopiaue/core/api/NstApiRewinder.cpp
slajerek/RetroDebugger
e761e4f9efd103a05e65ef283423b142fa4324c7
[ "Apache-2.0", "MIT" ]
34
2021-05-29T07:04:17.000Z
2022-03-10T20:16:03.000Z
src/Emulators/nestopiaue/core/api/NstApiRewinder.cpp
slajerek/RetroDebugger
e761e4f9efd103a05e65ef283423b142fa4324c7
[ "Apache-2.0", "MIT" ]
6
2021-12-25T13:05:21.000Z
2022-01-19T17:35:17.000Z
src/Emulators/nestopiaue/core/api/NstApiRewinder.cpp
slajerek/RetroDebugger
e761e4f9efd103a05e65ef283423b142fa4324c7
[ "Apache-2.0", "MIT" ]
6
2021-12-24T18:37:41.000Z
2022-02-06T23:06:02.000Z
//////////////////////////////////////////////////////////////////////////////////////// // // Nestopia - NES/Famicom emulator written in C++ // // Copyright (C) 2003-2008 Martin Freij // // This file is part of Nestopia. // // Nestopia is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // Nestopia is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Nestopia; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // //////////////////////////////////////////////////////////////////////////////////////// #include <new> #include "../NstMachine.hpp" #include "NstApiMachine.hpp" #include "NstApiRewinder.hpp" namespace Nes { namespace Api { #ifdef NST_MSVC_OPTIMIZE #pragma optimize("s", on) #endif Rewinder::StateCaller Rewinder::stateCallback; Result Rewinder::Enable(bool enable) throw() { try { return emulator.tracker.EnableRewinder( enable ? &emulator : NULL ); } catch (Result result) { return result; } catch (const std::bad_alloc&) { return RESULT_ERR_OUT_OF_MEMORY; } catch (...) { return RESULT_ERR_GENERIC; } } bool Rewinder::IsEnabled() const throw() { return emulator.tracker.IsRewinderEnabled(); } bool Rewinder::IsSoundEnabled() const throw() { return emulator.tracker.IsRewinderSoundEnabled(); } void Rewinder::EnableSound(bool enable) throw() { emulator.tracker.EnableRewinderSound( enable ); } Rewinder::Direction Rewinder::GetDirection() const throw() { return emulator.tracker.IsRewinding() ? BACKWARD : FORWARD; } Result Rewinder::SetDirection(Direction dir) throw() { if (emulator.Is(Machine::GAME,Machine::ON)) { if (dir == BACKWARD) return emulator.tracker.StartRewinding(); else return emulator.tracker.StopRewinding(); } return RESULT_ERR_NOT_READY; } void Rewinder::Reset() throw() { if (emulator.Is(Machine::GAME,Machine::ON)) emulator.tracker.ResetRewinder(); } #ifdef NST_MSVC_OPTIMIZE #pragma optimize("", on) #endif } }
25.384615
89
0.619697
slajerek
c76b1d8c95fc16a96df1d9e9a51d0d4bbe013bb5
1,695
cpp
C++
01_current/Vital_Clues/src/main.cpp
r0oland/Baltopia
a772733a73fd54ad837f079b525bf8c7c09712bf
[ "MIT" ]
null
null
null
01_current/Vital_Clues/src/main.cpp
r0oland/Baltopia
a772733a73fd54ad837f079b525bf8c7c09712bf
[ "MIT" ]
null
null
null
01_current/Vital_Clues/src/main.cpp
r0oland/Baltopia
a772733a73fd54ad837f079b525bf8c7c09712bf
[ "MIT" ]
null
null
null
#include "..\lib\vital_lib.cpp" #include "..\lib\iot_lib.cpp" #include "..\include\secrets.h" uint_fast32_t updateIOTInterval = 10000; Iot MyIot(IO_USERNAME,IO_KEY,WIFI_SSID,WIFI_PASS,updateIOTInterval); Vital MyVital(ONE_WIRE_BUS,LCD_ADDRESS,LCD_COLS,LCD_ROWS); DeviceAddress PAD_SENS = {0x28, 0xFF, 0x67, 0x98, 0x90, 0x16, 0x04, 0xFA}; DeviceAddress ROOM_SENS = {0x28, 0x70, 0x56, 0x79, 0xA2, 0x00, 0x03, 0xEF}; DeviceAddress AMB_SENS = {0x28, 0xF9, 0x9D, 0x79, 0xA2, 0x00, 0x03, 0xC1}; //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% void setup(void) { setup_serial(); MyVital.setup_lcd(); MyVital.setup_io_pins(); MyVital.setup_temp_sensor(12); // set resolution for temp sensor MyVital.PadTempSens = &PAD_SENS; MyVital.RoomTempSens = &ROOM_SENS; MyVital.AmbientTempSens = &AMB_SENS; MyVital.get_temp_sensor_address(); // MyIot.check_connection(); // connect to IOT server MyIot.aio.connect(); // wait for a connection while (MyIot.aio.status() < AIO_CONNECTED) { MyVital.V_LCD.print("."); delay(250); } } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% void loop(void) { MyIot.check_connection(); MyVital.control_heat_pads(); MyIot.send_data(MyVital.analTemp, MyVital.padTemp, MyVital.pwmValue, MyVital.roomTemp, MyVital.ambTemp); bool aioConnected = (MyIot.aio.status() == AIO_CONNECTED); MyVital.update_lcd(aioConnected); // FIXME -> replace with proper conn. check MyVital.update_serial(); }
33.9
106
0.585841
r0oland
c775a8a4e05fb4d060f7d55ccab140e9d9af142a
3,044
hpp
C++
utils/stringUtils.hpp
jasonnaldi/htmlvalidator-cpp
80ecd5ac823b685b6490136ed8d289c8ec7477a0
[ "MIT" ]
null
null
null
utils/stringUtils.hpp
jasonnaldi/htmlvalidator-cpp
80ecd5ac823b685b6490136ed8d289c8ec7477a0
[ "MIT" ]
2
2020-10-14T17:58:14.000Z
2020-10-14T18:58:18.000Z
utils/stringUtils.hpp
jasonnaldi/htmlvalidator
80ecd5ac823b685b6490136ed8d289c8ec7477a0
[ "MIT" ]
null
null
null
/* MIT License Copyright (c) 2016 Jason Naldi - direct contact: dev@jasonnaldi.com - web: https://jasonnaldi.com - github: https://github.com/jasonnaldi Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef stringUtils_hpp #define stringUtils_hpp #include <string> #include <vector> namespace stringUtils { /* @brief Given a string `str` and a character `separator`, return an array of substrings of `str`, split by `separator`. @param `str` A string to tokenize. @param `separator` The character to use as a separator. @return std::vector<std::string>. */ std::vector<std::string> tokenize(const std::string &str, char separator); /* @brief Given a string, return the same string but without leading and trailing spaces. Also replaces two or more consecutive white spaces with a single white space. @param `str` A string to trim. @return void. */ void trim(std::string &str); /* @brief Return the line in a string where a pattern first occurs. @param `str` A string to scan @param `pattern` A pattern to seek @return ssize_t. Will be std::string::npos if the pattern was not found. */ ssize_t firstLineOccurrence(const std::string &str, const std::string &pattern); /* @brief Convert a string to lowercase @param `str` A string to convert to lowercase @return std::string */ std::string lowercase(const std::string &str); /** Replace all occurrencies of a string with another string inside a string. @param source The string where to replace occurrencies @param oldStr The string to replace @param newStr The string to replace the old string with @return A string where all occurrencies of oldStr have been replaced by newStr */ std::string replaceAllOccurrencies(const std::string &source, const std::string &oldStr, const std::string &newStr); } #endif /* stringUtils_hpp */
34.202247
120
0.702365
jasonnaldi
c777d7b961ff701321c1270752ebc2a7ecf79abe
10,566
cpp
C++
Listen/upd-example2/Clisten.cpp
righthalfplane/SdrGult
f6a082939d7922c08cef1f53104a84841be80910
[ "MIT" ]
55
2019-12-13T07:32:26.000Z
2022-03-18T13:50:05.000Z
Listen/upd-example2/Clisten.cpp
righthalfplane/SdrGult
f6a082939d7922c08cef1f53104a84841be80910
[ "MIT" ]
27
2019-12-30T11:01:03.000Z
2022-02-10T20:08:08.000Z
Listen/upd-example2/Clisten.cpp
righthalfplane/SdrGult
f6a082939d7922c08cef1f53104a84841be80910
[ "MIT" ]
13
2019-12-10T21:20:38.000Z
2022-03-18T13:50:08.000Z
#include "Clisten.h" #include <cstdio> #include <chrono> #include <thread> #include <complex> #include <iostream> #include <string.h> #include <stdio.h> #include <stdlib.h> #include <liquid/liquid.h> #include <rtaudio/RtAudio.h> // #include <unistd.h> using namespace std; #include <stdlib.h> #include "SocketDefs.h" static int copyl(char *p1,char *p2,long n); int Sleep2(int ms) { std::this_thread::sleep_for(std::chrono::milliseconds(ms)); return 0; } int launchThread(void *data,int (*sageThread)(void *data)) { std::thread(sageThread,data).detach(); return 0; } Listen::Listen() { ncommand=0; Debug=0; buffsize=0; fc = 1e6; f = 760000; channels=2; output=NULL; buff1=NULL; ibuff=-1; fOut=48000; aminGlobal=0.0; amaxGlobal=0.0; gain=0.5; decodemode = MODE_AM; Port=3700; filter.iqSampler=0; filter.iqSampler2=0; filter.demod=0; filter.demodAM=0; pipe=0; binary=0; } Listen::~Listen() { closesocket(clientSocket); } int Listen::freeFilters(struct Filters2 *f) { return 0; } int Listen::setFilters(class Listen *rx,struct Filters2 *f) { return 0; } int Listen::mix(float *buf1,float *buf2) { return 0; } int ListenSocket(void *rxv) { class Listen *l=(class Listen *)rxv; time_t start,total; time_t ship; long size; size=4096*8; l->output=(complex<float> *)malloc(size*sizeof(complex<float>)); FILE *in=NULL; if(!in)in=fopen("junk.raw","wb"); fprintf(stderr,"******************************************************\n"); fprintf(stderr,"** listen 825 - COPYRIGHT 2020-2021. Start **\n"); fprintf(stderr,"******************************************************\n"); start=time(&ship); l->Bytes=0; l->ncommand=0; while(1){ int ret=l->netRead(l->clientSocket,(char *)l->output,size); if(ret > 0)break; fwrite((char *)l->output,size,1,in); fprintf(stderr,"ret %d size %ld\n",ret,size); } if(in)fclose(in); if(l->output)free(l->output); l->output=NULL; l->ibuff= -1; total=time(&ship)-start; if(!total)total=1; fprintf(stderr,"%ld Seconds To Receive %ld Bytes (%ld Bytes/s)\n", (long)total,l->Bytes,(long)(l->Bytes/total)); fprintf(stderr,"******************************************************\n"); fprintf(stderr,"** listen 825 - COPYRIGHT 2020-2021. Done **\n"); fprintf(stderr,"******************************************************\n"); return 1; } /* int launchThread(void *data,int (*sageThread)(void *data)) { std::thread(sageThread,data).detach(); return 0; } */ int Listen::setFrequency(double frequency) { return 0; } int Listen::setCenterFrequency(double frequency,double sampleRate) { return 0; } SOCKET Listen::waitForService(char *name) { serverSocket=startService(name); //fprintf(stderr,"startService %lld\n", serverSocket); addrLen=sizeof(clientSocketAddr); while(1){ int count; int ret; ret=CheckSocket(serverSocket,&count,3000); if(ret <= 0){ fprintf(stderr,"ret %d\n",ret); continue; } fprintf(stderr,"ret %d\n",ret); clientSocket=accept(serverSocket,(struct sockaddr *)&clientSocketAddr, &addrLen); this->ibuff=-2; launchThread((void *)this,ListenSocket); while(this->ibuff != -1){ Sleep2(10); } shutdown(clientSocket,2); close(clientSocket); } return serverSocket; return -1; } SOCKET Listen::startService(char *name) { // if(getPortAndName(name,&hostAddr,&Port))return -1; serverSocket=createService(&Port); if(serverSocket == -1){ fprintf(stderr,"Create Port %d Failed\n",Port); return -1; } return serverSocket; } int Listen::readString(SOCKET clientSocket,char *buff,long nbyte) { return netRead(clientSocket,buff,nbyte); } int Listen::getLong(SOCKET clientSocket,long *n) { unsigned char c[4]; if(readString(clientSocket,(char *)c,4L))return 1; *n = c[0] + ((long)c[1] << 8) + ((long)c[2] << 16) + ((long)c[3] << 24); return 0; } int Listen::readCommand(SOCKET clientSocket,char *buff,long *size) { long n; n=4; if(readString(clientSocket,buff,n))return 1; buff[n]=0; if(getLong(clientSocket,size))return 1; return 0; } //int Listen::ListenSocket(SOCKET clientSocket) //{ // return 0; //} int Listen::netRead(SOCKET clientSocket,char *buff,long n) { long k; int isleep; if(!buff)return 1; // fprintf(stderr,"clientSocket %d netRead %p n %ld\n",clientSocket,buff,n); // Bytes += n; isleep=0; k=n; while(k > 0){ n=k; n=recv(clientSocket,buff,n,0); if(n > 0){ k -= n; buff += n; isleep=0; }else if(n == 0){ if(++isleep > 20){ fprintf(stderr,"netRead Time Out Error\n"); return 1; }else{ Sleep2(10); } }else{ fprintf(stderr,"netRead Error Reading Socket\n"); return 1; } } return 0; } int Listen::CheckSocket(SOCKET serverSocket,int *count,int ms) { struct timeval tv; fd_set fds; FD_ZERO(&fds); FD_SET(serverSocket, &fds); tv.tv_sec = ms/1000; tv.tv_usec = (ms%1000)*1000; int ret = select((int)(serverSocket+1), &fds, NULL, NULL, &tv); if (ret < 0) return ret; if (ret == 0) return ret; /* if (select(32, &filedes, (fd_set *)NULL, (fd_set *)NULL, &timeout)) { ioctl(serverSocket, FIONREAD, count); return TRUE; } *count = 0; */ return ret; } SOCKET Listen::createService(unsigned short *Port) { struct sockaddr_in serverSocketAddr; SOCKET serverSocket; struct sockaddr_in name; /* int buf_size; int ret; buf_size=32768; */ memset((char *)&serverSocketAddr,0,sizeof(serverSocketAddr)); serverSocketAddr.sin_port=htons((unsigned short)0); serverSocketAddr.sin_port=htons(*Port); serverSocketAddr.sin_family=AF_INET; serverSocketAddr.sin_addr.s_addr=htonl(INADDR_ANY); serverSocket=socket(AF_INET,SOCK_STREAM,0); /* ret=setsockopt( serverSocket, SOL_SOCKET, SO_RCVBUF, (char *)&buf_size, sizeof(int) ); if(ret < 0)fprintf(stderr,"setsockopt failed\n"); */ int ret = ::bind(serverSocket, (struct sockaddr *)&serverSocketAddr, sizeof(serverSocketAddr)); if (ret < 0) { ; } listen(serverSocket,SOMAXCONN); namelen=sizeof(struct sockaddr_in); getsockname(serverSocket,(struct sockaddr *)&name,&namelen); *Port=ntohs(name.sin_port); return serverSocket; } int Listen::getPortAndName(char *in,unsigned int *hostAddr,unsigned short *Port) { struct sockaddr_in serverSocketAddr; struct hostent *serverHostEnt; char out[256]; unsigned int oneNeg; char *np; if(!in || !Port)return 1; memset((char *)&serverSocketAddr,0,sizeof(serverSocketAddr)); strcpy(out,in); if((np=strrchr(out,':'))){ *np=0; np += 1; *Port=(unsigned short)atol(np); } oneNeg = -1L; *hostAddr=(unsigned int)inet_addr(out); if((long)(*hostAddr) != (long)oneNeg){ *hostAddr=htonl(*hostAddr); fprintf(stderr,"Found Address %lx hostAddr %x oneNeg %x diff %x\n",(long)(*hostAddr),*hostAddr,oneNeg,*hostAddr-oneNeg); }else{ serverHostEnt=gethostbyname(out); if(serverHostEnt == NULL){ fprintf(stderr,"Could Not Find Host (%s)\n",out); return 1; } copyl((char *)serverHostEnt->h_addr,(char *)&serverSocketAddr.sin_addr,serverHostEnt->h_length); *hostAddr=serverSocketAddr.sin_addr.s_addr; *hostAddr=htonl(*hostAddr); fprintf(stderr,"Found Address %lx\n",(long)*hostAddr); } return 0; } SOCKET Listen::connectToServer(char *serverName,unsigned short *Port) { struct sockaddr_in serverSocketAddr; struct hostent *serverHostEnt; SOCKET toServerSocket; int ret; unsigned int hostAddr; unsigned int oneNeg; short result,Try; char *np; int buf_size; /* oneNeg=0xffffffff; */ oneNeg = -1L; long netsize=200000; buf_size=(int)(netsize+30); result= -1; memset(&serverSocketAddr, 0, sizeof(serverSocketAddr)); if(!(np=strrchr(serverName,':'))){ fprintf(stderr,"Bad Address (%s)",serverName); return result; }else{ *np=0; np += 1; *Port=(unsigned short)atol(np); } // hostAddr=(unsigned int)inet_addr(serverName); inet_pton(AF_INET, serverName, &hostAddr); if((long)hostAddr != (long)oneNeg){ serverSocketAddr.sin_addr.s_addr=hostAddr; fprintf(stderr,"Found Address %lx hostAddr %x oneNeg %x diff %x\n",(long)hostAddr,hostAddr,oneNeg,hostAddr-oneNeg); }else{ serverHostEnt=gethostbyname(serverName); if(serverHostEnt == NULL){ fprintf(stderr,"Could Not Find Host (%s)\n",serverName); return result; } copyl((char *)serverHostEnt->h_addr,(char *)&serverSocketAddr.sin_addr,serverHostEnt->h_length); } serverSocketAddr.sin_family=AF_INET; serverSocketAddr.sin_port=htons(*Port); Try=0; while(Try++ < 10){ if((toServerSocket=socket(AF_INET,SOCK_STREAM,0)) < 0){ fprintf(stderr,"socket Error (%ld)\n",(long)SOCKET_ERRNO); return toServerSocket; } ret=setsockopt( toServerSocket, SOL_SOCKET, SO_SNDBUF, (char *)&buf_size, sizeof(int) ); if(ret < 0)fprintf(stderr,"setsockopt SO_SNDBUF failed\n"); ret=connect(toServerSocket,(struct sockaddr *)&serverSocketAddr,sizeof(serverSocketAddr)); if(ret == -1){ if (SOCKET_ERRNO == SOCKET_ECONNREFUSED) { fprintf(stderr,"Connection Refused Try(%d)\n",Try); closesocket(toServerSocket); Sleep2(20); continue; }else{ fprintf(stderr,"Connection Error (%ld)\n",(long)SOCKET_ERRNO); return ret; } } return toServerSocket; } return ret; } static int copyl(char *p1,char *p2,long n) { if(!p1 || !p2)return 1; while(n-- > 0)*p2++ = *p1++; return 0; }
21.875776
126
0.582529
righthalfplane
c778c162f7934dd7fa32a227511539004c6d3cff
3,441
cpp
C++
tests/rect_spec.cpp
Polynominal/bump.hpp
a53e9d5c4d8079aa86ed9a73d36ea7188901215e
[ "MIT" ]
null
null
null
tests/rect_spec.cpp
Polynominal/bump.hpp
a53e9d5c4d8079aa86ed9a73d36ea7188901215e
[ "MIT" ]
null
null
null
tests/rect_spec.cpp
Polynominal/bump.hpp
a53e9d5c4d8079aa86ed9a73d36ea7188901215e
[ "MIT" ]
null
null
null
#include <gtest/gtest.h> #include <gmock/gmock.h> #include "../Rectangle.hpp" #include "../Collision.hpp" using namespace plugin::physics::bump; TEST(RECTANGLE, StaticIntersectTest) { { std::shared_ptr<Collision> col = std::make_shared<Collision>(); ASSERT_FALSE(Rectangle(0,0,1,1).DetectCollision(Rectangle(5,5,1,1), col.get(), math::vec2(0,0))); } { std::shared_ptr<Collision> col = std::make_shared<Collision>(); ASSERT_TRUE(Rectangle(5,5,1,1).DetectCollision(Rectangle(0,0,7,6), col.get(), math::vec2(5,5))); ASSERT_TRUE(Rectangle(0,0,7,6).DetectCollision(Rectangle(5,5,1,1), col.get(), math::vec2(0,0))); ASSERT_EQ(col->ti, -2.0f); ASSERT_EQ(col->move.x, 0.0f); ASSERT_EQ(col->move.y, 0.0f); ASSERT_EQ(col->itemRect.pos.x, 0.0f); ASSERT_EQ(col->itemRect.pos.y, 0.0f); ASSERT_EQ(col->itemRect.scale.x, 7.0f); ASSERT_EQ(col->itemRect.scale.y, 6.0f); ASSERT_EQ(col->otherRect.pos.x, 5.0f); ASSERT_EQ(col->otherRect.pos.y, 5.0f); ASSERT_EQ(col->otherRect.scale.x, 1.0f); ASSERT_EQ(col->otherRect.scale.y, 1.0f); ASSERT_EQ(col->normal.x, 0.0f); ASSERT_EQ(col->normal.y, -1.0f); } } TEST(RECTANGLE, StaticIntersectTestExtra) { { std::shared_ptr<Collision> col = std::make_shared<Collision>();; ASSERT_FALSE(Rectangle(4,6,10,10).DetectCollision(Rectangle(20,20,10,10), col.get(), math::vec2(0,0))); ASSERT_FALSE(Rectangle(20,20,10,10).DetectCollision(Rectangle(4,6,10,10), col.get())); } } TEST(RECTANGLE, MovingIntersectTest) { { std::shared_ptr<Collision> col = std::make_shared<Collision>();; ASSERT_FALSE(Rectangle(0,0,1,1).DetectCollision(Rectangle(5,5,1,1), col.get(), math::vec2(0,1))); } } TEST(RECTANGLE, MovingIntersectTestLeft) { std::shared_ptr<Collision> col = std::make_shared<Collision>();; ASSERT_TRUE(Rectangle(1,1,1,1).DetectCollision(Rectangle(5,0,1,1), col.get(), math::vec2(6,0))); ASSERT_EQ(col->ti, 0.6f); ASSERT_EQ(col->normal.x, -1.0f); ASSERT_EQ(col->normal.y, 0.0f); } TEST(RECTANGLE, MovingIntersectTestRight) { std::shared_ptr<Collision> col = std::make_shared<Collision>();; ASSERT_TRUE(Rectangle(6,0,1,1).DetectCollision(Rectangle(1,0,1,1), col.get(), math::vec2(1,1))); ASSERT_FALSE(col->overlaps); ASSERT_EQ(col->ti, 0.8f); ASSERT_EQ(col->normal.x, 1.0f); ASSERT_EQ(col->normal.y, 0.0f); } TEST(RECTANGLE, MovingIntersectTestTop) { std::shared_ptr<Collision> col = std::make_shared<Collision>();; ASSERT_TRUE(Rectangle(0,0,1,1).DetectCollision(Rectangle(0,4,1,1), col.get(), math::vec2(0,5))); ASSERT_FALSE(col->overlaps); ASSERT_EQ(col->ti, 0.6f); ASSERT_EQ(col->normal.x, 0.0f); ASSERT_EQ(col->normal.y, -1.0f); } TEST(RECTANGLE, MovingIntersectTestBottom) { std::shared_ptr<Collision> col = std::make_shared<Collision>();; ASSERT_TRUE(Rectangle(0,4,1,1).DetectCollision(Rectangle(0,0,1,1), col.get(), math::vec2(0,-1))); ASSERT_FALSE(col->overlaps); ASSERT_EQ(col->ti, 0.6f); ASSERT_EQ(col->normal.x, 0.0f); ASSERT_EQ(col->normal.y, 1.0f); } TEST(RECTANGLE, CornerCase) { { std::shared_ptr<Collision> col = std::make_shared<Collision>();; ASSERT_FALSE(Rectangle(0,16,16,16).DetectCollision(Rectangle(16,0,16,16), col.get(), math::vec2(-1,15))); } }
32.158879
114
0.642546
Polynominal
c77cf327a7dabc6ff652f91640e3986a76f91c2b
340
cc
C++
src/transport_sweep/Sweep_Fixed_Source_None.cc
pgmaginot/DARK_ARTS
f04b0a30dcac911ef06fe0916921020826f5c42b
[ "MIT" ]
null
null
null
src/transport_sweep/Sweep_Fixed_Source_None.cc
pgmaginot/DARK_ARTS
f04b0a30dcac911ef06fe0916921020826f5c42b
[ "MIT" ]
null
null
null
src/transport_sweep/Sweep_Fixed_Source_None.cc
pgmaginot/DARK_ARTS
f04b0a30dcac911ef06fe0916921020826f5c42b
[ "MIT" ]
null
null
null
#include "Sweep_Fixed_Source_None.h" Sweep_Fixed_Source_None::Sweep_Fixed_Source_None(const Fem_Quadrature& fem_quadrature) : V_Sweep_Fixed_Source(fem_quadrature) { } void Sweep_Fixed_Source_None::get_source(Eigen::VectorXd& source_vec) { for(int i=0; i< m_n_dfem_pts ; i++) source_vec(i) = 0.; return; }
18.888889
87
0.717647
pgmaginot
c780d63763d689da712811418e40c29e1ed0fb13
4,489
cpp
C++
src/runtime/NEON/functions/NEGEMMConvolutionLayer.cpp
MaximMilashchenko/ComputeLibrary
91ee4d0a9ef128b16936921470a0e3ffef347536
[ "MIT" ]
1
2022-02-10T11:06:25.000Z
2022-02-10T11:06:25.000Z
src/runtime/NEON/functions/NEGEMMConvolutionLayer.cpp
0xgpapad/ComputeLibrary
91ee4d0a9ef128b16936921470a0e3ffef347536
[ "MIT" ]
null
null
null
src/runtime/NEON/functions/NEGEMMConvolutionLayer.cpp
0xgpapad/ComputeLibrary
91ee4d0a9ef128b16936921470a0e3ffef347536
[ "MIT" ]
1
2022-02-04T10:22:53.000Z
2022-02-04T10:22:53.000Z
/* * Copyright (c) 2017-2021 Arm Limited. * * SPDX-License-Identifier: MIT * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include "arm_compute/runtime/NEON/functions/NEGEMMConvolutionLayer.h" #include "arm_compute/core/Size2D.h" #include "arm_compute/core/Utils.h" #include "arm_compute/core/Validate.h" #include "arm_compute/runtime/Tensor.h" #include "src/core/helpers/MemoryHelpers.h" #include "src/cpu/operators/CpuGemmConv2d.h" using namespace arm_compute::experimental; namespace arm_compute { struct NEGEMMConvolutionLayer::Impl { const ITensor *weights{ nullptr }; std::unique_ptr<cpu::CpuGemmConv2d> op{ nullptr }; ITensorPack run_pack{}; MemoryGroup memory_group{}; IWeightsManager *weights_manager{ nullptr }; MemoryRequirements aux_mem_req{}; WorkspaceData<Tensor> workspace_tensors{}; bool is_prepared{ false }; }; NEGEMMConvolutionLayer::NEGEMMConvolutionLayer(const std::shared_ptr<IMemoryManager> &memory_manager, IWeightsManager *weights_manager) : _impl(std::make_unique<Impl>()) { _impl->weights_manager = weights_manager; _impl->memory_group = MemoryGroup(memory_manager); } NEGEMMConvolutionLayer::~NEGEMMConvolutionLayer() = default; void NEGEMMConvolutionLayer::configure(const ITensor *input, const ITensor *weights, const ITensor *biases, ITensor *output, const PadStrideInfo &conv_info, const WeightsInfo &weights_info, const Size2D &dilation, const ActivationLayerInfo &act_info, bool enable_fast_math, unsigned int num_groups) { ARM_COMPUTE_ERROR_ON_NULLPTR(input, weights, output); _impl->weights = weights; _impl->op = std::make_unique<cpu::CpuGemmConv2d>(); _impl->op->configure(input->info(), weights->info(), (biases != nullptr ? biases->info() : nullptr), output->info(), conv_info, weights_info, dilation, act_info, enable_fast_math, num_groups); _impl->run_pack = { { TensorType::ACL_SRC_0, input }, { TensorType::ACL_SRC_1, weights }, { TensorType::ACL_SRC_2, biases }, { TensorType::ACL_DST, output } }; _impl->aux_mem_req = _impl->op->workspace(); _impl->workspace_tensors = manage_workspace<Tensor>(_impl->aux_mem_req, _impl->memory_group, _impl->run_pack, _impl->run_pack); } Status NEGEMMConvolutionLayer::validate(const ITensorInfo *input, const ITensorInfo *weights, const ITensorInfo *biases, const ITensorInfo *output, const PadStrideInfo &conv_info, const WeightsInfo &weights_info, const Size2D &dilation, const ActivationLayerInfo &act_info, bool enable_fast_math, unsigned int num_groups) { return cpu::CpuGemmConv2d::validate(input, weights, biases, output, conv_info, weights_info, dilation, act_info, enable_fast_math, num_groups); } void NEGEMMConvolutionLayer::run() { prepare(); MemoryGroupResourceScope scope_mg(_impl->memory_group); _impl->op->run(_impl->run_pack); } void NEGEMMConvolutionLayer::prepare() { if(!_impl->is_prepared) { _impl->op->prepare(_impl->run_pack); // Release temporary tensors that are only used in prepare stage release_temporaries<Tensor>(_impl->aux_mem_req, _impl->workspace_tensors); _impl->is_prepared = true; } } } // namespace arm_compute
44.445545
196
0.709067
MaximMilashchenko
c784cc15a590a3cd34d039cce7678aea6d485fb9
746
hpp
C++
include/RadonFramework/Core/Types/Int16.hpp
tak2004/RadonFramework
e916627a54a80fac93778d5010c50c09b112259b
[ "Apache-2.0" ]
3
2015-09-15T06:57:50.000Z
2021-03-16T19:05:02.000Z
include/RadonFramework/Core/Types/Int16.hpp
tak2004/RadonFramework
e916627a54a80fac93778d5010c50c09b112259b
[ "Apache-2.0" ]
2
2015-09-26T12:41:10.000Z
2015-12-08T08:41:37.000Z
include/RadonFramework/Core/Types/Int16.hpp
tak2004/RadonFramework
e916627a54a80fac93778d5010c50c09b112259b
[ "Apache-2.0" ]
1
2015-07-09T02:56:34.000Z
2015-07-09T02:56:34.000Z
#ifndef RF_CORE_TYPES_INT16_HPP #define RF_CORE_TYPES_INT16_HPP #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #include <cstdint> namespace RadonFramework::Core::Types { /// A Int16 have always the size of 2 byte and represent a signed number. using Int16 = int16_t; /// The maximum value which can be contained by a Int16. extern const Int16 Int16Max; /// The minimum value which can be contained by a Int16. extern const Int16 Int16Min; } // namespace RadonFramework::Core::Types #ifndef RF_SHORTHAND_NAMESPACE_TYPE #define RF_SHORTHAND_NAMESPACE_TYPE namespace RF_Type = RadonFramework::Core::Types; #endif #ifndef RF_DISABLE_USING_TYPES using RadonFramework::Core::Types::Int16; #endif #endif // RF_CORE_TYPES_INT16_HPP
23.3125
73
0.784182
tak2004
c788c97c8b91dbd1a009e0a89af3f86f2b0b8956
179
hpp
C++
engine/widgets.hpp
jpmorris33/ire
d6a0a9468c1f98010c5959be301b717f02336895
[ "BSD-3-Clause" ]
null
null
null
engine/widgets.hpp
jpmorris33/ire
d6a0a9468c1f98010c5959be301b717f02336895
[ "BSD-3-Clause" ]
8
2020-03-29T21:03:23.000Z
2020-04-11T23:28:14.000Z
engine/widgets.hpp
jpmorris33/ire
d6a0a9468c1f98010c5959be301b717f02336895
[ "BSD-3-Clause" ]
1
2020-06-11T16:54:37.000Z
2020-06-11T16:54:37.000Z
extern int GetLoadSaveSlot(int saving); // Menu extern int GetTextBox(char *text, const char *prompt, int maxlen); extern int GetFileSelect(char *prompt, char *newfile, char *x);
44.75
66
0.759777
jpmorris33
c78bdbabeb68bdb01222fbfbc657bdb27e4c72a3
188
cpp
C++
ABC/abc121/a.cpp
EnsekiTT/atcoder
6b40332d1b2493d1b6c00c9f1912895a67a3bbcb
[ "MIT" ]
null
null
null
ABC/abc121/a.cpp
EnsekiTT/atcoder
6b40332d1b2493d1b6c00c9f1912895a67a3bbcb
[ "MIT" ]
null
null
null
ABC/abc121/a.cpp
EnsekiTT/atcoder
6b40332d1b2493d1b6c00c9f1912895a67a3bbcb
[ "MIT" ]
null
null
null
#include<iostream> #include<string> using namespace std; int main() { int H, W, h, w; cin >> H >> W; cin >> h >> w; cout << H*W - ((H-h)*w + (W-w)*h + h*w) << endl; return 0; }
14.461538
50
0.5
EnsekiTT
c78df3511a8f0f914342fe0931c4b9ee0ba82d49
10,356
cc
C++
QTProject/window.cc
jtorres6/MeshColors
bef99c377bbca9d35532d589d4b7434764fc9bd0
[ "MIT" ]
null
null
null
QTProject/window.cc
jtorres6/MeshColors
bef99c377bbca9d35532d589d4b7434764fc9bd0
[ "MIT" ]
null
null
null
QTProject/window.cc
jtorres6/MeshColors
bef99c377bbca9d35532d589d4b7434764fc9bd0
[ "MIT" ]
null
null
null
/*! \file * Copyright Domingo Martín Perandres * email: dmartin@ugr.es * web: http://calipso.ugr.es/dmartin * 2003-2019 * GPL 3 */ #include <QApplication> #include <QAction> #include <QMenuBar> #include <QFrame> #include <QWheelEvent> #include <QPushButton> #include <QLabel> #include <QColorDialog> #include <QSpinBox> #include <QGLFormat> #include <QSlider> #include <debugtools.h> #include "window.h" #include "glwidget.h" /*****************************************************************************//** * * * *****************************************************************************/ _window::_window() { QSizePolicy Q(QSizePolicy::Expanding,QSizePolicy::Expanding); QWidget *Central_widget = new QWidget(this); QPalette Pal(palette()); Pal.setColor(QPalette::Background, Qt::black); QWidget *Options_widget = new QWidget; QVBoxLayout *Vertical_options = new QVBoxLayout; QLabel *Label1 = new QLabel("Select color"); Color_selection = new QPushButton(""); QColor SelectedColor = Qt::black; if(SelectedColor.isValid()) { QString qss = QString("background-color: %1").arg(SelectedColor.name()); Color_selection->setStyleSheet(qss); } Color_selection->setAutoFillBackground(true); Color_selection->setPalette(Pal); connect(Color_selection, SIGNAL(pressed()), this, SLOT(OpenColorDialog())); QPushButton *Lighting_button = new QPushButton("Toggle lighting"); QPushButton *Lerp_button = new QPushButton("Toggle color inerpolation"); Vertical_options->addWidget(Label1); Vertical_options->addWidget(Color_selection); Vertical_options->addWidget(Lighting_button); Vertical_options->addWidget(Lerp_button); Vertical_options->addStretch(); QLabel *Label2 = new QLabel("Face resolution"); QPushButton *FaceSelection_button = new QPushButton("Enable face selection"); QPushButton *Increment_button = new QPushButton("+"); QPushButton *Decrease_button = new QPushButton("-"); Vertical_options->addWidget(Label2); Vertical_options->addWidget(FaceSelection_button); Vertical_options->addWidget(Increment_button); Vertical_options->addWidget(Decrease_button); Vertical_options->addStretch(); QLabel *Label3 = new QLabel("Pencil size"); QSlider* PencilSize_widget = new QSlider(Qt::Horizontal); PencilSize_widget->setMinimum(1); PencilSize_widget->setMaximum(32); Vertical_options->addWidget(Label3); Vertical_options->addWidget(PencilSize_widget); Options_widget->setLayout(Vertical_options); QTabWidget *Tab_widget = new QTabWidget; Tab_widget->setMaximumWidth(300); Tab_widget->addTab(Options_widget, "Options"); QFrame *Framed_widget= new QFrame(Central_widget); Framed_widget->setSizePolicy(Q); Framed_widget->setFrameStyle(QFrame::Panel); Framed_widget->setLineWidth(3); GL_widget = new _gl_widget(this); GL_widget->setSizePolicy(Q); connect(FaceSelection_button, SIGNAL(pressed()), GL_widget, SLOT(EnableTriangleSelectionMode())); connect(Increment_button, SIGNAL(pressed()), GL_widget, SLOT(IncrementResolution())); connect(Decrease_button, SIGNAL(pressed()), GL_widget, SLOT(DecreaseResolution())); connect(Lighting_button, SIGNAL(pressed()), GL_widget, SLOT(ToggleLighting())); connect(Lerp_button, SIGNAL(pressed()), GL_widget, SLOT(ToggleColorInterpolation())); connect(PencilSize_widget, SIGNAL(valueChanged(int)), GL_widget, SLOT(UpdatePencilSize(int))); QHBoxLayout *Horizontal_frame = new QHBoxLayout(); Horizontal_frame->setContentsMargins(1,1,1,1); Horizontal_frame->addWidget(GL_widget); Horizontal_frame->addWidget(Tab_widget); Framed_widget->setLayout(Horizontal_frame); QHBoxLayout *Horizontal_main = new QHBoxLayout(Central_widget); Horizontal_main->addWidget(Framed_widget); Central_widget->setLayout(Horizontal_main); setCentralWidget(Central_widget); // actions for file menu QAction *Exit = new QAction(QIcon("./icons/exit.png"), tr("&Exit..."), this); Exit->setShortcut(tr("Ctrl+Q")); Exit->setToolTip(tr("Exit the application")); connect(Exit, SIGNAL(triggered()), this, SLOT(close())); // actions for file menu QAction *FileOpen = new QAction(tr("&Open file..."), this); FileOpen->setShortcut(tr("Ctrl+E")); connect(FileOpen, SIGNAL(triggered()), this, SLOT(OpenFileDialog())); // actions for file menu QAction *SaveTexture = new QAction(tr("&Save texture"), this); SaveTexture->setShortcut(tr("Ctrl+S")); connect(SaveTexture, SIGNAL(triggered()), this, SLOT(close())); QAction *SaveTextureAs = new QAction(tr("&Save texture as..."), this); SaveTextureAs->setShortcut(tr("Ctrl+Shift+S")); connect(SaveTextureAs, SIGNAL(triggered()), this, SLOT(SaveImage())); // actions for file menu QAction *LoadTexture = new QAction(tr("Load image"), this); connect(LoadTexture, SIGNAL(triggered()), this, SLOT(LoadMeshColorsFile())); // menus QMenu *File_menu=menuBar()->addMenu(tr("&File")); File_menu->addAction(FileOpen); File_menu->addAction(SaveTexture); File_menu->addAction(SaveTextureAs); File_menu->addAction(LoadTexture); File_menu->addAction(Exit); File_menu->setAttribute(Qt::WA_AlwaysShowToolTips); setWindowTitle(tr("MeshColors")); resize(800,800); } void _window::mousePressEvent(QMouseEvent *e) { if(e->buttons() & Qt::LeftButton) { GL_widget->pick(e->pos().x(), height() - e->pos().y()); } } void _window::mouseMoveEvent(QMouseEvent *e) { if(e->buttons() & Qt::LeftButton) { GL_widget->pick(e->pos().x(), height() - e->pos().y()); } if(e->buttons() & Qt::RightButton) { if(MousePressed) { GL_widget->MoveCameraRightLeft(QPair<qint32, qint32>(e->pos().x() - PreviousPosition.first, e->pos().y() - PreviousPosition.second)); } else { MousePressed = true; } PreviousPosition.first = e->pos().x(); PreviousPosition.second = e->pos().y(); } } void _window::mouseReleaseEvent(QMouseEvent *event) { if(event != nullptr) { MousePressed = false; } } void _window::wheelEvent(QWheelEvent *event) { if(event != nullptr) { GL_widget->AddCameraZoom(event->angleDelta().y()); } } void _window::resizeEvent(QResizeEvent *event) { if(event != nullptr) { GL_widget->resize(event->size().width(), event->size().height()); } } void _window::OpenFileDialog() { // Posible fix: https://blogs.kde.org/2009/03/26/how-crash-almost-every-qtkde-application-and-how-fix-it-0 QString fileName = QFileDialog::getOpenFileName(this, tr("3D object location"), "", tr("PLY objects (*.ply);;All Files (*)"), 0, QFileDialog::DontUseNativeDialog); QDir dir(QDir::currentPath()); std::string FileNameStd = dir.relativeFilePath(fileName).toStdString(); const char *fileNameChar = FileNameStd.c_str(); GL_widget->SetObjectPath(fileNameChar); } void _window::SaveImage() { QString fileName = QFileDialog::getSaveFileName(this, tr("Mesh Colors file location"), "", tr("Mesh colors map (*.mcm);;All Files (*)"), 0, QFileDialog::DontUseNativeDialog); if (fileName.isEmpty()) return; QFile file(fileName); if (!file.open(QIODevice::WriteOnly)) { QMessageBox::information(this, tr("Unable to open file"), file.errorString()); return; } QDataStream out(&file); out.setVersion(QDataStream::Qt_5_15); const int nFaces = GL_widget->GetObject3D()->Triangles.size(); QVector<int> Res; QVector<QVector4D> Colors; int counter = 0; for(int j = 0; j < GL_widget->GetObject3D()->Vertices.size()-1; j++) { Colors.push_back(GL_widget->GetMeshColorsArray()[j]); counter++; } for(int i = 0; i < nFaces; i++) { Res.push_back(GL_widget->GetResolutionsArray()[i]); int nColors = 3 * (GL_widget->GetResolutionsArray()[i] - 1) + ((GL_widget->GetResolutionsArray()[i] - 1) * (GL_widget->GetResolutionsArray()[i] - 2)) / 2; for(int j = 0; j < nColors; j++) { Colors.push_back(GL_widget->GetMeshColorsArray()[counter+j]); } counter += 2000; } out << Res; out << Colors; } void _window::LoadMeshColorsFile() { // Posible fix: https://blogs.kde.org/2009/03/26/how-crash-almost-every-qtkde-application-and-how-fix-it-0 QString fileName = QFileDialog::getOpenFileName(this, tr("Mesh Colors file location"), "", tr("Mesh colors map (*.mcm);;All Files (*)"), 0, QFileDialog::DontUseNativeDialog); if (fileName.isEmpty()) return; QFile file(fileName); if (!file.open(QIODevice::ReadOnly)) { QMessageBox::information(this, tr("Unable to open file"), file.errorString()); return; } QDataStream in(&file); in.setVersion(QDataStream::Qt_5_15); QVector<int> resolutions; QVector<QVector4D> array; in >> resolutions; in >> array; QVector<int> Res; QVector<QVector4D> Colors; const int nFaces = GL_widget->GetObject3D()->Triangles.size(); int counter = 0; for(int i = 0; i < GL_widget->GetObject3D()->Vertices.size() - 1; i++) { Colors.push_back(array[i]); counter++; } for(int i = 0; i < nFaces; i++) { int nColors = 3 * (resolutions[i] - 1) + ((resolutions[i] - 1) * (resolutions[i] - 2)) / 2; for(int j = 0; j < 2000; j++) { if(j < nColors) { Colors.push_back(array[counter]); counter++; } else { Colors.push_back(QVector4D(1.0f, 1.0f, 1.0f, 0.0f)); } } } GL_widget->SetResolutionsArray(resolutions); GL_widget->SetMeshColorsArray(Colors); } void _window::OpenColorDialog() { QColor NewColor = QColorDialog::getColor(Qt::yellow, this ); if(NewColor.isValid()) { GL_widget->SetCurrentPaintingColor(NewColor); QString qss = QString("background-color: %1").arg(NewColor.name()); Color_selection->setStyleSheet(qss); } }
29.504274
145
0.639146
jtorres6
c78e552a8351b21e7df47a56c0c332f15d1396d0
164,196
cpp
C++
Source/Rhi/Private/NullRhi/NullRhi.cpp
cofenberg/unrimp
90310657f106eb83f3a9688329b78619255a1042
[ "MIT" ]
187
2015-11-02T21:27:57.000Z
2022-02-17T21:39:17.000Z
Source/Rhi/Private/NullRhi/NullRhi.cpp
cofenberg/unrimp
90310657f106eb83f3a9688329b78619255a1042
[ "MIT" ]
null
null
null
Source/Rhi/Private/NullRhi/NullRhi.cpp
cofenberg/unrimp
90310657f106eb83f3a9688329b78619255a1042
[ "MIT" ]
20
2015-11-04T19:17:01.000Z
2021-11-18T11:23:25.000Z
/*********************************************************\ * Copyright (c) 2012-2021 The Unrimp Team * * 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. \*********************************************************/ /** * @brief * Null RHI amalgamated/unity build implementation * * @remarks * == Dependencies == * None. * * == Preprocessor Definitions == * - Set "RHI_NULL_EXPORTS" as preprocessor definition when building this library as shared library * - Do also have a look into the RHI header file documentation */ //[-------------------------------------------------------] //[ Includes ] //[-------------------------------------------------------] #include <Rhi/Public/Rhi.h> #ifdef _WIN32 // Set Windows version to Windows Vista (0x0600), we don't support Windows XP (0x0501) #ifdef WINVER #undef WINVER #endif #define WINVER 0x0600 #ifdef _WIN32_WINNT #undef _WIN32_WINNT #endif #define _WIN32_WINNT 0x0600 // Exclude some stuff from "windows.h" to speed up compilation a bit #define WIN32_LEAN_AND_MEAN #define NOGDICAPMASKS #define NOMENUS #define NOICONS #define NOKEYSTATES #define NOSYSCOMMANDS #define NORASTEROPS #define OEMRESOURCE #define NOATOM #define NOMEMMGR #define NOMETAFILE #define NOOPENFILE #define NOSCROLL #define NOSERVICE #define NOSOUND #define NOWH #define NOCOMM #define NOKANJI #define NOHELP #define NOPROFILER #define NODEFERWINDOWPOS #define NOMCX #define NOCRYPT #include <Windows.h> // Get rid of some nasty OS macros #undef max #elif LINUX // TODO(co) Review which of the following headers can be removed #include <X11/Xlib.h> #endif //[-------------------------------------------------------] //[ NullRhi/MakeID.h ] //[-------------------------------------------------------] /* Author: Emil Persson, A.K.A. Humus. http://www.humus.name Version history: 1.0 - Initial release. 1.01 - Code review fixes. Code reviewed by Denis A. Gladkiy. 1.02 - Fixed an off-by-one error in DestroyRange() found by Markus Billeter License: Public Domain This file is released in the hopes that it will be useful. Use in whatever way you like, but no guarantees that it actually works or fits any particular purpose. It has been unit-tested and benchmarked though, and seems to do what it was designed to do, and seems pretty quick at it too. Notes: There are many applications where it is desired to generate unique IDs at runtime for various resources, such that they can be distinguished, sorted or otherwise processed in an efficient manner. It can in some cases replace hashes, handles and pointers. In cases where resource pointers are used as IDs, it offers a unique ID that requires far fewer bits, especially for 64bit apps. The design goal of this implementation was to return the most compact IDs as possible, limiting to a specific range if necessary. The properties of this system are as follows: - Creating a new ID returns the smallest possible unused ID. - Creating a new range of IDs returns the smallest possible continuous range of the specified size. - Created IDs remain valid until destroyed. - Destroying an ID returns it to the pool and may be returned by subsequent allocations. - The system is NOT thread-safe. Performance properties: - Creating an ID is O(1) and generally super-cheap. - Destroying an ID is also cheap, but O(log(n)), where n is the current number of distinct available ranges. - The system merges available ranges when IDs are destroyed, keeping said n generally very small in practice. - After warmup, no further memory allocations should be necessary, or be very rare. - The system uses very little memory. - It is possible to construct a pathological case where fragmentation would cause n to become large. This can be done by first allocating a very large range of IDs, then deleting every other ID, causing a new range to be allocated for every free ID, or as many ranges as there are free IDs. I believe nothing close to this situation happens in practical applications. In tests, millions of random scattered creations and deletions only resulted in a relatively short list in the worst case. This is because freed IDs are quickly reused and ranges eagerly merged. Where would this system be useful? It was originally thought up as a replacement for resource pointers as part of sort-ids in rendering. Using for instance a 64-bit sort-id packing various flags and states, putting a pointer in there takes an awful lot of bits, especially considering the actual possible resources range in the thousands at most. This got far worse of course with the switch to 64bit as pointers are now twice as large and essentially eats all bits except bottom few for alignment. Another application would be for managing a shared pool of resources. IDs could be handed out as handles and used to access the actual resource from an array. By always returning the lowest possible ID or range of IDs we get very good cache behavior since all active resources will grouped together in the bottom part of the array. Using IDs instead of pointers for handles also allows easy resizing of the allocated memory since IDs can remain the same even if the underlying storage changed. */ #ifdef RHI_DEBUG #include <cstdio> // For printf(). Remove if you don't need the PrintRanges() function (mostly for debugging anyway). #endif #include <cstdint> // uint32_t #include <limits> // std::numeric_limits<type>::max() #include <cstdlib> #include <cstring> class MakeID final { private: // Change to uint16_t here for a more compact implementation if 16bit or less IDs work for you. typedef uint16_t uint; struct Range { uint m_First; uint m_Last; }; Rhi::IAllocator& m_Allocator; Range *m_Ranges; // Sorted array of ranges of free IDs uint m_Count; // Number of ranges in list uint m_Capacity; // Total capacity of range list MakeID & operator=(const MakeID &) = delete; MakeID(const MakeID &) = delete; public: MakeID(Rhi::IAllocator& allocator, const uint max_id = std::numeric_limits<uint>::max()) : m_Allocator(allocator), m_Ranges(static_cast<Range*>(allocator.reallocate(nullptr, 0, sizeof(Range), 1))), m_Count(1), m_Capacity(1) { // Start with a single range, from 0 to max allowed ID (specified) m_Ranges[0].m_First = 0; m_Ranges[0].m_Last = max_id; } ~MakeID() { m_Allocator.reallocate(m_Ranges, 0, 0, 1); } bool CreateID(uint &id) { if (m_Ranges[0].m_First <= m_Ranges[0].m_Last) { id = m_Ranges[0].m_First; // If current range is full and there is another one, that will become the new current range if (m_Ranges[0].m_First == m_Ranges[0].m_Last && m_Count > 1) { DestroyRange(0); } else { ++m_Ranges[0].m_First; } return true; } // No available ID left return false; } bool CreateRangeID(uint &id, const uint count) { uint i = 0; do { const uint range_count = 1u + m_Ranges[i].m_Last - m_Ranges[i].m_First; if (count <= range_count) { id = m_Ranges[i].m_First; // If current range is full and there is another one, that will become the new current range if (count == range_count && i + 1 < m_Count) { DestroyRange(i); } else { m_Ranges[i].m_First += count; } return true; } ++i; } while (i < m_Count); // No range of free IDs was large enough to create the requested continuous ID sequence return false; } bool DestroyID(const uint id) { return DestroyRangeID(id, 1); } bool DestroyRangeID(const uint id, const uint count) { const uint end_id = static_cast<uint>(id + count); // Binary search of the range list uint i0 = 0u; uint i1 = m_Count - 1u; for (;;) { const uint i = (i0 + i1) / 2u; if (id < m_Ranges[i].m_First) { // Before current range, check if neighboring if (end_id >= m_Ranges[i].m_First) { if (end_id != m_Ranges[i].m_First) return false; // Overlaps a range of free IDs, thus (at least partially) invalid IDs // Neighbor id, check if neighboring previous range too if (i > i0 && id - 1 == m_Ranges[i - 1].m_Last) { // Merge with previous range m_Ranges[i - 1].m_Last = m_Ranges[i].m_Last; DestroyRange(i); } else { // Just grow range m_Ranges[i].m_First = id; } return true; } else { // Non-neighbor id if (i != i0) { // Cull upper half of list i1 = i - 1u; } else { // Found our position in the list, insert the deleted range here InsertRange(i); m_Ranges[i].m_First = id; m_Ranges[i].m_Last = end_id - 1u; return true; } } } else if (id > m_Ranges[i].m_Last) { // After current range, check if neighboring if (id - 1 == m_Ranges[i].m_Last) { // Neighbor id, check if neighboring next range too if (i < i1 && end_id == m_Ranges[i + 1].m_First) { // Merge with next range m_Ranges[i].m_Last = m_Ranges[i + 1].m_Last; DestroyRange(i + 1u); } else { // Just grow range m_Ranges[i].m_Last += count; } return true; } else { // Non-neighbor id if (i != i1) { // Cull bottom half of list i0 = i + 1u; } else { // Found our position in the list, insert the deleted range here InsertRange(i + 1u); m_Ranges[i + 1].m_First = id; m_Ranges[i + 1].m_Last = end_id - 1u; return true; } } } else { // Inside a free block, not a valid ID return false; } } } bool IsID(const uint id) const { // Binary search of the range list uint i0 = 0u; uint i1 = m_Count - 1u; for (;;) { const uint i = (i0 + i1) / 2u; if (id < m_Ranges[i].m_First) { if (i == i0) return true; // Cull upper half of list i1 = i - 1u; } else if (id > m_Ranges[i].m_Last) { if (i == i1) return true; // Cull bottom half of list i0 = i + 1u; } else { // Inside a free block, not a valid ID return false; } } } uint GetAvailableIDs() const { uint count = m_Count; uint i = 0; do { count += m_Ranges[i].m_Last - m_Ranges[i].m_First; ++i; } while (i < m_Count); return count; } uint GetLargestContinuousRange() const { uint max_count = 0; uint i = 0; do { uint count = m_Ranges[i].m_Last - m_Ranges[i].m_First + 1u; if (count > max_count) max_count = count; ++i; } while (i < m_Count); return max_count; } #ifdef RHI_DEBUG void PrintRanges() const { uint i = 0; for (;;) { if (m_Ranges[i].m_First < m_Ranges[i].m_Last) printf("%u-%u", m_Ranges[i].m_First, m_Ranges[i].m_Last); else if (m_Ranges[i].m_First == m_Ranges[i].m_Last) printf("%u", m_Ranges[i].m_First); else printf("-"); ++i; if (i >= m_Count) { printf("\n"); return; } printf(", "); } } #endif private: void InsertRange(const uint index) { if (m_Count >= m_Capacity) { m_Ranges = static_cast<Range *>(m_Allocator.reallocate(m_Ranges, sizeof(Range) * m_Capacity, (m_Capacity + m_Capacity) * sizeof(Range), 1)); m_Capacity += m_Capacity; } ::memmove(m_Ranges + index + 1, m_Ranges + index, (m_Count - index) * sizeof(Range)); ++m_Count; } void DestroyRange(const uint index) { --m_Count; ::memmove(m_Ranges + index, m_Ranges + index + 1, (m_Count - index) * sizeof(Range)); } }; //[-------------------------------------------------------] //[ Forward declarations ] //[-------------------------------------------------------] namespace NullRhi { class RootSignature; } //[-------------------------------------------------------] //[ Macros & definitions ] //[-------------------------------------------------------] #ifdef RHI_DEBUG /* * @brief * Check whether or not the given resource is owned by the given RHI */ #define RHI_MATCH_CHECK(rhiReference, resourceReference) \ RHI_ASSERT(mContext, &rhiReference == &(resourceReference).getRhi(), "Null error: The given resource is owned by another RHI instance") /** * @brief * Resource name for debugging purposes, ignored when not using "RHI_DEBUG" * * @param[in] debugName * ASCII name for debugging purposes, must be valid (there's no internal null pointer test) */ #define RHI_RESOURCE_DEBUG_NAME_MAYBE_UNUSED_PARAMETER_NO_DEFAULT , [[maybe_unused]] const char debugName[] #else /* * @brief * Check whether or not the given resource is owned by the given RHI */ #define RHI_MATCH_CHECK(rhiReference, resourceReference) /** * @brief * Resource name for debugging purposes, ignored when not using "RHI_DEBUG" * * @param[in] debugName * ASCII name for debugging purposes, must be valid (there's no internal null pointer test) */ #define RHI_RESOURCE_DEBUG_NAME_MAYBE_UNUSED_PARAMETER_NO_DEFAULT #endif //[-------------------------------------------------------] //[ Anonymous detail namespace ] //[-------------------------------------------------------] namespace { namespace detail { //[-------------------------------------------------------] //[ Global definitions ] //[-------------------------------------------------------] static constexpr const char* NULL_NAME = "Null"; ///< ASCII name of this shader language, always valid (do not free the memory the returned pointer is pointing to) //[-------------------------------------------------------] //[ Anonymous detail namespace ] //[-------------------------------------------------------] } // detail } //[-------------------------------------------------------] //[ Namespace ] //[-------------------------------------------------------] namespace NullRhi { //[-------------------------------------------------------] //[ NullRhi/NullRhi.h ] //[-------------------------------------------------------] /** * @brief * Null RHI class */ class NullRhi final : public Rhi::IRhi { //[-------------------------------------------------------] //[ Public data ] //[-------------------------------------------------------] public: MakeID VertexArrayMakeId; MakeID GraphicsPipelineStateMakeId; MakeID ComputePipelineStateMakeId; //[-------------------------------------------------------] //[ Public methods ] //[-------------------------------------------------------] public: /** * @brief * Constructor * * @param[in] context * RHI context, the RHI context instance must stay valid as long as the RHI instance exists * * @note * - Do never ever use a not properly initialized RHI. Use "Rhi::IRhi::isInitialized()" to check the initialization state. */ explicit NullRhi(const Rhi::Context& context); /** * @brief * Destructor */ virtual ~NullRhi() override; void dispatchCommandBufferInternal(const Rhi::CommandBuffer& commandBuffer); //[-------------------------------------------------------] //[ Graphics ] //[-------------------------------------------------------] void setGraphicsRootSignature(Rhi::IRootSignature* rootSignature); void setGraphicsPipelineState(Rhi::IGraphicsPipelineState* graphicsPipelineState); void setGraphicsResourceGroup(uint32_t rootParameterIndex, Rhi::IResourceGroup* resourceGroup); void setGraphicsVertexArray(Rhi::IVertexArray* vertexArray); // Input-assembler (IA) stage void setGraphicsViewports(uint32_t numberOfViewports, const Rhi::Viewport* viewports); // Rasterizer (RS) stage void setGraphicsScissorRectangles(uint32_t numberOfScissorRectangles, const Rhi::ScissorRectangle* scissorRectangles); // Rasterizer (RS) stage void setGraphicsRenderTarget(Rhi::IRenderTarget* renderTarget); // Output-merger (OM) stage void clearGraphics(uint32_t clearFlags, const float color[4], float z, uint32_t stencil); void drawGraphicsEmulated(const uint8_t* emulationData, uint32_t indirectBufferOffset = 0, uint32_t numberOfDraws = 1); void drawIndexedGraphicsEmulated(const uint8_t* emulationData, uint32_t indirectBufferOffset = 0, uint32_t numberOfDraws = 1); void drawMeshTasksEmulated(const uint8_t* emulationData, uint32_t indirectBufferOffset = 0, uint32_t numberOfDraws = 1); //[-------------------------------------------------------] //[ Compute ] //[-------------------------------------------------------] void setComputeRootSignature(Rhi::IRootSignature* rootSignature); void setComputePipelineState(Rhi::IComputePipelineState* computePipelineState); void setComputeResourceGroup(uint32_t rootParameterIndex, Rhi::IResourceGroup* resourceGroup); void dispatchCompute(uint32_t groupCountX, uint32_t groupCountY, uint32_t groupCountZ); //[-------------------------------------------------------] //[ Resource ] //[-------------------------------------------------------] void resolveMultisampleFramebuffer(Rhi::IRenderTarget& destinationRenderTarget, Rhi::IFramebuffer& sourceMultisampleFramebuffer); void copyResource(Rhi::IResource& destinationResource, Rhi::IResource& sourceResource); void generateMipmaps(Rhi::IResource& resource); //[-------------------------------------------------------] //[ Query ] //[-------------------------------------------------------] void resetQueryPool(Rhi::IQueryPool& queryPool, uint32_t firstQueryIndex, uint32_t numberOfQueries); void beginQuery(Rhi::IQueryPool& queryPool, uint32_t queryIndex, uint32_t queryControlFlags); void endQuery(Rhi::IQueryPool& queryPool, uint32_t queryIndex); void writeTimestampQuery(Rhi::IQueryPool& queryPool, uint32_t queryIndex); //[-------------------------------------------------------] //[ Debug ] //[-------------------------------------------------------] #ifdef RHI_DEBUG void setDebugMarker(const char* name); void beginDebugEvent(const char* name); void endDebugEvent(); #endif //[-------------------------------------------------------] //[ Public virtual Rhi::IRhi methods ] //[-------------------------------------------------------] public: [[nodiscard]] virtual const char* getName() const override; [[nodiscard]] virtual bool isInitialized() const override; [[nodiscard]] virtual bool isDebugEnabled() override; //[-------------------------------------------------------] //[ Shader language ] //[-------------------------------------------------------] [[nodiscard]] virtual uint32_t getNumberOfShaderLanguages() const override; [[nodiscard]] virtual const char* getShaderLanguageName(uint32_t index) const override; [[nodiscard]] virtual Rhi::IShaderLanguage* getShaderLanguage(const char* shaderLanguageName = nullptr) override; //[-------------------------------------------------------] //[ Resource creation ] //[-------------------------------------------------------] [[nodiscard]] virtual Rhi::IRenderPass* createRenderPass(uint32_t numberOfColorAttachments, const Rhi::TextureFormat::Enum* colorAttachmentTextureFormats, Rhi::TextureFormat::Enum depthStencilAttachmentTextureFormat = Rhi::TextureFormat::UNKNOWN, uint8_t numberOfMultisamples = 1 RHI_RESOURCE_DEBUG_NAME_PARAMETER) override; [[nodiscard]] virtual Rhi::IQueryPool* createQueryPool(Rhi::QueryType queryType, uint32_t numberOfQueries = 1 RHI_RESOURCE_DEBUG_NAME_PARAMETER) override; [[nodiscard]] virtual Rhi::ISwapChain* createSwapChain(Rhi::IRenderPass& renderPass, Rhi::WindowHandle windowHandle, bool useExternalContext = false RHI_RESOURCE_DEBUG_NAME_PARAMETER) override; [[nodiscard]] virtual Rhi::IFramebuffer* createFramebuffer(Rhi::IRenderPass& renderPass, const Rhi::FramebufferAttachment* colorFramebufferAttachments, const Rhi::FramebufferAttachment* depthStencilFramebufferAttachment = nullptr RHI_RESOURCE_DEBUG_NAME_PARAMETER) override; [[nodiscard]] virtual Rhi::IBufferManager* createBufferManager() override; [[nodiscard]] virtual Rhi::ITextureManager* createTextureManager() override; [[nodiscard]] virtual Rhi::IRootSignature* createRootSignature(const Rhi::RootSignature& rootSignature RHI_RESOURCE_DEBUG_NAME_PARAMETER) override; [[nodiscard]] virtual Rhi::IGraphicsPipelineState* createGraphicsPipelineState(const Rhi::GraphicsPipelineState& graphicsPipelineState RHI_RESOURCE_DEBUG_NAME_PARAMETER) override; [[nodiscard]] virtual Rhi::IComputePipelineState* createComputePipelineState(Rhi::IRootSignature& rootSignature, Rhi::IComputeShader& computeShader RHI_RESOURCE_DEBUG_NAME_PARAMETER) override; [[nodiscard]] virtual Rhi::ISamplerState* createSamplerState(const Rhi::SamplerState& samplerState RHI_RESOURCE_DEBUG_NAME_PARAMETER) override; //[-------------------------------------------------------] //[ Resource handling ] //[-------------------------------------------------------] [[nodiscard]] virtual bool map(Rhi::IResource& resource, uint32_t subresource, Rhi::MapType mapType, uint32_t mapFlags, Rhi::MappedSubresource& mappedSubresource) override; virtual void unmap(Rhi::IResource& resource, uint32_t subresource) override; [[nodiscard]] virtual bool getQueryPoolResults(Rhi::IQueryPool& queryPool, uint32_t numberOfDataBytes, uint8_t* data, uint32_t firstQueryIndex = 0, uint32_t numberOfQueries = 1, uint32_t strideInBytes = 0, uint32_t queryResultFlags = 0) override; //[-------------------------------------------------------] //[ Operation ] //[-------------------------------------------------------] virtual void dispatchCommandBuffer(const Rhi::CommandBuffer& commandBuffer) override; //[-------------------------------------------------------] //[ Protected virtual Rhi::RefCount methods ] //[-------------------------------------------------------] protected: virtual void selfDestruct() override; //[-------------------------------------------------------] //[ Private methods ] //[-------------------------------------------------------] private: explicit NullRhi(const NullRhi& source) = delete; NullRhi& operator =(const NullRhi& source) = delete; /** * @brief * Initialize the capabilities */ void initializeCapabilities(); //[-------------------------------------------------------] //[ Private data ] //[-------------------------------------------------------] private: Rhi::IShaderLanguage* mShaderLanguage; ///< Null shader language instance (we keep a reference to it), can be a null pointer Rhi::IRenderTarget* mRenderTarget; ///< Currently set render target (we keep a reference to it), can be a null pointer RootSignature* mGraphicsRootSignature; ///< Currently set graphics root signature (we keep a reference to it), can be a null pointer RootSignature* mComputeRootSignature; ///< Currently set compute root signature (we keep a reference to it), can be a null pointer }; //[-------------------------------------------------------] //[ NullRhi/ResourceGroup.h ] //[-------------------------------------------------------] /** * @brief * Null resource group class */ class ResourceGroup final : public Rhi::IResourceGroup { //[-------------------------------------------------------] //[ Public methods ] //[-------------------------------------------------------] public: /** * @brief * Constructor * * @param[in] rhi * Owner RHI instance * @param[in] rootParameterIndex * The root parameter index number for binding * @param[in] numberOfResources * Number of resources, having no resources is invalid * @param[in] resources * At least "numberOfResources" resource pointers, must be valid, the resource group will keep a reference to the resources * @param[in] samplerStates * If not a null pointer at least "numberOfResources" sampler state pointers, must be valid if there's at least one texture resource, the resource group will keep a reference to the sampler states */ ResourceGroup(Rhi::IRhi& rhi, uint32_t rootParameterIndex, uint32_t numberOfResources, Rhi::IResource** resources, Rhi::ISamplerState** samplerStates RHI_RESOURCE_DEBUG_NAME_PARAMETER_NO_DEFAULT) : IResourceGroup(rhi RHI_RESOURCE_DEBUG_PASS_PARAMETER), mRootParameterIndex(rootParameterIndex), mNumberOfResources(numberOfResources), mResources(RHI_MALLOC_TYPED(rhi.getContext(), Rhi::IResource*, mNumberOfResources)), mSamplerStates(nullptr) { // Process all resources and add our reference to the RHI resource for (uint32_t resourceIndex = 0; resourceIndex < mNumberOfResources; ++resourceIndex, ++resources) { Rhi::IResource* resource = *resources; RHI_ASSERT(rhi.getContext(), nullptr != resource, "Invalid null resource") mResources[resourceIndex] = resource; resource->addReference(); } if (nullptr != samplerStates) { mSamplerStates = RHI_MALLOC_TYPED(rhi.getContext(), Rhi::ISamplerState*, mNumberOfResources); for (uint32_t resourceIndex = 0; resourceIndex < mNumberOfResources; ++resourceIndex) { Rhi::ISamplerState* samplerState = mSamplerStates[resourceIndex] = samplerStates[resourceIndex]; if (nullptr != samplerState) { samplerState->addReference(); } } } } /** * @brief * Destructor */ virtual ~ResourceGroup() override { // Remove our reference from the RHI resources const Rhi::Context& context = getRhi().getContext(); if (nullptr != mSamplerStates) { for (uint32_t resourceIndex = 0; resourceIndex < mNumberOfResources; ++resourceIndex) { Rhi::ISamplerState* samplerState = mSamplerStates[resourceIndex]; if (nullptr != samplerState) { samplerState->releaseReference(); } } RHI_FREE(context, mSamplerStates); } for (uint32_t resourceIndex = 0; resourceIndex < mNumberOfResources; ++resourceIndex) { mResources[resourceIndex]->releaseReference(); } RHI_FREE(context, mResources); } /** * @brief * Return the number of resources this resource group groups together * * @return * The number of resources this resource group groups together */ [[nodiscard]] inline uint32_t getNumberOfResources() const { return mNumberOfResources; } /** * @brief * Return the RHI resources * * @return * The RHI resources, don't release or destroy the returned pointer */ [[nodiscard]] inline Rhi::IResource** getResources() const { return mResources; } //[-------------------------------------------------------] //[ Protected virtual Rhi::RefCount methods ] //[-------------------------------------------------------] protected: inline virtual void selfDestruct() override { RHI_DELETE(getRhi().getContext(), ResourceGroup, this); } //[-------------------------------------------------------] //[ Private methods ] //[-------------------------------------------------------] private: explicit ResourceGroup(const ResourceGroup& source) = delete; ResourceGroup& operator =(const ResourceGroup& source) = delete; //[-------------------------------------------------------] //[ Private data ] //[-------------------------------------------------------] private: uint32_t mRootParameterIndex; ///< The root parameter index number for binding uint32_t mNumberOfResources; ///< Number of resources this resource group groups together Rhi::IResource** mResources; ///< RHI resources, we keep a reference to it Rhi::ISamplerState** mSamplerStates; ///< Sampler states, we keep a reference to it }; //[-------------------------------------------------------] //[ NullRhi/RootSignature.h ] //[-------------------------------------------------------] /** * @brief * Null root signature ("pipeline layout" in Vulkan terminology) class */ class RootSignature final : public Rhi::IRootSignature { //[-------------------------------------------------------] //[ Public methods ] //[-------------------------------------------------------] public: /** * @brief * Constructor * * @param[in] nullRhi * Owner null RHI instance * @param[in] rootSignature * Root signature to use */ RootSignature(NullRhi& nullRhi, const Rhi::RootSignature& rootSignature RHI_RESOURCE_DEBUG_NAME_PARAMETER_NO_DEFAULT) : IRootSignature(nullRhi RHI_RESOURCE_DEBUG_PASS_PARAMETER), mRootSignature(rootSignature) { const Rhi::Context& context = nullRhi.getContext(); { // Copy the parameter data const uint32_t numberOfParameters = mRootSignature.numberOfParameters; if (numberOfParameters > 0) { mRootSignature.parameters = RHI_MALLOC_TYPED(context, Rhi::RootParameter, numberOfParameters); Rhi::RootParameter* destinationRootParameters = const_cast<Rhi::RootParameter*>(mRootSignature.parameters); memcpy(destinationRootParameters, rootSignature.parameters, sizeof(Rhi::RootParameter) * numberOfParameters); // Copy the descriptor table data for (uint32_t i = 0; i < numberOfParameters; ++i) { Rhi::RootParameter& destinationRootParameter = destinationRootParameters[i]; const Rhi::RootParameter& sourceRootParameter = rootSignature.parameters[i]; if (Rhi::RootParameterType::DESCRIPTOR_TABLE == destinationRootParameter.parameterType) { const uint32_t numberOfDescriptorRanges = destinationRootParameter.descriptorTable.numberOfDescriptorRanges; destinationRootParameter.descriptorTable.descriptorRanges = reinterpret_cast<uintptr_t>(RHI_MALLOC_TYPED(context, Rhi::DescriptorRange, numberOfDescriptorRanges)); memcpy(reinterpret_cast<Rhi::DescriptorRange*>(destinationRootParameter.descriptorTable.descriptorRanges), reinterpret_cast<const Rhi::DescriptorRange*>(sourceRootParameter.descriptorTable.descriptorRanges), sizeof(Rhi::DescriptorRange) * numberOfDescriptorRanges); } } } } { // Copy the static sampler data const uint32_t numberOfStaticSamplers = mRootSignature.numberOfStaticSamplers; if (numberOfStaticSamplers > 0) { mRootSignature.staticSamplers = RHI_MALLOC_TYPED(context, Rhi::StaticSampler, numberOfStaticSamplers); memcpy(const_cast<Rhi::StaticSampler*>(mRootSignature.staticSamplers), rootSignature.staticSamplers, sizeof(Rhi::StaticSampler) * numberOfStaticSamplers); } } } /** * @brief * Destructor */ virtual ~RootSignature() override { const Rhi::Context& context = getRhi().getContext(); if (nullptr != mRootSignature.parameters) { for (uint32_t i = 0; i < mRootSignature.numberOfParameters; ++i) { const Rhi::RootParameter& rootParameter = mRootSignature.parameters[i]; if (Rhi::RootParameterType::DESCRIPTOR_TABLE == rootParameter.parameterType) { RHI_FREE(context, reinterpret_cast<Rhi::DescriptorRange*>(rootParameter.descriptorTable.descriptorRanges)); } } RHI_FREE(context, const_cast<Rhi::RootParameter*>(mRootSignature.parameters)); } RHI_FREE(context, const_cast<Rhi::StaticSampler*>(mRootSignature.staticSamplers)); } /** * @brief * Return the root signature data * * @return * The root signature data */ [[nodiscard]] inline const Rhi::RootSignature& getRootSignature() const { return mRootSignature; } //[-------------------------------------------------------] //[ Public virtual Rhi::IRootSignature methods ] //[-------------------------------------------------------] public: virtual Rhi::IResourceGroup* createResourceGroup(uint32_t rootParameterIndex, uint32_t numberOfResources, Rhi::IResource** resources, Rhi::ISamplerState** samplerStates = nullptr RHI_RESOURCE_DEBUG_NAME_PARAMETER) override { Rhi::IRhi& rhi = getRhi(); // Sanity checks RHI_ASSERT(rhi.getContext(), rootParameterIndex < mRootSignature.numberOfParameters, "The null root parameter index is out-of-bounds") RHI_ASSERT(rhi.getContext(), numberOfResources > 0, "The number of null resources must not be zero") RHI_ASSERT(rhi.getContext(), nullptr != resources, "The null resource pointers must be valid") // Create resource group return RHI_NEW(rhi.getContext(), ResourceGroup)(rhi, rootParameterIndex, numberOfResources, resources, samplerStates RHI_RESOURCE_DEBUG_PASS_PARAMETER); } //[-------------------------------------------------------] //[ Protected virtual Rhi::RefCount methods ] //[-------------------------------------------------------] protected: inline virtual void selfDestruct() override { RHI_DELETE(getRhi().getContext(), RootSignature, this); } //[-------------------------------------------------------] //[ Private methods ] //[-------------------------------------------------------] private: explicit RootSignature(const RootSignature& source) = delete; RootSignature& operator =(const RootSignature& source) = delete; //[-------------------------------------------------------] //[ Private data ] //[-------------------------------------------------------] private: Rhi::RootSignature mRootSignature; }; //[-------------------------------------------------------] //[ NullRhi/Buffer/VertexBuffer.h ] //[-------------------------------------------------------] /** * @brief * Null vertex buffer object (VBO, "array buffer" in OpenGL terminology) class */ class VertexBuffer final : public Rhi::IVertexBuffer { //[-------------------------------------------------------] //[ Public methods ] //[-------------------------------------------------------] public: /** * @brief * Constructor * * @param[in] nullRhi * Owner null RHI instance */ inline explicit VertexBuffer(NullRhi& nullRhi RHI_RESOURCE_DEBUG_NAME_PARAMETER_NO_DEFAULT) : IVertexBuffer(nullRhi RHI_RESOURCE_DEBUG_PASS_PARAMETER) {} /** * @brief * Destructor */ inline virtual ~VertexBuffer() override {} //[-------------------------------------------------------] //[ Protected virtual Rhi::RefCount methods ] //[-------------------------------------------------------] protected: inline virtual void selfDestruct() override { RHI_DELETE(getRhi().getContext(), VertexBuffer, this); } //[-------------------------------------------------------] //[ Private methods ] //[-------------------------------------------------------] private: explicit VertexBuffer(const VertexBuffer& source) = delete; VertexBuffer& operator =(const VertexBuffer& source) = delete; }; //[-------------------------------------------------------] //[ NullRhi/Buffer/IndexBuffer.h ] //[-------------------------------------------------------] /** * @brief * Null index buffer object (IBO, "element array buffer" in OpenGL terminology) class */ class IndexBuffer final : public Rhi::IIndexBuffer { //[-------------------------------------------------------] //[ Public methods ] //[-------------------------------------------------------] public: /** * @brief * Constructor * * @param[in] nullRhi * Owner null RHI instance */ inline explicit IndexBuffer(NullRhi& nullRhi RHI_RESOURCE_DEBUG_NAME_PARAMETER_NO_DEFAULT) : IIndexBuffer(nullRhi RHI_RESOURCE_DEBUG_PASS_PARAMETER) {} /** * @brief * Destructor */ inline virtual ~IndexBuffer() override {} //[-------------------------------------------------------] //[ Protected virtual Rhi::RefCount methods ] //[-------------------------------------------------------] protected: inline virtual void selfDestruct() override { RHI_DELETE(getRhi().getContext(), IndexBuffer, this); } //[-------------------------------------------------------] //[ Private methods ] //[-------------------------------------------------------] private: explicit IndexBuffer(const IndexBuffer& source) = delete; IndexBuffer& operator =(const IndexBuffer& source) = delete; }; //[-------------------------------------------------------] //[ NullRhi/Buffer/VertexArray.h ] //[-------------------------------------------------------] /** * @brief * Null vertex array class */ class VertexArray final : public Rhi::IVertexArray { //[-------------------------------------------------------] //[ Public methods ] //[-------------------------------------------------------] public: /** * @brief * Constructor * * @param[in] nullRhi * Owner null RHI instance * @param[in] id * The unique compact vertex array ID */ inline explicit VertexArray(NullRhi& nullRhi, uint16_t id RHI_RESOURCE_DEBUG_NAME_PARAMETER_NO_DEFAULT) : IVertexArray(nullRhi, id RHI_RESOURCE_DEBUG_PASS_PARAMETER) {} /** * @brief * Destructor */ inline virtual ~VertexArray() override { // Free the unique compact vertex array ID static_cast<NullRhi&>(getRhi()).VertexArrayMakeId.DestroyID(getId()); } //[-------------------------------------------------------] //[ Protected virtual Rhi::RefCount methods ] //[-------------------------------------------------------] protected: inline virtual void selfDestruct() override { RHI_DELETE(getRhi().getContext(), VertexArray, this); } //[-------------------------------------------------------] //[ Private methods ] //[-------------------------------------------------------] private: explicit VertexArray(const VertexArray& source) = delete; VertexArray& operator =(const VertexArray& source) = delete; }; //[-------------------------------------------------------] //[ NullRhi/Buffer/TextureBuffer.h ] //[-------------------------------------------------------] /** * @brief * Null texture buffer object (TBO) class */ class TextureBuffer final : public Rhi::ITextureBuffer { //[-------------------------------------------------------] //[ Public methods ] //[-------------------------------------------------------] public: /** * @brief * Constructor * * @param[in] nullRhi * Owner null RHI instance */ inline explicit TextureBuffer(NullRhi& nullRhi RHI_RESOURCE_DEBUG_NAME_PARAMETER_NO_DEFAULT) : ITextureBuffer(nullRhi RHI_RESOURCE_DEBUG_PASS_PARAMETER) {} /** * @brief * Destructor */ inline virtual ~TextureBuffer() override {} //[-------------------------------------------------------] //[ Protected virtual Rhi::RefCount methods ] //[-------------------------------------------------------] protected: inline virtual void selfDestruct() override { RHI_DELETE(getRhi().getContext(), TextureBuffer, this); } //[-------------------------------------------------------] //[ Private methods ] //[-------------------------------------------------------] private: explicit TextureBuffer(const TextureBuffer& source) = delete; TextureBuffer& operator =(const TextureBuffer& source) = delete; }; //[-------------------------------------------------------] //[ NullRhi/Buffer/StructuredBuffer.h ] //[-------------------------------------------------------] /** * @brief * Null structured buffer object (SBO) class */ class StructuredBuffer final : public Rhi::IStructuredBuffer { //[-------------------------------------------------------] //[ Public methods ] //[-------------------------------------------------------] public: /** * @brief * Constructor * * @param[in] nullRhi * Owner null RHI instance */ inline explicit StructuredBuffer(NullRhi& nullRhi RHI_RESOURCE_DEBUG_NAME_PARAMETER_NO_DEFAULT) : IStructuredBuffer(nullRhi RHI_RESOURCE_DEBUG_PASS_PARAMETER) {} /** * @brief * Destructor */ inline virtual ~StructuredBuffer() override {} //[-------------------------------------------------------] //[ Protected virtual Rhi::RefCount methods ] //[-------------------------------------------------------] protected: inline virtual void selfDestruct() override { RHI_DELETE(getRhi().getContext(), StructuredBuffer, this); } //[-------------------------------------------------------] //[ Private methods ] //[-------------------------------------------------------] private: explicit StructuredBuffer(const StructuredBuffer& source) = delete; StructuredBuffer& operator =(const StructuredBuffer& source) = delete; }; //[-------------------------------------------------------] //[ NullRhi/Buffer/IndirectBuffer.h ] //[-------------------------------------------------------] /** * @brief * Null indirect buffer object class */ class IndirectBuffer final : public Rhi::IIndirectBuffer { //[-------------------------------------------------------] //[ Public methods ] //[-------------------------------------------------------] public: /** * @brief * Constructor * * @param[in] nullRhi * Owner null RHI instance */ inline explicit IndirectBuffer(NullRhi& nullRhi RHI_RESOURCE_DEBUG_NAME_PARAMETER_NO_DEFAULT) : IIndirectBuffer(nullRhi RHI_RESOURCE_DEBUG_PASS_PARAMETER) {} /** * @brief * Destructor */ inline virtual ~IndirectBuffer() override {} //[-------------------------------------------------------] //[ Public virtual Rhi::IIndirectBuffer methods ] //[-------------------------------------------------------] public: [[nodiscard]] inline virtual const uint8_t* getEmulationData() const override { return nullptr; } //[-------------------------------------------------------] //[ Protected virtual Rhi::RefCount methods ] //[-------------------------------------------------------] protected: inline virtual void selfDestruct() override { RHI_DELETE(getRhi().getContext(), IndirectBuffer, this); } //[-------------------------------------------------------] //[ Private methods ] //[-------------------------------------------------------] private: explicit IndirectBuffer(const IndirectBuffer& source) = delete; IndirectBuffer& operator =(const IndirectBuffer& source) = delete; }; //[-------------------------------------------------------] //[ NullRhi/Buffer/UniformBuffer.h ] //[-------------------------------------------------------] /** * @brief * Null uniform buffer object (UBO, "constant buffer" in Direct3D terminology) class */ class UniformBuffer final : public Rhi::IUniformBuffer { //[-------------------------------------------------------] //[ Public methods ] //[-------------------------------------------------------] public: /** * @brief * Constructor * * @param[in] nullRhi * Owner null RHI instance */ inline explicit UniformBuffer(NullRhi& nullRhi RHI_RESOURCE_DEBUG_NAME_PARAMETER_NO_DEFAULT) : IUniformBuffer(nullRhi RHI_RESOURCE_DEBUG_PASS_PARAMETER) {} /** * @brief * Destructor */ inline virtual ~UniformBuffer() override {} //[-------------------------------------------------------] //[ Protected virtual Rhi::RefCount methods ] //[-------------------------------------------------------] protected: inline virtual void selfDestruct() override { RHI_DELETE(getRhi().getContext(), UniformBuffer, this); } //[-------------------------------------------------------] //[ Private methods ] //[-------------------------------------------------------] private: explicit UniformBuffer(const UniformBuffer& source) = delete; UniformBuffer& operator =(const UniformBuffer& source) = delete; }; //[-------------------------------------------------------] //[ NullRhi/Buffer/BufferManager.h ] //[-------------------------------------------------------] /** * @brief * Null buffer manager interface */ class BufferManager final : public Rhi::IBufferManager { //[-------------------------------------------------------] //[ Public methods ] //[-------------------------------------------------------] public: /** * @brief * Constructor * * @param[in] nullRhi * Owner null RHI instance */ inline explicit BufferManager(NullRhi& nullRhi) : IBufferManager(nullRhi) {} /** * @brief * Destructor */ inline virtual ~BufferManager() override {} //[-------------------------------------------------------] //[ Public virtual Rhi::IBufferManager methods ] //[-------------------------------------------------------] public: [[nodiscard]] inline virtual Rhi::IVertexBuffer* createVertexBuffer([[maybe_unused]] uint32_t numberOfBytes, [[maybe_unused]] const void* data = nullptr, [[maybe_unused]] uint32_t bufferFlags = 0, [[maybe_unused]] Rhi::BufferUsage bufferUsage = Rhi::BufferUsage::STATIC_DRAW RHI_RESOURCE_DEBUG_NAME_PARAMETER) override { NullRhi& nullRhi = static_cast<NullRhi&>(getRhi()); return RHI_NEW(nullRhi.getContext(), VertexBuffer)(nullRhi RHI_RESOURCE_DEBUG_PASS_PARAMETER); } [[nodiscard]] inline virtual Rhi::IIndexBuffer* createIndexBuffer([[maybe_unused]] uint32_t numberOfBytes, [[maybe_unused]] const void* data = nullptr, [[maybe_unused]] uint32_t bufferFlags = 0, [[maybe_unused]] Rhi::BufferUsage bufferUsage = Rhi::BufferUsage::STATIC_DRAW, [[maybe_unused]] Rhi::IndexBufferFormat::Enum indexBufferFormat = Rhi::IndexBufferFormat::UNSIGNED_SHORT RHI_RESOURCE_DEBUG_NAME_PARAMETER) override { NullRhi& nullRhi = static_cast<NullRhi&>(getRhi()); return RHI_NEW(nullRhi.getContext(), IndexBuffer)(nullRhi RHI_RESOURCE_DEBUG_PASS_PARAMETER); } [[nodiscard]] virtual Rhi::IVertexArray* createVertexArray([[maybe_unused]] const Rhi::VertexAttributes& vertexAttributes, uint32_t numberOfVertexBuffers, const Rhi::VertexArrayVertexBuffer* vertexBuffers, Rhi::IIndexBuffer* indexBuffer = nullptr RHI_RESOURCE_DEBUG_NAME_PARAMETER) override { NullRhi& nullRhi = static_cast<NullRhi&>(getRhi()); // Sanity checks #ifdef RHI_DEBUG { const Rhi::VertexArrayVertexBuffer* vertexBufferEnd = vertexBuffers + numberOfVertexBuffers; for (const Rhi::VertexArrayVertexBuffer* vertexBuffer = vertexBuffers; vertexBuffer < vertexBufferEnd; ++vertexBuffer) { RHI_ASSERT(nullRhi.getContext(), &nullRhi == &vertexBuffer->vertexBuffer->getRhi(), "Null error: The given vertex buffer resource is owned by another RHI instance") } } #endif RHI_ASSERT(nullRhi.getContext(), nullptr == indexBuffer || &nullRhi == &indexBuffer->getRhi(), "Null error: The given index buffer resource is owned by another RHI instance") // We don't keep a reference to the vertex buffers used by the vertex array attributes in here // -> Ensure a correct reference counter behaviour const Rhi::VertexArrayVertexBuffer* vertexBufferEnd = vertexBuffers + numberOfVertexBuffers; for (const Rhi::VertexArrayVertexBuffer* vertexBuffer = vertexBuffers; vertexBuffer < vertexBufferEnd; ++vertexBuffer) { vertexBuffer->vertexBuffer->addReference(); vertexBuffer->vertexBuffer->releaseReference(); } // We don't keep a reference to the index buffer in here // -> Ensure a correct reference counter behaviour if (nullptr != indexBuffer) { indexBuffer->addReference(); indexBuffer->releaseReference(); } // Create the vertex array instance uint16_t id = 0; return nullRhi.VertexArrayMakeId.CreateID(id) ? RHI_NEW(nullRhi.getContext(), VertexArray)(nullRhi, id RHI_RESOURCE_DEBUG_PASS_PARAMETER) : nullptr; } [[nodiscard]] inline virtual Rhi::ITextureBuffer* createTextureBuffer([[maybe_unused]] uint32_t numberOfBytes, [[maybe_unused]] const void* data = nullptr, [[maybe_unused]] uint32_t bufferFlags = Rhi::BufferFlag::SHADER_RESOURCE, [[maybe_unused]] Rhi::BufferUsage bufferUsage = Rhi::BufferUsage::STATIC_DRAW, [[maybe_unused]] Rhi::TextureFormat::Enum textureFormat = Rhi::TextureFormat::R32G32B32A32F RHI_RESOURCE_DEBUG_NAME_PARAMETER) override { NullRhi& nullRhi = static_cast<NullRhi&>(getRhi()); // Sanity check RHI_ASSERT(nullRhi.getContext(), (numberOfBytes % Rhi::TextureFormat::getNumberOfBytesPerElement(textureFormat)) == 0, "The null texture buffer size must be a multiple of the selected texture format bytes per texel") // Create the texture buffer return RHI_NEW(nullRhi.getContext(), TextureBuffer)(nullRhi RHI_RESOURCE_DEBUG_PASS_PARAMETER); } [[nodiscard]] inline virtual Rhi::IStructuredBuffer* createStructuredBuffer([[maybe_unused]] uint32_t numberOfBytes, [[maybe_unused]] const void* data, [[maybe_unused]] uint32_t bufferFlags, [[maybe_unused]] Rhi::BufferUsage bufferUsage, [[maybe_unused]] uint32_t numberOfStructureBytes RHI_RESOURCE_DEBUG_NAME_PARAMETER) override { NullRhi& nullRhi = static_cast<NullRhi&>(getRhi()); // Sanity checks RHI_ASSERT(nullRhi.getContext(), (numberOfBytes % numberOfStructureBytes) == 0, "The null structured buffer size must be a multiple of the given number of structure bytes") RHI_ASSERT(nullRhi.getContext(), (numberOfBytes % (sizeof(float) * 4)) == 0, "Performance: The null structured buffer should be aligned to a 128-bit stride, see \"Understanding Structured Buffer Performance\" by Evan Hart, posted Apr 17 2015 at 11:33AM - https://developer.nvidia.com/content/understanding-structured-buffer-performance") // Create the structured buffer return RHI_NEW(nullRhi.getContext(), StructuredBuffer)(nullRhi RHI_RESOURCE_DEBUG_PASS_PARAMETER); } [[nodiscard]] inline virtual Rhi::IIndirectBuffer* createIndirectBuffer([[maybe_unused]] uint32_t numberOfBytes, [[maybe_unused]] const void* data = nullptr, [[maybe_unused]] uint32_t indirectBufferFlags = 0, [[maybe_unused]] Rhi::BufferUsage bufferUsage = Rhi::BufferUsage::STATIC_DRAW RHI_RESOURCE_DEBUG_NAME_PARAMETER) override { NullRhi& nullRhi = static_cast<NullRhi&>(getRhi()); // Sanity checks RHI_ASSERT(nullRhi.getContext(), (indirectBufferFlags & Rhi::IndirectBufferFlag::DRAW_ARGUMENTS) != 0 || (indirectBufferFlags & Rhi::IndirectBufferFlag::DRAW_INDEXED_ARGUMENTS) != 0, "Invalid null flags, indirect buffer element type specification \"DRAW_ARGUMENTS\" or \"DRAW_INDEXED_ARGUMENTS\" is missing") RHI_ASSERT(nullRhi.getContext(), !((indirectBufferFlags & Rhi::IndirectBufferFlag::DRAW_ARGUMENTS) != 0 && (indirectBufferFlags & Rhi::IndirectBufferFlag::DRAW_INDEXED_ARGUMENTS) != 0), "Invalid null flags, indirect buffer element type specification \"DRAW_ARGUMENTS\" or \"DRAW_INDEXED_ARGUMENTS\" must be set, but not both at one and the same time") RHI_ASSERT(nullRhi.getContext(), (indirectBufferFlags & Rhi::IndirectBufferFlag::DRAW_ARGUMENTS) == 0 || (numberOfBytes % sizeof(Rhi::DrawArguments)) == 0, "Null indirect buffer element type flags specification is \"DRAW_ARGUMENTS\" but the given number of bytes don't align to this") RHI_ASSERT(nullRhi.getContext(), (indirectBufferFlags & Rhi::IndirectBufferFlag::DRAW_INDEXED_ARGUMENTS) == 0 || (numberOfBytes % sizeof(Rhi::DrawIndexedArguments)) == 0, "Null indirect buffer element type flags specification is \"DRAW_INDEXED_ARGUMENTS\" but the given number of bytes don't align to this") // Create indirect buffer return RHI_NEW(nullRhi.getContext(), IndirectBuffer)(nullRhi RHI_RESOURCE_DEBUG_PASS_PARAMETER); } [[nodiscard]] inline virtual Rhi::IUniformBuffer* createUniformBuffer([[maybe_unused]] uint32_t numberOfBytes, [[maybe_unused]] const void* data = nullptr, [[maybe_unused]] Rhi::BufferUsage bufferUsage = Rhi::BufferUsage::STATIC_DRAW RHI_RESOURCE_DEBUG_NAME_PARAMETER) override { NullRhi& nullRhi = static_cast<NullRhi&>(getRhi()); // Don't remove this reminder comment block: There are no buffer flags by intent since an uniform buffer can't be used for unordered access and as a consequence an uniform buffer must always used as shader resource to not be pointless // RHI_ASSERT(nullRhi.getContext(), (bufferFlags & Rhi::BufferFlag::UNORDERED_ACCESS) == 0, "Invalid null buffer flags, uniform buffer can't be used for unordered access") // RHI_ASSERT(nullRhi.getContext(), (bufferFlags & Rhi::BufferFlag::SHADER_RESOURCE) != 0, "Invalid null buffer flags, uniform buffer must be used as shader resource") // Create the uniform buffer return RHI_NEW(nullRhi.getContext(), UniformBuffer)(nullRhi RHI_RESOURCE_DEBUG_PASS_PARAMETER); } //[-------------------------------------------------------] //[ Protected virtual Rhi::RefCount methods ] //[-------------------------------------------------------] protected: inline virtual void selfDestruct() override { RHI_DELETE(getRhi().getContext(), BufferManager, this); } //[-------------------------------------------------------] //[ Private methods ] //[-------------------------------------------------------] private: explicit BufferManager(const BufferManager& source) = delete; BufferManager& operator =(const BufferManager& source) = delete; }; //[-------------------------------------------------------] //[ NullRhi/Texture/Texture1D.h ] //[-------------------------------------------------------] /** * @brief * Null 1D texture class */ class Texture1D final : public Rhi::ITexture1D { //[-------------------------------------------------------] //[ Public methods ] //[-------------------------------------------------------] public: /** * @brief * Constructor * * @param[in] nullRhi * Owner null RHI instance * @param[in] width * The width of the texture */ inline Texture1D(NullRhi& nullRhi, uint32_t width RHI_RESOURCE_DEBUG_NAME_PARAMETER_NO_DEFAULT) : ITexture1D(nullRhi, width RHI_RESOURCE_DEBUG_PASS_PARAMETER) {} /** * @brief * Destructor */ inline virtual ~Texture1D() override {} //[-------------------------------------------------------] //[ Protected virtual Rhi::RefCount methods ] //[-------------------------------------------------------] protected: inline virtual void selfDestruct() override { RHI_DELETE(getRhi().getContext(), Texture1D, this); } //[-------------------------------------------------------] //[ Private methods ] //[-------------------------------------------------------] private: explicit Texture1D(const Texture1D& source) = delete; Texture1D& operator =(const Texture1D& source) = delete; }; //[-------------------------------------------------------] //[ NullRhi/Texture/Texture1DArray.h ] //[-------------------------------------------------------] /** * @brief * Null 1D array texture class */ class Texture1DArray final : public Rhi::ITexture1DArray { //[-------------------------------------------------------] //[ Public methods ] //[-------------------------------------------------------] public: /** * @brief * Constructor * * @param[in] nullRhi * Owner null RHI instance * @param[in] width * The width of the texture * @param[in] numberOfSlices * The number of slices */ inline Texture1DArray(NullRhi& nullRhi, uint32_t width, uint32_t numberOfSlices RHI_RESOURCE_DEBUG_NAME_PARAMETER_NO_DEFAULT) : ITexture1DArray(nullRhi, width, numberOfSlices RHI_RESOURCE_DEBUG_PASS_PARAMETER) {} /** * @brief * Destructor */ inline virtual ~Texture1DArray() override {} //[-------------------------------------------------------] //[ Protected virtual Rhi::RefCount methods ] //[-------------------------------------------------------] protected: inline virtual void selfDestruct() override { RHI_DELETE(getRhi().getContext(), Texture1DArray, this); } //[-------------------------------------------------------] //[ Private methods ] //[-------------------------------------------------------] private: explicit Texture1DArray(const Texture1DArray& source) = delete; Texture1DArray& operator =(const Texture1DArray& source) = delete; }; //[-------------------------------------------------------] //[ NullRhi/Texture/Texture2D.h ] //[-------------------------------------------------------] /** * @brief * Null 2D texture class */ class Texture2D final : public Rhi::ITexture2D { //[-------------------------------------------------------] //[ Public methods ] //[-------------------------------------------------------] public: /** * @brief * Constructor * * @param[in] nullRhi * Owner null RHI instance * @param[in] width * The width of the texture * @param[in] height * The height of the texture */ inline Texture2D(NullRhi& nullRhi, uint32_t width, uint32_t height RHI_RESOURCE_DEBUG_NAME_PARAMETER_NO_DEFAULT) : ITexture2D(nullRhi, width, height RHI_RESOURCE_DEBUG_PASS_PARAMETER) {} /** * @brief * Destructor */ inline virtual ~Texture2D() override {} //[-------------------------------------------------------] //[ Protected virtual Rhi::RefCount methods ] //[-------------------------------------------------------] protected: inline virtual void selfDestruct() override { RHI_DELETE(getRhi().getContext(), Texture2D, this); } //[-------------------------------------------------------] //[ Private methods ] //[-------------------------------------------------------] private: explicit Texture2D(const Texture2D& source) = delete; Texture2D& operator =(const Texture2D& source) = delete; }; //[-------------------------------------------------------] //[ NullRhi/Texture/Texture2DArray.h ] //[-------------------------------------------------------] /** * @brief * Null 2D array texture class */ class Texture2DArray final : public Rhi::ITexture2DArray { //[-------------------------------------------------------] //[ Public methods ] //[-------------------------------------------------------] public: /** * @brief * Constructor * * @param[in] nullRhi * Owner null RHI instance * @param[in] width * The width of the texture * @param[in] height * The height of the texture * @param[in] numberOfSlices * The number of slices */ inline Texture2DArray(NullRhi& nullRhi, uint32_t width, uint32_t height, uint32_t numberOfSlices RHI_RESOURCE_DEBUG_NAME_PARAMETER_NO_DEFAULT) : ITexture2DArray(nullRhi, width, height, numberOfSlices RHI_RESOURCE_DEBUG_PASS_PARAMETER) {} /** * @brief * Destructor */ inline virtual ~Texture2DArray() override {} //[-------------------------------------------------------] //[ Protected virtual Rhi::RefCount methods ] //[-------------------------------------------------------] protected: inline virtual void selfDestruct() override { RHI_DELETE(getRhi().getContext(), Texture2DArray, this); } //[-------------------------------------------------------] //[ Private methods ] //[-------------------------------------------------------] private: explicit Texture2DArray(const Texture2DArray& source) = delete; Texture2DArray& operator =(const Texture2DArray& source) = delete; }; //[-------------------------------------------------------] //[ NullRhi/Texture/Texture3D.h ] //[-------------------------------------------------------] /** * @brief * Null 3D texture class */ class Texture3D final : public Rhi::ITexture3D { //[-------------------------------------------------------] //[ Public methods ] //[-------------------------------------------------------] public: /** * @brief * Constructor * * @param[in] nullRhi * Owner null RHI instance * @param[in] width * The width of the texture * @param[in] height * The height of the texture * @param[in] depth * The depth of the texture */ inline Texture3D(NullRhi& nullRhi, uint32_t width, uint32_t height, uint32_t depth RHI_RESOURCE_DEBUG_NAME_PARAMETER_NO_DEFAULT) : ITexture3D(nullRhi, width, height, depth RHI_RESOURCE_DEBUG_PASS_PARAMETER) {} /** * @brief * Destructor */ inline virtual ~Texture3D() override {} //[-------------------------------------------------------] //[ Protected virtual Rhi::RefCount methods ] //[-------------------------------------------------------] protected: inline virtual void selfDestruct() override { RHI_DELETE(getRhi().getContext(), Texture3D, this); } //[-------------------------------------------------------] //[ Private methods ] //[-------------------------------------------------------] private: explicit Texture3D(const Texture3D& source) = delete; Texture3D& operator =(const Texture3D& source) = delete; }; //[-------------------------------------------------------] //[ NullRhi/Texture/TextureCube.h ] //[-------------------------------------------------------] /** * @brief * Null cube texture class */ class TextureCube final : public Rhi::ITextureCube { //[-------------------------------------------------------] //[ Public methods ] //[-------------------------------------------------------] public: /** * @brief * Constructor * * @param[in] nullRhi * Owner null RHI instance * @param[in] width * The width of the texture */ inline TextureCube(NullRhi& nullRhi, uint32_t width RHI_RESOURCE_DEBUG_NAME_PARAMETER_NO_DEFAULT) : ITextureCube(nullRhi, width RHI_RESOURCE_DEBUG_PASS_PARAMETER) {} /** * @brief * Destructor */ inline virtual ~TextureCube() override {} //[-------------------------------------------------------] //[ Protected virtual Rhi::RefCount methods ] //[-------------------------------------------------------] protected: inline virtual void selfDestruct() override { RHI_DELETE(getRhi().getContext(), TextureCube, this); } //[-------------------------------------------------------] //[ Private methods ] //[-------------------------------------------------------] private: explicit TextureCube(const TextureCube& source) = delete; TextureCube& operator =(const TextureCube& source) = delete; }; //[-------------------------------------------------------] //[ NullRhi/Texture/TextureCubeArray.h ] //[-------------------------------------------------------] /** * @brief * Null cube array texture class */ class TextureCubeArray final : public Rhi::ITextureCubeArray { //[-------------------------------------------------------] //[ Public methods ] //[-------------------------------------------------------] public: /** * @brief * Constructor * * @param[in] nullRhi * Owner null RHI instance * @param[in] width * The width of the texture * @param[in] numberOfSlices * The number of slices */ inline TextureCubeArray(NullRhi& nullRhi, uint32_t width, uint32_t numberOfSlices RHI_RESOURCE_DEBUG_NAME_PARAMETER_NO_DEFAULT) : ITextureCubeArray(nullRhi, width, numberOfSlices RHI_RESOURCE_DEBUG_PASS_PARAMETER) {} /** * @brief * Destructor */ inline virtual ~TextureCubeArray() override {} //[-------------------------------------------------------] //[ Protected virtual Rhi::RefCount methods ] //[-------------------------------------------------------] protected: inline virtual void selfDestruct() override { RHI_DELETE(getRhi().getContext(), TextureCubeArray, this); } //[-------------------------------------------------------] //[ Private methods ] //[-------------------------------------------------------] private: explicit TextureCubeArray(const TextureCubeArray& source) = delete; TextureCubeArray& operator =(const TextureCubeArray& source) = delete; }; //[-------------------------------------------------------] //[ NullRhi/Texture/TextureManager.h ] //[-------------------------------------------------------] /** * @brief * Null texture manager interface */ class TextureManager final : public Rhi::ITextureManager { //[-------------------------------------------------------] //[ Public methods ] //[-------------------------------------------------------] public: /** * @brief * Constructor * * @param[in] nullRhi * Owner null RHI instance */ inline explicit TextureManager(NullRhi& nullRhi) : ITextureManager(nullRhi) {} /** * @brief * Destructor */ inline virtual ~TextureManager() override {} //[-------------------------------------------------------] //[ Public virtual Rhi::ITextureManager methods ] //[-------------------------------------------------------] public: [[nodiscard]] virtual Rhi::ITexture1D* createTexture1D(uint32_t width, [[maybe_unused]] Rhi::TextureFormat::Enum textureFormat, [[maybe_unused]] const void* data = nullptr, [[maybe_unused]] uint32_t textureFlags = 0, [[maybe_unused]] Rhi::TextureUsage textureUsage = Rhi::TextureUsage::DEFAULT RHI_RESOURCE_DEBUG_NAME_PARAMETER) override { NullRhi& nullRhi = static_cast<NullRhi&>(getRhi()); // Sanity check RHI_ASSERT(nullRhi.getContext(), width > 0, "Null create texture 1D was called with invalid parameters") // Create 1D texture resource return RHI_NEW(nullRhi.getContext(), Texture1D)(nullRhi, width RHI_RESOURCE_DEBUG_PASS_PARAMETER); } [[nodiscard]] virtual Rhi::ITexture1DArray* createTexture1DArray(uint32_t width, uint32_t numberOfSlices, [[maybe_unused]] Rhi::TextureFormat::Enum textureFormat, [[maybe_unused]] const void* data = nullptr, [[maybe_unused]] uint32_t textureFlags = 0, [[maybe_unused]] Rhi::TextureUsage textureUsage = Rhi::TextureUsage::DEFAULT RHI_RESOURCE_DEBUG_NAME_PARAMETER) override { NullRhi& nullRhi = static_cast<NullRhi&>(getRhi()); // Sanity check RHI_ASSERT(nullRhi.getContext(), width > 0 && numberOfSlices > 0, "Null create texture 1D array was called with invalid parameters") // Create 1D texture array resource return RHI_NEW(nullRhi.getContext(), Texture1DArray)(nullRhi, width, numberOfSlices RHI_RESOURCE_DEBUG_PASS_PARAMETER); } [[nodiscard]] virtual Rhi::ITexture2D* createTexture2D(uint32_t width, uint32_t height, [[maybe_unused]] Rhi::TextureFormat::Enum textureFormat, [[maybe_unused]] const void* data = nullptr, [[maybe_unused]] uint32_t textureFlags = 0, [[maybe_unused]] Rhi::TextureUsage textureUsage = Rhi::TextureUsage::DEFAULT, [[maybe_unused]] uint8_t numberOfMultisamples = 1, [[maybe_unused]] const Rhi::OptimizedTextureClearValue* optimizedTextureClearValue = nullptr RHI_RESOURCE_DEBUG_NAME_PARAMETER) override { NullRhi& nullRhi = static_cast<NullRhi&>(getRhi()); // Sanity check RHI_ASSERT(nullRhi.getContext(), width > 0 && height > 0, "Null create texture 2D was called with invalid parameters") // Create 2D texture resource return RHI_NEW(nullRhi.getContext(), Texture2D)(nullRhi, width, height RHI_RESOURCE_DEBUG_PASS_PARAMETER); } [[nodiscard]] virtual Rhi::ITexture2DArray* createTexture2DArray(uint32_t width, uint32_t height, uint32_t numberOfSlices, [[maybe_unused]] Rhi::TextureFormat::Enum textureFormat, [[maybe_unused]] const void* data = nullptr, [[maybe_unused]] uint32_t textureFlags = 0, [[maybe_unused]] Rhi::TextureUsage textureUsage = Rhi::TextureUsage::DEFAULT RHI_RESOURCE_DEBUG_NAME_PARAMETER) override { NullRhi& nullRhi = static_cast<NullRhi&>(getRhi()); // Sanity check RHI_ASSERT(nullRhi.getContext(), width > 0 && height > 0 && numberOfSlices > 0, "Null create texture 2D array was called with invalid parameters") // Create 2D texture array resource return RHI_NEW(nullRhi.getContext(), Texture2DArray)(nullRhi, width, height, numberOfSlices RHI_RESOURCE_DEBUG_PASS_PARAMETER); } [[nodiscard]] virtual Rhi::ITexture3D* createTexture3D(uint32_t width, uint32_t height, uint32_t depth, [[maybe_unused]] Rhi::TextureFormat::Enum textureFormat, [[maybe_unused]] const void* data = nullptr, [[maybe_unused]] uint32_t textureFlags = 0, [[maybe_unused]] Rhi::TextureUsage textureUsage = Rhi::TextureUsage::DEFAULT RHI_RESOURCE_DEBUG_NAME_PARAMETER) override { NullRhi& nullRhi = static_cast<NullRhi&>(getRhi()); // Sanity check RHI_ASSERT(nullRhi.getContext(), width > 0 && height > 0 && depth > 0, "Null create texture 3D was called with invalid parameters") // Create 3D texture resource return RHI_NEW(nullRhi.getContext(), Texture3D)(nullRhi, width, height, depth RHI_RESOURCE_DEBUG_PASS_PARAMETER); } [[nodiscard]] virtual Rhi::ITextureCube* createTextureCube(uint32_t width, [[maybe_unused]] Rhi::TextureFormat::Enum textureFormat, [[maybe_unused]] const void* data = nullptr, [[maybe_unused]] uint32_t textureFlags = 0, [[maybe_unused]] Rhi::TextureUsage textureUsage = Rhi::TextureUsage::DEFAULT RHI_RESOURCE_DEBUG_NAME_PARAMETER) override { NullRhi& nullRhi = static_cast<NullRhi&>(getRhi()); // Sanity check RHI_ASSERT(nullRhi.getContext(), width > 0, "Null create texture cube was called with invalid parameters") // Create cube texture resource return RHI_NEW(nullRhi.getContext(), TextureCube)(nullRhi, width RHI_RESOURCE_DEBUG_PASS_PARAMETER); } [[nodiscard]] virtual Rhi::ITextureCubeArray* createTextureCubeArray(uint32_t width, uint32_t numberOfSlices, [[maybe_unused]] Rhi::TextureFormat::Enum textureFormat, [[maybe_unused]] const void* data = nullptr, [[maybe_unused]] uint32_t textureFlags = 0, [[maybe_unused]] Rhi::TextureUsage textureUsage = Rhi::TextureUsage::DEFAULT RHI_RESOURCE_DEBUG_NAME_PARAMETER) override { NullRhi& nullRhi = static_cast<NullRhi&>(getRhi()); // Sanity check RHI_ASSERT(nullRhi.getContext(), width > 0, "Null create texture cube array was called with invalid parameters") // Create cube texture array resource return RHI_NEW(nullRhi.getContext(), TextureCubeArray)(nullRhi, width, numberOfSlices RHI_RESOURCE_DEBUG_PASS_PARAMETER); } //[-------------------------------------------------------] //[ Protected virtual Rhi::RefCount methods ] //[-------------------------------------------------------] protected: inline virtual void selfDestruct() override { RHI_DELETE(getRhi().getContext(), TextureManager, this); } //[-------------------------------------------------------] //[ Private methods ] //[-------------------------------------------------------] private: explicit TextureManager(const TextureManager& source) = delete; TextureManager& operator =(const TextureManager& source) = delete; }; //[-------------------------------------------------------] //[ NullRhi/State/SamplerState.h ] //[-------------------------------------------------------] /** * @brief * Null sampler state class */ class SamplerState final : public Rhi::ISamplerState { //[-------------------------------------------------------] //[ Public methods ] //[-------------------------------------------------------] public: /** * @brief * Constructor * * @param[in] nullRhi * Owner null RHI instance */ inline explicit SamplerState(NullRhi& nullRhi RHI_RESOURCE_DEBUG_NAME_PARAMETER_NO_DEFAULT) : ISamplerState(nullRhi RHI_RESOURCE_DEBUG_PASS_PARAMETER) {} /** * @brief * Destructor */ inline virtual ~SamplerState() override {} //[-------------------------------------------------------] //[ Protected virtual Rhi::RefCount methods ] //[-------------------------------------------------------] protected: inline virtual void selfDestruct() override { RHI_DELETE(getRhi().getContext(), SamplerState, this); } //[-------------------------------------------------------] //[ Private methods ] //[-------------------------------------------------------] private: explicit SamplerState(const SamplerState& source) = delete; SamplerState& operator =(const SamplerState& source) = delete; }; //[-------------------------------------------------------] //[ NullRhi/RenderTarget/RenderPass.h ] //[-------------------------------------------------------] /** * @brief * Null render pass interface */ class RenderPass final : public Rhi::IRenderPass { //[-------------------------------------------------------] //[ Public methods ] //[-------------------------------------------------------] public: /** * @brief * Constructor * * @param[in] rhi * Owner RHI instance * @param[in] numberOfColorAttachments * Number of color render target textures, must be <="Rhi::Capabilities::maximumNumberOfSimultaneousRenderTargets" * @param[in] colorAttachmentTextureFormats * The color render target texture formats, can be a null pointer or can contain null pointers, if not a null pointer there must be at * least "numberOfColorAttachments" textures in the provided C-array of pointers * @param[in] depthStencilAttachmentTextureFormat * The optional depth stencil render target texture format, can be a "Rhi::TextureFormat::UNKNOWN" if there should be no depth buffer * @param[in] numberOfMultisamples * The number of multisamples per pixel (valid values: 1, 2, 4, 8) */ RenderPass(Rhi::IRhi& rhi, uint32_t numberOfColorAttachments, const Rhi::TextureFormat::Enum* colorAttachmentTextureFormats, Rhi::TextureFormat::Enum depthStencilAttachmentTextureFormat, uint8_t numberOfMultisamples RHI_RESOURCE_DEBUG_NAME_PARAMETER_NO_DEFAULT) : IRenderPass(rhi RHI_RESOURCE_DEBUG_PASS_PARAMETER), mNumberOfColorAttachments(numberOfColorAttachments), mDepthStencilAttachmentTextureFormat(depthStencilAttachmentTextureFormat), mNumberOfMultisamples(numberOfMultisamples) { RHI_ASSERT(rhi.getContext(), mNumberOfColorAttachments < 8, "Invalid number of null color attachments") memcpy(mColorAttachmentTextureFormats, colorAttachmentTextureFormats, sizeof(Rhi::TextureFormat::Enum) * mNumberOfColorAttachments); } /** * @brief * Destructor */ inline virtual ~RenderPass() override {} /** * @brief * Return the number of color render target textures * * @return * The number of color render target textures */ [[nodiscard]] inline uint32_t getNumberOfColorAttachments() const { return mNumberOfColorAttachments; } //[-------------------------------------------------------] //[ Protected virtual Rhi::RefCount methods ] //[-------------------------------------------------------] protected: inline virtual void selfDestruct() override { RHI_DELETE(getRhi().getContext(), RenderPass, this); } //[-------------------------------------------------------] //[ Private methods ] //[-------------------------------------------------------] private: explicit RenderPass(const RenderPass& source) = delete; RenderPass& operator =(const RenderPass& source) = delete; //[-------------------------------------------------------] //[ Private data ] //[-------------------------------------------------------] private: uint32_t mNumberOfColorAttachments; Rhi::TextureFormat::Enum mColorAttachmentTextureFormats[8]; Rhi::TextureFormat::Enum mDepthStencilAttachmentTextureFormat; uint8_t mNumberOfMultisamples; }; //[-------------------------------------------------------] //[ NullRhi/RenderTarget/SwapChain.h ] //[-------------------------------------------------------] /** * @brief * Null swap chain class */ class SwapChain final : public Rhi::ISwapChain { //[-------------------------------------------------------] //[ Public methods ] //[-------------------------------------------------------] public: /** * @brief * Constructor * * @param[in] renderPass * Render pass to use, the swap chain keeps a reference to the render pass * @param[in] windowHandle * Information about the window to render into */ inline SwapChain(Rhi::IRenderPass& renderPass, Rhi::WindowHandle windowHandle RHI_RESOURCE_DEBUG_NAME_PARAMETER_NO_DEFAULT) : ISwapChain(renderPass RHI_RESOURCE_DEBUG_PASS_PARAMETER), mNativeWindowHandle(windowHandle.nativeWindowHandle) {} /** * @brief * Destructor */ inline virtual ~SwapChain() override {} //[-------------------------------------------------------] //[ Public virtual Rhi::IRenderTarget methods ] //[-------------------------------------------------------] public: virtual void getWidthAndHeight(uint32_t& width, uint32_t& height) const override { #ifdef _WIN32 // Is there a valid native OS window? if (NULL_HANDLE != mNativeWindowHandle) { // Get the width and height long swapChainWidth = 1; long swapChainHeight = 1; { // Get the client rectangle of the native output window // -> Don't use the width and height stored in "DXGI_SWAP_CHAIN_DESC" -> "DXGI_MODE_DESC" // because it might have been modified in order to avoid zero values RECT rect; ::GetClientRect(reinterpret_cast<HWND>(mNativeWindowHandle), &rect); // Get the width and height... swapChainWidth = rect.right - rect.left; swapChainHeight = rect.bottom - rect.top; // ... and ensure that none of them is ever zero if (swapChainWidth < 1) { swapChainWidth = 1; } if (swapChainHeight < 1) { swapChainHeight = 1; } } // Write out the width and height width = static_cast<UINT>(swapChainWidth); height = static_cast<UINT>(swapChainHeight); } else #elif defined LINUX if (mNativeWindowHandle) { // TODO(sw) Reuse X11 display from "Frontend" Display* display = XOpenDisplay(0); // Get the width and height... ::Window rootWindow = 0; int positionX = 0, positionY = 0; unsigned int unsignedWidth = 0, unsignedHeight = 0, border = 0, depth = 0; XGetGeometry(display, mNativeWindowHandle, &rootWindow, &positionX, &positionY, &unsignedWidth, &unsignedHeight, &border, &depth); // ... and ensure that none of them is ever zero if (unsignedWidth < 1) { unsignedWidth = 1; } if (unsignedHeight < 1) { unsignedHeight = 1; } // Done width = unsignedWidth; height = unsignedHeight; } else #else #error "Unsupported platform" #endif { // Set known default return values width = 1; height = 1; } } //[-------------------------------------------------------] //[ Public virtual Rhi::ISwapChain methods ] //[-------------------------------------------------------] public: [[nodiscard]] inline virtual Rhi::handle getNativeWindowHandle() const override { return mNativeWindowHandle; } inline virtual void setVerticalSynchronizationInterval(uint32_t) override {} inline virtual void present() override {} inline virtual void resizeBuffers() override {} [[nodiscard]] inline virtual bool getFullscreenState() const override { // Window mode return false; } inline virtual void setFullscreenState(bool) override {} inline virtual void setRenderWindow(Rhi::IRenderWindow*) override {} //[-------------------------------------------------------] //[ Protected virtual Rhi::RefCount methods ] //[-------------------------------------------------------] protected: inline virtual void selfDestruct() override { RHI_DELETE(getRhi().getContext(), SwapChain, this); } //[-------------------------------------------------------] //[ Private methods ] //[-------------------------------------------------------] private: explicit SwapChain(const SwapChain& source) = delete; SwapChain& operator =(const SwapChain& source) = delete; //[-------------------------------------------------------] //[ Private data ] //[-------------------------------------------------------] private: Rhi::handle mNativeWindowHandle; ///< Native window handle window, can be a null handle }; //[-------------------------------------------------------] //[ NullRhi/RenderTarget/Framebuffer.h ] //[-------------------------------------------------------] /** * @brief * Null framebuffer class */ class Framebuffer final : public Rhi::IFramebuffer { //[-------------------------------------------------------] //[ Public methods ] //[-------------------------------------------------------] public: /** * @brief * Constructor * * @param[in] renderPass * Render pass to use, the swap chain keeps a reference to the render pass */ inline explicit Framebuffer(Rhi::IRenderPass& renderPass RHI_RESOURCE_DEBUG_NAME_PARAMETER_NO_DEFAULT) : IFramebuffer(renderPass RHI_RESOURCE_DEBUG_PASS_PARAMETER) {} /** * @brief * Destructor */ inline virtual ~Framebuffer() override {} //[-------------------------------------------------------] //[ Public virtual Rhi::IRenderTarget methods ] //[-------------------------------------------------------] public: inline virtual void getWidthAndHeight(uint32_t& width, uint32_t& height) const override { // TODO(co) Better implementation instead of just returning one (not that important, but would be nice) width = 1; height = 1; } //[-------------------------------------------------------] //[ Protected virtual Rhi::RefCount methods ] //[-------------------------------------------------------] protected: inline virtual void selfDestruct() override { RHI_DELETE(getRhi().getContext(), Framebuffer, this); } //[-------------------------------------------------------] //[ Private methods ] //[-------------------------------------------------------] private: explicit Framebuffer(const Framebuffer& source) = delete; Framebuffer& operator =(const Framebuffer& source) = delete; }; //[-------------------------------------------------------] //[ NullRhi/Shader/VertexShader.h ] //[-------------------------------------------------------] /** * @brief * Null vertex shader class */ class VertexShader final : public Rhi::IVertexShader { //[-------------------------------------------------------] //[ Public methods ] //[-------------------------------------------------------] public: /** * @brief * Constructor * * @param[in] nullRhi * Owner null RHI instance */ inline explicit VertexShader(NullRhi& nullRhi RHI_RESOURCE_DEBUG_NAME_PARAMETER_NO_DEFAULT) : IVertexShader(nullRhi RHI_RESOURCE_DEBUG_PASS_PARAMETER) {} /** * @brief * Destructor */ inline virtual ~VertexShader() override {} //[-------------------------------------------------------] //[ Public virtual Rhi::IShader methods ] //[-------------------------------------------------------] public: [[nodiscard]] inline virtual const char* getShaderLanguageName() const override { return ::detail::NULL_NAME; } //[-------------------------------------------------------] //[ Protected virtual Rhi::RefCount methods ] //[-------------------------------------------------------] protected: inline virtual void selfDestruct() override { RHI_DELETE(getRhi().getContext(), VertexShader, this); } //[-------------------------------------------------------] //[ Private methods ] //[-------------------------------------------------------] private: explicit VertexShader(const VertexShader& source) = delete; VertexShader& operator =(const VertexShader& source) = delete; }; //[-------------------------------------------------------] //[ NullRhi/Shader/TessellationControlShader.h ] //[-------------------------------------------------------] /** * @brief * Null tessellation control shader ("hull shader" in Direct3D terminology) class */ class TessellationControlShader final : public Rhi::ITessellationControlShader { //[-------------------------------------------------------] //[ Public methods ] //[-------------------------------------------------------] public: /** * @brief * Constructor * * @param[in] nullRhi * Owner null RHI instance */ inline explicit TessellationControlShader(NullRhi& nullRhi RHI_RESOURCE_DEBUG_NAME_PARAMETER_NO_DEFAULT) : ITessellationControlShader(nullRhi RHI_RESOURCE_DEBUG_PASS_PARAMETER) {} /** * @brief * Destructor */ inline virtual ~TessellationControlShader() override {} //[-------------------------------------------------------] //[ Public virtual Rhi::IShader methods ] //[-------------------------------------------------------] public: [[nodiscard]] inline virtual const char* getShaderLanguageName() const override { return ::detail::NULL_NAME; } //[-------------------------------------------------------] //[ Protected virtual Rhi::RefCount methods ] //[-------------------------------------------------------] protected: inline virtual void selfDestruct() override { RHI_DELETE(getRhi().getContext(), TessellationControlShader, this); } //[-------------------------------------------------------] //[ Private methods ] //[-------------------------------------------------------] private: explicit TessellationControlShader(const TessellationControlShader& source) = delete; TessellationControlShader& operator =(const TessellationControlShader& source) = delete; }; //[-------------------------------------------------------] //[ NullRhi/Shader/TessellationEvaluationShader.h ] //[-------------------------------------------------------] /** * @brief * Null tessellation evaluation shader ("domain shader" in Direct3D terminology) class */ class TessellationEvaluationShader final : public Rhi::ITessellationEvaluationShader { //[-------------------------------------------------------] //[ Public methods ] //[-------------------------------------------------------] public: /** * @brief * Constructor * * @param[in] nullRhi * Owner null RHI instance */ inline explicit TessellationEvaluationShader(NullRhi& nullRhi RHI_RESOURCE_DEBUG_NAME_PARAMETER_NO_DEFAULT) : ITessellationEvaluationShader(nullRhi RHI_RESOURCE_DEBUG_PASS_PARAMETER) {} /** * @brief * Destructor */ inline virtual ~TessellationEvaluationShader() override {} //[-------------------------------------------------------] //[ Public virtual Rhi::IShader methods ] //[-------------------------------------------------------] public: [[nodiscard]] inline virtual const char* getShaderLanguageName() const override { return ::detail::NULL_NAME; } //[-------------------------------------------------------] //[ Protected virtual Rhi::RefCount methods ] //[-------------------------------------------------------] protected: inline virtual void selfDestruct() override { RHI_DELETE(getRhi().getContext(), TessellationEvaluationShader, this); } //[-------------------------------------------------------] //[ Private methods ] //[-------------------------------------------------------] private: explicit TessellationEvaluationShader(const TessellationEvaluationShader& source) = delete; TessellationEvaluationShader& operator =(const TessellationEvaluationShader& source) = delete; }; //[-------------------------------------------------------] //[ NullRhi/Shader/GeometryShader.h ] //[-------------------------------------------------------] /** * @brief * Null geometry shader class */ class GeometryShader final : public Rhi::IGeometryShader { //[-------------------------------------------------------] //[ Public methods ] //[-------------------------------------------------------] public: /** * @brief * Constructor * * @param[in] nullRhi * Owner null RHI instance */ inline explicit GeometryShader(NullRhi& nullRhi RHI_RESOURCE_DEBUG_NAME_PARAMETER_NO_DEFAULT) : IGeometryShader(nullRhi RHI_RESOURCE_DEBUG_PASS_PARAMETER) {} /** * @brief * Destructor */ inline virtual ~GeometryShader() override {} //[-------------------------------------------------------] //[ Public virtual Rhi::IShader methods ] //[-------------------------------------------------------] public: [[nodiscard]] inline virtual const char* getShaderLanguageName() const override { return ::detail::NULL_NAME; } //[-------------------------------------------------------] //[ Protected virtual Rhi::RefCount methods ] //[-------------------------------------------------------] protected: inline virtual void selfDestruct() override { RHI_DELETE(getRhi().getContext(), GeometryShader, this); } //[-------------------------------------------------------] //[ Private methods ] //[-------------------------------------------------------] private: explicit GeometryShader(const GeometryShader& source) = delete; GeometryShader& operator =(const GeometryShader& source) = delete; }; //[-------------------------------------------------------] //[ NullRhi/Shader/FragmentShader.h ] //[-------------------------------------------------------] /** * @brief * Null fragment shader class (FS, "pixel shader" in Direct3D terminology) */ class FragmentShader final : public Rhi::IFragmentShader { //[-------------------------------------------------------] //[ Public methods ] //[-------------------------------------------------------] public: /** * @brief * Constructor * * @param[in] nullRhi * Owner null RHI instance */ inline explicit FragmentShader(NullRhi& nullRhi RHI_RESOURCE_DEBUG_NAME_PARAMETER_NO_DEFAULT) : IFragmentShader(nullRhi RHI_RESOURCE_DEBUG_PASS_PARAMETER) {} /** * @brief * Destructor */ inline virtual ~FragmentShader() override {} //[-------------------------------------------------------] //[ Public virtual Rhi::IShader methods ] //[-------------------------------------------------------] public: [[nodiscard]] inline virtual const char* getShaderLanguageName() const override { return ::detail::NULL_NAME; } //[-------------------------------------------------------] //[ Protected virtual Rhi::RefCount methods ] //[-------------------------------------------------------] protected: inline virtual void selfDestruct() override { RHI_DELETE(getRhi().getContext(), FragmentShader, this); } //[-------------------------------------------------------] //[ Private methods ] //[-------------------------------------------------------] private: explicit FragmentShader(const FragmentShader& source) = delete; FragmentShader& operator =(const FragmentShader& source) = delete; }; //[-------------------------------------------------------] //[ NullRhi/Shader/TaskShader.h ] //[-------------------------------------------------------] /** * @brief * Null task shader class (TS, "amplification shader" in Direct3D terminology) */ class TaskShader final : public Rhi::ITaskShader { //[-------------------------------------------------------] //[ Public methods ] //[-------------------------------------------------------] public: /** * @brief * Constructor * * @param[in] nullRhi * Owner null RHI instance */ inline explicit TaskShader(NullRhi& nullRhi RHI_RESOURCE_DEBUG_NAME_PARAMETER_NO_DEFAULT) : ITaskShader(nullRhi RHI_RESOURCE_DEBUG_PASS_PARAMETER) {} /** * @brief * Destructor */ inline virtual ~TaskShader() override {} //[-------------------------------------------------------] //[ Public virtual Rhi::IShader methods ] //[-------------------------------------------------------] public: [[nodiscard]] inline virtual const char* getShaderLanguageName() const override { return ::detail::NULL_NAME; } //[-------------------------------------------------------] //[ Protected virtual Rhi::RefCount methods ] //[-------------------------------------------------------] protected: inline virtual void selfDestruct() override { RHI_DELETE(getRhi().getContext(), TaskShader, this); } //[-------------------------------------------------------] //[ Private methods ] //[-------------------------------------------------------] private: explicit TaskShader(const TaskShader& source) = delete; TaskShader& operator =(const TaskShader& source) = delete; }; //[-------------------------------------------------------] //[ NullRhi/Shader/MeshShader.h ] //[-------------------------------------------------------] /** * @brief * Null mesh shader class (MS) */ class MeshShader final : public Rhi::IMeshShader { //[-------------------------------------------------------] //[ Public methods ] //[-------------------------------------------------------] public: /** * @brief * Constructor * * @param[in] nullRhi * Owner null RHI instance */ inline explicit MeshShader(NullRhi& nullRhi RHI_RESOURCE_DEBUG_NAME_PARAMETER_NO_DEFAULT) : IMeshShader(nullRhi RHI_RESOURCE_DEBUG_PASS_PARAMETER) {} /** * @brief * Destructor */ inline virtual ~MeshShader() override {} //[-------------------------------------------------------] //[ Public virtual Rhi::IShader methods ] //[-------------------------------------------------------] public: [[nodiscard]] inline virtual const char* getShaderLanguageName() const override { return ::detail::NULL_NAME; } //[-------------------------------------------------------] //[ Protected virtual Rhi::RefCount methods ] //[-------------------------------------------------------] protected: inline virtual void selfDestruct() override { RHI_DELETE(getRhi().getContext(), MeshShader, this); } //[-------------------------------------------------------] //[ Private methods ] //[-------------------------------------------------------] private: explicit MeshShader(const MeshShader& source) = delete; MeshShader& operator =(const MeshShader& source) = delete; }; //[-------------------------------------------------------] //[ NullRhi/Shader/ComputeShader.h ] //[-------------------------------------------------------] /** * @brief * Null compute shader class (CS) */ class ComputeShader final : public Rhi::IComputeShader { //[-------------------------------------------------------] //[ Public methods ] //[-------------------------------------------------------] public: /** * @brief * Constructor * * @param[in] nullRhi * Owner null RHI instance */ inline explicit ComputeShader(NullRhi& nullRhi RHI_RESOURCE_DEBUG_NAME_PARAMETER_NO_DEFAULT) : IComputeShader(nullRhi RHI_RESOURCE_DEBUG_PASS_PARAMETER) {} /** * @brief * Destructor */ inline virtual ~ComputeShader() override {} //[-------------------------------------------------------] //[ Public virtual Rhi::IShader methods ] //[-------------------------------------------------------] public: [[nodiscard]] inline virtual const char* getShaderLanguageName() const override { return ::detail::NULL_NAME; } //[-------------------------------------------------------] //[ Protected virtual Rhi::RefCount methods ] //[-------------------------------------------------------] protected: inline virtual void selfDestruct() override { RHI_DELETE(getRhi().getContext(), ComputeShader, this); } //[-------------------------------------------------------] //[ Private methods ] //[-------------------------------------------------------] private: explicit ComputeShader(const ComputeShader& source) = delete; ComputeShader& operator =(const ComputeShader& source) = delete; }; //[-------------------------------------------------------] //[ NullRhi/Shader/GraphicsProgram.h ] //[-------------------------------------------------------] /** * @brief * Null graphics program class */ class GraphicsProgram final : public Rhi::IGraphicsProgram { //[-------------------------------------------------------] //[ Public methods ] //[-------------------------------------------------------] public: /** * @brief * Constructor for traditional graphics program * * @param[in] nullRhi * Owner null RHI instance * @param[in] vertexShader * Vertex shader the graphics program is using, can be a null pointer * @param[in] tessellationControlShader * Tessellation control shader the graphics program is using, can be a null pointer * @param[in] tessellationEvaluationShader * Tessellation evaluation shader the graphics program is using, can be a null pointer * @param[in] geometryShader * Geometry shader the graphics program is using, can be a null pointer * @param[in] fragmentShader * Fragment shader the graphics program is using, can be a null pointer * * @note * - The graphics program keeps a reference to the provided shaders and releases it when no longer required */ GraphicsProgram(NullRhi& nullRhi, VertexShader* vertexShader, TessellationControlShader* tessellationControlShader, TessellationEvaluationShader* tessellationEvaluationShader, GeometryShader* geometryShader, FragmentShader* fragmentShader RHI_RESOURCE_DEBUG_NAME_PARAMETER_NO_DEFAULT) : IGraphicsProgram(nullRhi RHI_RESOURCE_DEBUG_PASS_PARAMETER) { // We don't keep a reference to the shaders in here // -> Ensure a correct reference counter behaviour if (nullptr != vertexShader) { vertexShader->addReference(); vertexShader->releaseReference(); } if (nullptr != tessellationControlShader) { tessellationControlShader->addReference(); tessellationControlShader->releaseReference(); } if (nullptr != tessellationEvaluationShader) { tessellationEvaluationShader->addReference(); tessellationEvaluationShader->releaseReference(); } if (nullptr != geometryShader) { geometryShader->addReference(); geometryShader->releaseReference(); } if (nullptr != fragmentShader) { fragmentShader->addReference(); fragmentShader->releaseReference(); } } /** * @brief * Constructor for task and mesh shader based graphics program * * @param[in] nullRhi * Owner null RHI instance * @param[in] taskShader * Task shader the graphics program is using, can be a null pointer * @param[in] meshShader * Mesh shader the graphics program is using * @param[in] fragmentShader * Fragment shader the graphics program is using, can be a null pointer * * @note * - The graphics program keeps a reference to the provided shaders and releases it when no longer required */ GraphicsProgram(NullRhi& nullRhi, TaskShader* taskShader, MeshShader& meshShader, FragmentShader* fragmentShader RHI_RESOURCE_DEBUG_NAME_PARAMETER_NO_DEFAULT) : IGraphicsProgram(nullRhi RHI_RESOURCE_DEBUG_PASS_PARAMETER) { // We don't keep a reference to the shaders in here // -> Ensure a correct reference counter behaviour if (nullptr != taskShader) { taskShader->addReference(); taskShader->releaseReference(); } meshShader.addReference(); meshShader.releaseReference(); if (nullptr != fragmentShader) { fragmentShader->addReference(); fragmentShader->releaseReference(); } } /** * @brief * Destructor */ inline virtual ~GraphicsProgram() override {} //[-------------------------------------------------------] //[ Public virtual Rhi::IGraphicsProgram methods ] //[-------------------------------------------------------] public: [[nodiscard]] virtual Rhi::handle getUniformHandle(const char*) override { RHI_ASSERT(getRhi().getContext(), false, "The null RHI graphics program implementation doesn't have legacy uniform support") return NULL_HANDLE; } //[-------------------------------------------------------] //[ Protected virtual Rhi::RefCount methods ] //[-------------------------------------------------------] protected: inline virtual void selfDestruct() override { RHI_DELETE(getRhi().getContext(), GraphicsProgram, this); } //[-------------------------------------------------------] //[ Private methods ] //[-------------------------------------------------------] private: explicit GraphicsProgram(const GraphicsProgram& source) = delete; GraphicsProgram& operator =(const GraphicsProgram& source) = delete; }; //[-------------------------------------------------------] //[ NullRhi/Shader/ShaderLanguage.h ] //[-------------------------------------------------------] /** * @brief * Null shader language class */ class ShaderLanguage final : public Rhi::IShaderLanguage { //[-------------------------------------------------------] //[ Public methods ] //[-------------------------------------------------------] public: /** * @brief * Constructor * * @param[in] nullRhi * Owner null RHI instance */ inline explicit ShaderLanguage(NullRhi& nullRhi) : IShaderLanguage(nullRhi) {} /** * @brief * Destructor */ inline virtual ~ShaderLanguage() override {} //[-------------------------------------------------------] //[ Public virtual Rhi::IShaderLanguage methods ] //[-------------------------------------------------------] public: [[nodiscard]] inline virtual const char* getShaderLanguageName() const override { return ::detail::NULL_NAME; } [[nodiscard]] inline virtual Rhi::IVertexShader* createVertexShaderFromBytecode([[maybe_unused]] const Rhi::VertexAttributes& vertexAttributes, [[maybe_unused]] const Rhi::ShaderBytecode& shaderBytecode RHI_RESOURCE_DEBUG_NAME_PARAMETER) override { // There's no need to check for "Rhi::Capabilities::vertexShader", we know there's vertex shader support NullRhi& nullRhi = static_cast<NullRhi&>(getRhi()); return RHI_NEW(nullRhi.getContext(), VertexShader)(nullRhi RHI_RESOURCE_DEBUG_PASS_PARAMETER); } [[nodiscard]] inline virtual Rhi::IVertexShader* createVertexShaderFromSourceCode([[maybe_unused]] const Rhi::VertexAttributes& vertexAttributes, [[maybe_unused]] const Rhi::ShaderSourceCode& shaderSourceCode, [[maybe_unused]] Rhi::ShaderBytecode* shaderBytecode = nullptr RHI_RESOURCE_DEBUG_NAME_PARAMETER) override { // There's no need to check for "Rhi::Capabilities::vertexShader", we know there's vertex shader support NullRhi& nullRhi = static_cast<NullRhi&>(getRhi()); return RHI_NEW(nullRhi.getContext(), VertexShader)(nullRhi RHI_RESOURCE_DEBUG_PASS_PARAMETER); } [[nodiscard]] inline virtual Rhi::ITessellationControlShader* createTessellationControlShaderFromBytecode([[maybe_unused]] const Rhi::ShaderBytecode& shaderBytecode RHI_RESOURCE_DEBUG_NAME_PARAMETER) override { // There's no need to check for "Rhi::Capabilities::maximumNumberOfPatchVertices", we know there's tessellation control shader support NullRhi& nullRhi = static_cast<NullRhi&>(getRhi()); return RHI_NEW(nullRhi.getContext(), TessellationControlShader)(nullRhi RHI_RESOURCE_DEBUG_PASS_PARAMETER); } [[nodiscard]] inline virtual Rhi::ITessellationControlShader* createTessellationControlShaderFromSourceCode([[maybe_unused]] const Rhi::ShaderSourceCode& shaderSourceCode, [[maybe_unused]] Rhi::ShaderBytecode* shaderBytecode = nullptr RHI_RESOURCE_DEBUG_NAME_PARAMETER) override { // There's no need to check for "Rhi::Capabilities::maximumNumberOfPatchVertices", we know there's tessellation control shader support NullRhi& nullRhi = static_cast<NullRhi&>(getRhi()); return RHI_NEW(nullRhi.getContext(), TessellationControlShader)(nullRhi RHI_RESOURCE_DEBUG_PASS_PARAMETER); } [[nodiscard]] inline virtual Rhi::ITessellationEvaluationShader* createTessellationEvaluationShaderFromBytecode([[maybe_unused]] const Rhi::ShaderBytecode& shaderBytecode RHI_RESOURCE_DEBUG_NAME_PARAMETER) override { // There's no need to check for "Rhi::Capabilities::maximumNumberOfPatchVertices", we know there's tessellation evaluation shader support NullRhi& nullRhi = static_cast<NullRhi&>(getRhi()); return RHI_NEW(nullRhi.getContext(), TessellationEvaluationShader)(nullRhi RHI_RESOURCE_DEBUG_PASS_PARAMETER); } [[nodiscard]] inline virtual Rhi::ITessellationEvaluationShader* createTessellationEvaluationShaderFromSourceCode([[maybe_unused]] const Rhi::ShaderSourceCode& shaderSourceCode, [[maybe_unused]] Rhi::ShaderBytecode* shaderBytecode = nullptr RHI_RESOURCE_DEBUG_NAME_PARAMETER) override { // There's no need to check for "Rhi::Capabilities::maximumNumberOfPatchVertices", we know there's tessellation evaluation shader support NullRhi& nullRhi = static_cast<NullRhi&>(getRhi()); return RHI_NEW(nullRhi.getContext(), TessellationEvaluationShader)(nullRhi RHI_RESOURCE_DEBUG_PASS_PARAMETER); } [[nodiscard]] inline virtual Rhi::IGeometryShader* createGeometryShaderFromBytecode([[maybe_unused]] const Rhi::ShaderBytecode& shaderBytecode RHI_RESOURCE_DEBUG_NAME_PARAMETER) override { // There's no need to check for "Rhi::Capabilities::maximumNumberOfGsOutputVertices", we know there's geometry shader support NullRhi& nullRhi = static_cast<NullRhi&>(getRhi()); return RHI_NEW(nullRhi.getContext(), GeometryShader)(nullRhi RHI_RESOURCE_DEBUG_PASS_PARAMETER); } [[nodiscard]] inline virtual Rhi::IGeometryShader* createGeometryShaderFromSourceCode([[maybe_unused]] const Rhi::ShaderSourceCode& shaderSourceCode, [[maybe_unused]] Rhi::ShaderBytecode* shaderBytecode = nullptr RHI_RESOURCE_DEBUG_NAME_PARAMETER) override { // There's no need to check for "Rhi::Capabilities::maximumNumberOfGsOutputVertices", we know there's geometry shader support NullRhi& nullRhi = static_cast<NullRhi&>(getRhi()); return RHI_NEW(nullRhi.getContext(), GeometryShader)(nullRhi RHI_RESOURCE_DEBUG_PASS_PARAMETER); } [[nodiscard]] inline virtual Rhi::IFragmentShader* createFragmentShaderFromBytecode([[maybe_unused]] const Rhi::ShaderBytecode& shaderBytecode RHI_RESOURCE_DEBUG_NAME_PARAMETER) override { // There's no need to check for "Rhi::Capabilities::fragmentShader", we know there's fragment shader support NullRhi& nullRhi = static_cast<NullRhi&>(getRhi()); return RHI_NEW(nullRhi.getContext(), FragmentShader)(nullRhi RHI_RESOURCE_DEBUG_PASS_PARAMETER); } [[nodiscard]] inline virtual Rhi::IFragmentShader* createFragmentShaderFromSourceCode([[maybe_unused]] const Rhi::ShaderSourceCode& shaderSourceCode, [[maybe_unused]] Rhi::ShaderBytecode* shaderBytecode = nullptr RHI_RESOURCE_DEBUG_NAME_PARAMETER) override { // There's no need to check for "Rhi::Capabilities::fragmentShader", we know there's fragment shader support NullRhi& nullRhi = static_cast<NullRhi&>(getRhi()); return RHI_NEW(nullRhi.getContext(), FragmentShader)(nullRhi RHI_RESOURCE_DEBUG_PASS_PARAMETER); } [[nodiscard]] inline virtual Rhi::ITaskShader* createTaskShaderFromBytecode([[maybe_unused]] const Rhi::ShaderBytecode& shaderBytecode RHI_RESOURCE_DEBUG_NAME_PARAMETER) override { // There's no need to check for "Rhi::Capabilities::meshShader", we know there's mesh shader support NullRhi& nullRhi = static_cast<NullRhi&>(getRhi()); return RHI_NEW(nullRhi.getContext(), TaskShader)(nullRhi RHI_RESOURCE_DEBUG_PASS_PARAMETER); } [[nodiscard]] inline virtual Rhi::ITaskShader* createTaskShaderFromSourceCode([[maybe_unused]] const Rhi::ShaderSourceCode& shaderSourceCode, [[maybe_unused]] Rhi::ShaderBytecode* shaderBytecode = nullptr RHI_RESOURCE_DEBUG_NAME_PARAMETER) override { // There's no need to check for "Rhi::Capabilities::meshShader", we know there's mesh shader support NullRhi& nullRhi = static_cast<NullRhi&>(getRhi()); return RHI_NEW(nullRhi.getContext(), TaskShader)(nullRhi RHI_RESOURCE_DEBUG_PASS_PARAMETER); } [[nodiscard]] inline virtual Rhi::IMeshShader* createMeshShaderFromBytecode([[maybe_unused]] const Rhi::ShaderBytecode& shaderBytecode RHI_RESOURCE_DEBUG_NAME_PARAMETER) override { // There's no need to check for "Rhi::Capabilities::meshShader", we know there's mesh shader support NullRhi& nullRhi = static_cast<NullRhi&>(getRhi()); return RHI_NEW(nullRhi.getContext(), MeshShader)(nullRhi RHI_RESOURCE_DEBUG_PASS_PARAMETER); } [[nodiscard]] inline virtual Rhi::IMeshShader* createMeshShaderFromSourceCode([[maybe_unused]] const Rhi::ShaderSourceCode& shaderSourceCode, [[maybe_unused]] Rhi::ShaderBytecode* shaderBytecode = nullptr RHI_RESOURCE_DEBUG_NAME_PARAMETER) override { // There's no need to check for "Rhi::Capabilities::meshShader", we know there's mesh shader support NullRhi& nullRhi = static_cast<NullRhi&>(getRhi()); return RHI_NEW(nullRhi.getContext(), MeshShader)(nullRhi RHI_RESOURCE_DEBUG_PASS_PARAMETER); } [[nodiscard]] inline virtual Rhi::IComputeShader* createComputeShaderFromBytecode([[maybe_unused]] const Rhi::ShaderBytecode& shaderBytecode RHI_RESOURCE_DEBUG_NAME_PARAMETER) override { // There's no need to check for "Rhi::Capabilities::computeShader", we know there's compute shader support NullRhi& nullRhi = static_cast<NullRhi&>(getRhi()); return RHI_NEW(nullRhi.getContext(), ComputeShader)(nullRhi RHI_RESOURCE_DEBUG_PASS_PARAMETER); } [[nodiscard]] inline virtual Rhi::IComputeShader* createComputeShaderFromSourceCode([[maybe_unused]] const Rhi::ShaderSourceCode& shaderSourceCode, [[maybe_unused]] Rhi::ShaderBytecode* shaderBytecode = nullptr RHI_RESOURCE_DEBUG_NAME_PARAMETER) override { // There's no need to check for "Rhi::Capabilities::computeShader", we know there's compute shader support NullRhi& nullRhi = static_cast<NullRhi&>(getRhi()); return RHI_NEW(nullRhi.getContext(), ComputeShader)(nullRhi RHI_RESOURCE_DEBUG_PASS_PARAMETER); } [[nodiscard]] virtual Rhi::IGraphicsProgram* createGraphicsProgram([[maybe_unused]] const Rhi::IRootSignature& rootSignature, [[maybe_unused]] const Rhi::VertexAttributes& vertexAttributes, Rhi::IVertexShader* vertexShader, Rhi::ITessellationControlShader* tessellationControlShader, Rhi::ITessellationEvaluationShader* tessellationEvaluationShader, Rhi::IGeometryShader* geometryShader, Rhi::IFragmentShader* fragmentShader RHI_RESOURCE_DEBUG_NAME_PARAMETER) override { NullRhi& nullRhi = static_cast<NullRhi&>(getRhi()); // Sanity checks // -> A shader can be a null pointer, but if it's not the shader and graphics program language must match // -> Optimization: Comparing the shader language name by directly comparing the pointer address of // the name is safe because we know that we always reference to one and the same name address // TODO(co) Add security check: Is the given resource one of the currently used RHI? RHI_ASSERT(nullRhi.getContext(), nullptr == vertexShader || vertexShader->getShaderLanguageName() == ::detail::NULL_NAME, "Null vertex shader language mismatch") RHI_ASSERT(nullRhi.getContext(), nullptr == tessellationControlShader || tessellationControlShader->getShaderLanguageName() == ::detail::NULL_NAME, "Null tessellation control shader language mismatch") RHI_ASSERT(nullRhi.getContext(), nullptr == tessellationEvaluationShader || tessellationEvaluationShader->getShaderLanguageName() == ::detail::NULL_NAME, "Null tessellation evaluation shader language mismatch") RHI_ASSERT(nullRhi.getContext(), nullptr == geometryShader || geometryShader->getShaderLanguageName() == ::detail::NULL_NAME, "Null geometry shader language mismatch") RHI_ASSERT(nullRhi.getContext(), nullptr == fragmentShader || fragmentShader->getShaderLanguageName() == ::detail::NULL_NAME, "Null fragment shader language mismatch") // Create the graphics program return RHI_NEW(nullRhi.getContext(), GraphicsProgram)(nullRhi, static_cast<VertexShader*>(vertexShader), static_cast<TessellationControlShader*>(tessellationControlShader), static_cast<TessellationEvaluationShader*>(tessellationEvaluationShader), static_cast<GeometryShader*>(geometryShader), static_cast<FragmentShader*>(fragmentShader) RHI_RESOURCE_DEBUG_PASS_PARAMETER); } [[nodiscard]] virtual Rhi::IGraphicsProgram* createGraphicsProgram([[maybe_unused]] const Rhi::IRootSignature& rootSignature, Rhi::ITaskShader* taskShader, Rhi::IMeshShader& meshShader, Rhi::IFragmentShader* fragmentShader RHI_RESOURCE_DEBUG_NAME_PARAMETER) { NullRhi& nullRhi = static_cast<NullRhi&>(getRhi()); // Sanity checks // -> A shader can be a null pointer, but if it's not the shader and graphics program language must match // -> Optimization: Comparing the shader language name by directly comparing the pointer address of // the name is safe because we know that we always reference to one and the same name address // TODO(co) Add security check: Is the given resource one of the currently used RHI? RHI_ASSERT(nullRhi.getContext(), nullptr == taskShader || taskShader->getShaderLanguageName() == ::detail::NULL_NAME, "Null task shader language mismatch") RHI_ASSERT(nullRhi.getContext(), meshShader.getShaderLanguageName() == ::detail::NULL_NAME, "Null mesh shader language mismatch") RHI_ASSERT(nullRhi.getContext(), nullptr == fragmentShader || fragmentShader->getShaderLanguageName() == ::detail::NULL_NAME, "Null fragment shader language mismatch") // Create the graphics program return RHI_NEW(nullRhi.getContext(), GraphicsProgram)(nullRhi, static_cast<TaskShader*>(taskShader), static_cast<MeshShader&>(meshShader), static_cast<FragmentShader*>(fragmentShader) RHI_RESOURCE_DEBUG_PASS_PARAMETER); } //[-------------------------------------------------------] //[ Protected virtual Rhi::RefCount methods ] //[-------------------------------------------------------] protected: inline virtual void selfDestruct() override { RHI_DELETE(getRhi().getContext(), ShaderLanguage, this); } //[-------------------------------------------------------] //[ Private methods ] //[-------------------------------------------------------] private: explicit ShaderLanguage(const ShaderLanguage& source) = delete; ShaderLanguage& operator =(const ShaderLanguage& source) = delete; }; //[-------------------------------------------------------] //[ NullRhi/State/GraphicsPipelineState.h ] //[-------------------------------------------------------] /** * @brief * Null graphics pipeline state class */ class GraphicsPipelineState final : public Rhi::IGraphicsPipelineState { //[-------------------------------------------------------] //[ Public methods ] //[-------------------------------------------------------] public: /** * @brief * Constructor * * @param[in] nullRhi * Owner null RHI instance * @param[in] graphicsPipelineState * Graphics pipeline state to use * @param[in] id * The unique compact graphics pipeline state ID */ GraphicsPipelineState(NullRhi& nullRhi, const Rhi::GraphicsPipelineState& graphicsPipelineState, uint16_t id RHI_RESOURCE_DEBUG_NAME_PARAMETER_NO_DEFAULT) : IGraphicsPipelineState(nullRhi, id RHI_RESOURCE_DEBUG_PASS_PARAMETER), mRootSignature(graphicsPipelineState.rootSignature), mGraphicsProgram(graphicsPipelineState.graphicsProgram), mRenderPass(graphicsPipelineState.renderPass) { // Add a reference to the referenced RHI resources mRootSignature->addReference(); mGraphicsProgram->addReference(); mRenderPass->addReference(); } /** * @brief * Destructor */ virtual ~GraphicsPipelineState() override { // Release referenced RHI resources mRootSignature->releaseReference(); mGraphicsProgram->releaseReference(); mRenderPass->releaseReference(); // Free the unique compact graphics pipeline state ID static_cast<NullRhi&>(getRhi()).GraphicsPipelineStateMakeId.DestroyID(getId()); } //[-------------------------------------------------------] //[ Protected virtual Rhi::RefCount methods ] //[-------------------------------------------------------] protected: inline virtual void selfDestruct() override { RHI_DELETE(getRhi().getContext(), GraphicsPipelineState, this); } //[-------------------------------------------------------] //[ Private methods ] //[-------------------------------------------------------] private: explicit GraphicsPipelineState(const GraphicsPipelineState& source) = delete; GraphicsPipelineState& operator =(const GraphicsPipelineState& source) = delete; //[-------------------------------------------------------] //[ Private data ] //[-------------------------------------------------------] private: Rhi::IRootSignature* mRootSignature; Rhi::IGraphicsProgram* mGraphicsProgram; Rhi::IRenderPass* mRenderPass; }; //[-------------------------------------------------------] //[ NullRhi/State/ComputePipelineState.h ] //[-------------------------------------------------------] /** * @brief * Null compute pipeline state class */ class ComputePipelineState final : public Rhi::IComputePipelineState { //[-------------------------------------------------------] //[ Public methods ] //[-------------------------------------------------------] public: /** * @brief * Constructor * * @param[in] nullRhi * Owner null RHI instance * @param[in] rootSignature * Root signature to use * @param[in] computeShader * Compute shader to use * @param[in] id * The unique compact compute pipeline state ID */ ComputePipelineState(NullRhi& nullRhi, Rhi::IRootSignature& rootSignature, Rhi::IComputeShader& computeShader, uint16_t id RHI_RESOURCE_DEBUG_NAME_PARAMETER_NO_DEFAULT) : IComputePipelineState(nullRhi, id RHI_RESOURCE_DEBUG_PASS_PARAMETER), mRootSignature(rootSignature), mComputeShader(computeShader) { // Add a reference to the given root signature and compute shader rootSignature.addReference(); computeShader.addReference(); } /** * @brief * Destructor */ virtual ~ComputePipelineState() override { // Release the root signature and compute shader reference mRootSignature.releaseReference(); mComputeShader.releaseReference(); // Free the unique compact compute pipeline state ID static_cast<NullRhi&>(getRhi()).ComputePipelineStateMakeId.DestroyID(getId()); } //[-------------------------------------------------------] //[ Protected virtual Rhi::RefCount methods ] //[-------------------------------------------------------] protected: inline virtual void selfDestruct() override { RHI_DELETE(getRhi().getContext(), ComputePipelineState, this); } //[-------------------------------------------------------] //[ Private methods ] //[-------------------------------------------------------] private: explicit ComputePipelineState(const ComputePipelineState& source) = delete; ComputePipelineState& operator =(const ComputePipelineState& source) = delete; //[-------------------------------------------------------] //[ Private data ] //[-------------------------------------------------------] private: Rhi::IRootSignature& mRootSignature; Rhi::IComputeShader& mComputeShader; }; //[-------------------------------------------------------] //[ Namespace ] //[-------------------------------------------------------] } // NullRhi //[-------------------------------------------------------] //[ Anonymous detail namespace ] //[-------------------------------------------------------] namespace { namespace detail { //[-------------------------------------------------------] //[ Global functions ] //[-------------------------------------------------------] namespace ImplementationDispatch { //[-------------------------------------------------------] //[ Command buffer ] //[-------------------------------------------------------] void DispatchCommandBuffer(const void* data, Rhi::IRhi& rhi) { const Rhi::Command::DispatchCommandBuffer* realData = static_cast<const Rhi::Command::DispatchCommandBuffer*>(data); RHI_ASSERT(rhi.getContext(), nullptr != realData->commandBufferToDispatch, "The null command buffer to dispatch must be valid") static_cast<NullRhi::NullRhi&>(rhi).dispatchCommandBufferInternal(*realData->commandBufferToDispatch); } //[-------------------------------------------------------] //[ Graphics ] //[-------------------------------------------------------] void SetGraphicsRootSignature(const void* data, Rhi::IRhi& rhi) { const Rhi::Command::SetGraphicsRootSignature* realData = static_cast<const Rhi::Command::SetGraphicsRootSignature*>(data); static_cast<NullRhi::NullRhi&>(rhi).setGraphicsRootSignature(realData->rootSignature); } void SetGraphicsPipelineState(const void* data, Rhi::IRhi& rhi) { const Rhi::Command::SetGraphicsPipelineState* realData = static_cast<const Rhi::Command::SetGraphicsPipelineState*>(data); static_cast<NullRhi::NullRhi&>(rhi).setGraphicsPipelineState(realData->graphicsPipelineState); } void SetGraphicsResourceGroup(const void* data, Rhi::IRhi& rhi) { const Rhi::Command::SetGraphicsResourceGroup* realData = static_cast<const Rhi::Command::SetGraphicsResourceGroup*>(data); static_cast<NullRhi::NullRhi&>(rhi).setGraphicsResourceGroup(realData->rootParameterIndex, realData->resourceGroup); } void SetGraphicsVertexArray(const void* data, Rhi::IRhi& rhi) { // Input-assembler (IA) stage const Rhi::Command::SetGraphicsVertexArray* realData = static_cast<const Rhi::Command::SetGraphicsVertexArray*>(data); static_cast<NullRhi::NullRhi&>(rhi).setGraphicsVertexArray(realData->vertexArray); } void SetGraphicsViewports(const void* data, Rhi::IRhi& rhi) { // Rasterizer (RS) stage const Rhi::Command::SetGraphicsViewports* realData = static_cast<const Rhi::Command::SetGraphicsViewports*>(data); static_cast<NullRhi::NullRhi&>(rhi).setGraphicsViewports(realData->numberOfViewports, (nullptr != realData->viewports) ? realData->viewports : reinterpret_cast<const Rhi::Viewport*>(Rhi::CommandPacketHelper::getAuxiliaryMemory(realData))); } void SetGraphicsScissorRectangles(const void* data, Rhi::IRhi& rhi) { // Rasterizer (RS) stage const Rhi::Command::SetGraphicsScissorRectangles* realData = static_cast<const Rhi::Command::SetGraphicsScissorRectangles*>(data); static_cast<NullRhi::NullRhi&>(rhi).setGraphicsScissorRectangles(realData->numberOfScissorRectangles, (nullptr != realData->scissorRectangles) ? realData->scissorRectangles : reinterpret_cast<const Rhi::ScissorRectangle*>(Rhi::CommandPacketHelper::getAuxiliaryMemory(realData))); } void SetGraphicsRenderTarget(const void* data, Rhi::IRhi& rhi) { // Output-merger (OM) stage const Rhi::Command::SetGraphicsRenderTarget* realData = static_cast<const Rhi::Command::SetGraphicsRenderTarget*>(data); static_cast<NullRhi::NullRhi&>(rhi).setGraphicsRenderTarget(realData->renderTarget); } void ClearGraphics(const void* data, Rhi::IRhi& rhi) { const Rhi::Command::ClearGraphics* realData = static_cast<const Rhi::Command::ClearGraphics*>(data); static_cast<NullRhi::NullRhi&>(rhi).clearGraphics(realData->clearFlags, realData->color, realData->z, realData->stencil); } void DrawGraphics(const void* data, Rhi::IRhi& rhi) { const Rhi::Command::DrawGraphics* realData = static_cast<const Rhi::Command::DrawGraphics*>(data); if (nullptr != realData->indirectBuffer) { // No resource owner security check in here, we only support emulated indirect buffer static_cast<NullRhi::NullRhi&>(rhi).drawGraphicsEmulated(realData->indirectBuffer->getEmulationData(), realData->indirectBufferOffset, realData->numberOfDraws); } else { static_cast<NullRhi::NullRhi&>(rhi).drawGraphicsEmulated(Rhi::CommandPacketHelper::getAuxiliaryMemory(realData), realData->indirectBufferOffset, realData->numberOfDraws); } } void DrawIndexedGraphics(const void* data, Rhi::IRhi& rhi) { const Rhi::Command::DrawIndexedGraphics* realData = static_cast<const Rhi::Command::DrawIndexedGraphics*>(data); if (nullptr != realData->indirectBuffer) { // No resource owner security check in here, we only support emulated indirect buffer static_cast<NullRhi::NullRhi&>(rhi).drawIndexedGraphicsEmulated(realData->indirectBuffer->getEmulationData(), realData->indirectBufferOffset, realData->numberOfDraws); } else { static_cast<NullRhi::NullRhi&>(rhi).drawIndexedGraphicsEmulated(Rhi::CommandPacketHelper::getAuxiliaryMemory(realData), realData->indirectBufferOffset, realData->numberOfDraws); } } void DrawMeshTasks(const void* data, Rhi::IRhi& rhi) { const Rhi::Command::DrawMeshTasks* realData = static_cast<const Rhi::Command::DrawMeshTasks*>(data); if (nullptr != realData->indirectBuffer) { // No resource owner security check in here, we only support emulated indirect buffer static_cast<NullRhi::NullRhi&>(rhi).drawMeshTasksEmulated(realData->indirectBuffer->getEmulationData(), realData->indirectBufferOffset, realData->numberOfDraws); } else { static_cast<NullRhi::NullRhi&>(rhi).drawMeshTasksEmulated(Rhi::CommandPacketHelper::getAuxiliaryMemory(realData), realData->indirectBufferOffset, realData->numberOfDraws); } } //[-------------------------------------------------------] //[ Compute ] //[-------------------------------------------------------] void SetComputeRootSignature(const void* data, Rhi::IRhi& rhi) { const Rhi::Command::SetComputeRootSignature* realData = static_cast<const Rhi::Command::SetComputeRootSignature*>(data); static_cast<NullRhi::NullRhi&>(rhi).setComputeRootSignature(realData->rootSignature); } void SetComputePipelineState(const void* data, Rhi::IRhi& rhi) { const Rhi::Command::SetComputePipelineState* realData = static_cast<const Rhi::Command::SetComputePipelineState*>(data); static_cast<NullRhi::NullRhi&>(rhi).setComputePipelineState(realData->computePipelineState); } void SetComputeResourceGroup(const void* data, Rhi::IRhi& rhi) { const Rhi::Command::SetComputeResourceGroup* realData = static_cast<const Rhi::Command::SetComputeResourceGroup*>(data); static_cast<NullRhi::NullRhi&>(rhi).setComputeResourceGroup(realData->rootParameterIndex, realData->resourceGroup); } void DispatchCompute(const void* data, Rhi::IRhi& rhi) { const Rhi::Command::DispatchCompute* realData = static_cast<const Rhi::Command::DispatchCompute*>(data); static_cast<NullRhi::NullRhi&>(rhi).dispatchCompute(realData->groupCountX, realData->groupCountY, realData->groupCountZ); } //[-------------------------------------------------------] //[ Resource ] //[-------------------------------------------------------] void SetTextureMinimumMaximumMipmapIndex(const void*, Rhi::IRhi&) {} void ResolveMultisampleFramebuffer(const void* data, Rhi::IRhi& rhi) { const Rhi::Command::ResolveMultisampleFramebuffer* realData = static_cast<const Rhi::Command::ResolveMultisampleFramebuffer*>(data); static_cast<NullRhi::NullRhi&>(rhi).resolveMultisampleFramebuffer(*realData->destinationRenderTarget, *realData->sourceMultisampleFramebuffer); } void CopyResource(const void* data, Rhi::IRhi& rhi) { const Rhi::Command::CopyResource* realData = static_cast<const Rhi::Command::CopyResource*>(data); static_cast<NullRhi::NullRhi&>(rhi).copyResource(*realData->destinationResource, *realData->sourceResource); } void GenerateMipmaps(const void* data, Rhi::IRhi& rhi) { const Rhi::Command::GenerateMipmaps* realData = static_cast<const Rhi::Command::GenerateMipmaps*>(data); static_cast<NullRhi::NullRhi&>(rhi).generateMipmaps(*realData->resource); } void CopyUniformBufferData(const void* data, Rhi::IRhi& rhi) { const Rhi::Command::CopyUniformBufferData* realData = static_cast<const Rhi::Command::CopyUniformBufferData*>(data); Rhi::MappedSubresource mappedSubresource; if (rhi.map(*realData->uniformBuffer, 0, Rhi::MapType::WRITE_DISCARD, 0, mappedSubresource)) { memcpy(mappedSubresource.data, Rhi::CommandPacketHelper::getAuxiliaryMemory(realData), realData->numberOfBytes); rhi.unmap(*realData->uniformBuffer, 0); } } void SetUniform(const void*, [[maybe_unused]] Rhi::IRhi& rhi) { RHI_ASSERT(rhi.getContext(), false, "The set uniform command isn't supported by the null RHI implementation") } //[-------------------------------------------------------] //[ Query ] //[-------------------------------------------------------] void ResetQueryPool(const void* data, Rhi::IRhi& rhi) { const Rhi::Command::ResetQueryPool* realData = static_cast<const Rhi::Command::ResetQueryPool*>(data); static_cast<NullRhi::NullRhi&>(rhi).resetQueryPool(*realData->queryPool, realData->firstQueryIndex, realData->numberOfQueries); } void BeginQuery(const void* data, Rhi::IRhi& rhi) { const Rhi::Command::BeginQuery* realData = static_cast<const Rhi::Command::BeginQuery*>(data); static_cast<NullRhi::NullRhi&>(rhi).beginQuery(*realData->queryPool, realData->queryIndex, realData->queryControlFlags); } void EndQuery(const void* data, Rhi::IRhi& rhi) { const Rhi::Command::EndQuery* realData = static_cast<const Rhi::Command::EndQuery*>(data); static_cast<NullRhi::NullRhi&>(rhi).endQuery(*realData->queryPool, realData->queryIndex); } void WriteTimestampQuery(const void* data, Rhi::IRhi& rhi) { const Rhi::Command::WriteTimestampQuery* realData = static_cast<const Rhi::Command::WriteTimestampQuery*>(data); static_cast<NullRhi::NullRhi&>(rhi).writeTimestampQuery(*realData->queryPool, realData->queryIndex); } //[-------------------------------------------------------] //[ Debug ] //[-------------------------------------------------------] #ifdef RHI_DEBUG void SetDebugMarker(const void* data, Rhi::IRhi& rhi) { const Rhi::Command::SetDebugMarker* realData = static_cast<const Rhi::Command::SetDebugMarker*>(data); static_cast<NullRhi::NullRhi&>(rhi).setDebugMarker(realData->name); } void BeginDebugEvent(const void* data, Rhi::IRhi& rhi) { const Rhi::Command::BeginDebugEvent* realData = static_cast<const Rhi::Command::BeginDebugEvent*>(data); static_cast<NullRhi::NullRhi&>(rhi).beginDebugEvent(realData->name); } void EndDebugEvent(const void*, Rhi::IRhi& rhi) { static_cast<NullRhi::NullRhi&>(rhi).endDebugEvent(); } #else void SetDebugMarker(const void*, Rhi::IRhi&) {} void BeginDebugEvent(const void*, Rhi::IRhi&) {} void EndDebugEvent(const void*, Rhi::IRhi&) {} #endif } //[-------------------------------------------------------] //[ Global definitions ] //[-------------------------------------------------------] static constexpr Rhi::ImplementationDispatchFunction DISPATCH_FUNCTIONS[static_cast<uint8_t>(Rhi::CommandDispatchFunctionIndex::NUMBER_OF_FUNCTIONS)] = { // Command buffer &ImplementationDispatch::DispatchCommandBuffer, // Graphics &ImplementationDispatch::SetGraphicsRootSignature, &ImplementationDispatch::SetGraphicsPipelineState, &ImplementationDispatch::SetGraphicsResourceGroup, &ImplementationDispatch::SetGraphicsVertexArray, // Input-assembler (IA) stage &ImplementationDispatch::SetGraphicsViewports, // Rasterizer (RS) stage &ImplementationDispatch::SetGraphicsScissorRectangles, // Rasterizer (RS) stage &ImplementationDispatch::SetGraphicsRenderTarget, // Output-merger (OM) stage &ImplementationDispatch::ClearGraphics, &ImplementationDispatch::DrawGraphics, &ImplementationDispatch::DrawIndexedGraphics, &ImplementationDispatch::DrawMeshTasks, // Compute &ImplementationDispatch::SetComputeRootSignature, &ImplementationDispatch::SetComputePipelineState, &ImplementationDispatch::SetComputeResourceGroup, &ImplementationDispatch::DispatchCompute, // Resource &ImplementationDispatch::SetTextureMinimumMaximumMipmapIndex, &ImplementationDispatch::ResolveMultisampleFramebuffer, &ImplementationDispatch::CopyResource, &ImplementationDispatch::GenerateMipmaps, &ImplementationDispatch::CopyUniformBufferData, &ImplementationDispatch::SetUniform, // Query &ImplementationDispatch::ResetQueryPool, &ImplementationDispatch::BeginQuery, &ImplementationDispatch::EndQuery, &ImplementationDispatch::WriteTimestampQuery, // Debug &ImplementationDispatch::SetDebugMarker, &ImplementationDispatch::BeginDebugEvent, &ImplementationDispatch::EndDebugEvent }; //[-------------------------------------------------------] //[ Anonymous detail namespace ] //[-------------------------------------------------------] } // detail } //[-------------------------------------------------------] //[ Namespace ] //[-------------------------------------------------------] namespace NullRhi { //[-------------------------------------------------------] //[ Public methods ] //[-------------------------------------------------------] NullRhi::NullRhi(const Rhi::Context& context) : IRhi(Rhi::NameId::NULL_DUMMY, context), VertexArrayMakeId(context.getAllocator()), GraphicsPipelineStateMakeId(context.getAllocator()), ComputePipelineStateMakeId(context.getAllocator()), mShaderLanguage(nullptr), mRenderTarget(nullptr), mGraphicsRootSignature(nullptr), mComputeRootSignature(nullptr) { // Initialize the capabilities initializeCapabilities(); } NullRhi::~NullRhi() { // Release instances if (nullptr != mRenderTarget) { mRenderTarget->releaseReference(); mRenderTarget = nullptr; } if (nullptr != mGraphicsRootSignature) { mGraphicsRootSignature->releaseReference(); mGraphicsRootSignature = nullptr; } if (nullptr != mComputeRootSignature) { mComputeRootSignature->releaseReference(); mComputeRootSignature = nullptr; } #ifdef RHI_STATISTICS { // For debugging: At this point there should be no resource instances left, validate this! // -> Are the currently any resource instances? const uint32_t numberOfCurrentResources = getStatistics().getNumberOfCurrentResources(); if (numberOfCurrentResources > 0) { // Error! if (numberOfCurrentResources > 1) { RHI_ASSERT(mContext, false, "The null RHI implementation is going to be destroyed, but there are still %u resource instances left (memory leak)", numberOfCurrentResources) } else { RHI_ASSERT(mContext, false, "The null RHI implementation is going to be destroyed, but there is still one resource instance left (memory leak)") } // Use debug output to show the current number of resource instances getStatistics().debugOutputCurrentResouces(mContext); } } #endif // Release the null shader language instance, in case we have one if (nullptr != mShaderLanguage) { mShaderLanguage->releaseReference(); } } void NullRhi::dispatchCommandBufferInternal(const Rhi::CommandBuffer& commandBuffer) { // Loop through all commands const uint8_t* commandPacketBuffer = commandBuffer.getCommandPacketBuffer(); Rhi::ConstCommandPacket constCommandPacket = commandPacketBuffer; while (nullptr != constCommandPacket) { { // Dispatch command packet const Rhi::CommandDispatchFunctionIndex commandDispatchFunctionIndex = Rhi::CommandPacketHelper::loadCommandDispatchFunctionIndex(constCommandPacket); const void* command = Rhi::CommandPacketHelper::loadCommand(constCommandPacket); detail::DISPATCH_FUNCTIONS[static_cast<uint32_t>(commandDispatchFunctionIndex)](command, *this); } { // Next command const uint32_t nextCommandPacketByteIndex = Rhi::CommandPacketHelper::getNextCommandPacketByteIndex(constCommandPacket); constCommandPacket = (~0u != nextCommandPacketByteIndex) ? &commandPacketBuffer[nextCommandPacketByteIndex] : nullptr; } } } //[-------------------------------------------------------] //[ Graphics ] //[-------------------------------------------------------] void NullRhi::setGraphicsRootSignature(Rhi::IRootSignature* rootSignature) { if (nullptr != mGraphicsRootSignature) { mGraphicsRootSignature->releaseReference(); } mGraphicsRootSignature = static_cast<RootSignature*>(rootSignature); if (nullptr != mGraphicsRootSignature) { mGraphicsRootSignature->addReference(); // Sanity check RHI_MATCH_CHECK(*this, *rootSignature) } } void NullRhi::setGraphicsPipelineState(Rhi::IGraphicsPipelineState* graphicsPipelineState) { if (nullptr != graphicsPipelineState) { // Sanity check RHI_MATCH_CHECK(*this, *graphicsPipelineState) } else { // TODO(co) Handle this situation? } } void NullRhi::setGraphicsResourceGroup([[maybe_unused]] uint32_t rootParameterIndex, Rhi::IResourceGroup* resourceGroup) { // Security checks #ifdef RHI_DEBUG { RHI_ASSERT(mContext, nullptr != mGraphicsRootSignature, "No null RHI implementation graphics root signature set") const Rhi::RootSignature& rootSignature = mGraphicsRootSignature->getRootSignature(); RHI_ASSERT(mContext, rootParameterIndex < rootSignature.numberOfParameters, "The null RHI implementation root parameter index is out of bounds") const Rhi::RootParameter& rootParameter = rootSignature.parameters[rootParameterIndex]; RHI_ASSERT(mContext, Rhi::RootParameterType::DESCRIPTOR_TABLE == rootParameter.parameterType, "The null RHI implementation root parameter index doesn't reference a descriptor table") RHI_ASSERT(mContext, nullptr != reinterpret_cast<const Rhi::DescriptorRange*>(rootParameter.descriptorTable.descriptorRanges), "The null RHI implementation descriptor ranges is a null pointer") } #endif if (nullptr != resourceGroup) { // Sanity check RHI_MATCH_CHECK(*this, *resourceGroup) // TODO(co) Some additional resource type root signature security checks in debug build? } else { // TODO(co) Handle this situation? } } void NullRhi::setGraphicsVertexArray(Rhi::IVertexArray* vertexArray) { // Input-assembler (IA) stage // Nothing here, the following is just for debugging if (nullptr != vertexArray) { // Sanity check RHI_MATCH_CHECK(*this, *vertexArray) } } void NullRhi::setGraphicsViewports([[maybe_unused]] uint32_t numberOfViewports, [[maybe_unused]] const Rhi::Viewport* viewports) { // Rasterizer (RS) stage // Sanity check RHI_ASSERT(mContext, numberOfViewports > 0 && nullptr != viewports, "Invalid null rasterizer state viewports") } void NullRhi::setGraphicsScissorRectangles([[maybe_unused]] uint32_t numberOfScissorRectangles, [[maybe_unused]] const Rhi::ScissorRectangle* scissorRectangles) { // Rasterizer (RS) stage // Sanity check RHI_ASSERT(mContext, numberOfScissorRectangles > 0 && nullptr != scissorRectangles, "Invalid null rasterizer state scissor rectangles") } void NullRhi::setGraphicsRenderTarget(Rhi::IRenderTarget* renderTarget) { // Output-merger (OM) stage // New render target? if (mRenderTarget != renderTarget) { // Set a render target? if (nullptr != renderTarget) { // Sanity check RHI_MATCH_CHECK(*this, *renderTarget) // Release the render target reference, in case we have one if (nullptr != mRenderTarget) { mRenderTarget->releaseReference(); } // Set new render target and add a reference to it mRenderTarget = renderTarget; mRenderTarget->addReference(); // That's all folks! } else { // Release the render target reference, in case we have one if (nullptr != mRenderTarget) { mRenderTarget->releaseReference(); mRenderTarget = nullptr; } // That's all folks! } } } void NullRhi::clearGraphics(uint32_t, const float [4], [[maybe_unused]] float z, uint32_t) { // Sanity check RHI_ASSERT(mContext, z >= 0.0f && z <= 1.0f, "The null clear graphics z value must be between [0, 1] (inclusive)") } void NullRhi::drawGraphicsEmulated([[maybe_unused]] const uint8_t* emulationData, uint32_t, [[maybe_unused]] uint32_t numberOfDraws) { // Sanity checks RHI_ASSERT(mContext, nullptr != emulationData, "The null emulation data must be valid") RHI_ASSERT(mContext, numberOfDraws > 0, "The number of null draws must not be zero") } void NullRhi::drawIndexedGraphicsEmulated([[maybe_unused]] const uint8_t* emulationData, uint32_t, [[maybe_unused]] uint32_t numberOfDraws) { // Sanity checks RHI_ASSERT(mContext, nullptr != emulationData, "The null emulation data must be valid") RHI_ASSERT(mContext, numberOfDraws > 0, "The number of null draws must not be zero") } void NullRhi::drawMeshTasksEmulated([[maybe_unused]] const uint8_t* emulationData, uint32_t, [[maybe_unused]] uint32_t numberOfDraws) { // Sanity checks RHI_ASSERT(mContext, nullptr != emulationData, "The null emulation data must be valid") RHI_ASSERT(mContext, numberOfDraws > 0, "The number of null draws must not be zero") } //[-------------------------------------------------------] //[ Compute ] //[-------------------------------------------------------] void NullRhi::setComputeRootSignature(Rhi::IRootSignature* rootSignature) { if (nullptr != mComputeRootSignature) { mComputeRootSignature->releaseReference(); } mComputeRootSignature = static_cast<RootSignature*>(rootSignature); if (nullptr != mComputeRootSignature) { mComputeRootSignature->addReference(); // Sanity check RHI_MATCH_CHECK(*this, *rootSignature) } } void NullRhi::setComputePipelineState(Rhi::IComputePipelineState* computePipelineState) { if (nullptr != computePipelineState) { // Sanity check RHI_MATCH_CHECK(*this, *computePipelineState) } else { // TODO(co) Handle this situation? } } void NullRhi::setComputeResourceGroup([[maybe_unused]] uint32_t rootParameterIndex, Rhi::IResourceGroup* resourceGroup) { // Security checks #ifdef RHI_DEBUG { RHI_ASSERT(mContext, nullptr != mComputeRootSignature, "No null RHI implementation compute root signature set") const Rhi::RootSignature& rootSignature = mComputeRootSignature->getRootSignature(); RHI_ASSERT(mContext, rootParameterIndex < rootSignature.numberOfParameters, "The null RHI implementation root parameter index is out of bounds") const Rhi::RootParameter& rootParameter = rootSignature.parameters[rootParameterIndex]; RHI_ASSERT(mContext, Rhi::RootParameterType::DESCRIPTOR_TABLE == rootParameter.parameterType, "The null RHI implementation root parameter index doesn't reference a descriptor table") RHI_ASSERT(mContext, nullptr != reinterpret_cast<const Rhi::DescriptorRange*>(rootParameter.descriptorTable.descriptorRanges), "The null RHI implementation descriptor ranges is a null pointer") } #endif if (nullptr != resourceGroup) { // Sanity check RHI_MATCH_CHECK(*this, *resourceGroup) // TODO(co) Some additional resource type root signature security checks in debug build? } else { // TODO(co) Handle this situation? } } void NullRhi::dispatchCompute(uint32_t, uint32_t, uint32_t) {} //[-------------------------------------------------------] //[ Resource ] //[-------------------------------------------------------] void NullRhi::resolveMultisampleFramebuffer(Rhi::IRenderTarget&, Rhi::IFramebuffer&) {} void NullRhi::copyResource(Rhi::IResource&, Rhi::IResource&) {} void NullRhi::generateMipmaps(Rhi::IResource&) {} //[-------------------------------------------------------] //[ Query ] //[-------------------------------------------------------] void NullRhi::resetQueryPool(Rhi::IQueryPool&, uint32_t, uint32_t) {} void NullRhi::beginQuery(Rhi::IQueryPool&, uint32_t, uint32_t) {} void NullRhi::endQuery(Rhi::IQueryPool&, uint32_t) {} void NullRhi::writeTimestampQuery(Rhi::IQueryPool&, uint32_t) {} //[-------------------------------------------------------] //[ Debug ] //[-------------------------------------------------------] #ifdef RHI_DEBUG void NullRhi::setDebugMarker(const char*) {} void NullRhi::beginDebugEvent(const char*) {} void NullRhi::endDebugEvent() {} #endif //[-------------------------------------------------------] //[ Public virtual Rhi::IRhi methods ] //[-------------------------------------------------------] const char* NullRhi::getName() const { return "Null"; } bool NullRhi::isInitialized() const { return true; } bool NullRhi::isDebugEnabled() { // Nothing here // Debug disabled return false; } //[-------------------------------------------------------] //[ Shader language ] //[-------------------------------------------------------] uint32_t NullRhi::getNumberOfShaderLanguages() const { // Only one shader language supported in here return 1; } const char* NullRhi::getShaderLanguageName([[maybe_unused]] uint32_t index) const { RHI_ASSERT(mContext, index < getNumberOfShaderLanguages(), "Null: Shader language index is out-of-bounds") return ::detail::NULL_NAME; } Rhi::IShaderLanguage* NullRhi::getShaderLanguage(const char* shaderLanguageName) { // In case "shaderLanguage" is a null pointer, use the default shader language if (nullptr != shaderLanguageName) { // In case "shaderLanguage" is a null pointer, use the default shader language // -> Only one shader language supported in here if (nullptr == shaderLanguageName || !stricmp(shaderLanguageName, ::detail::NULL_NAME)) { // If required, create the null shader language instance right now if (nullptr == mShaderLanguage) { mShaderLanguage = RHI_NEW(mContext, ShaderLanguage)(*this); mShaderLanguage->addReference(); // Internal RHI reference } // Return the shader language instance return mShaderLanguage; } // Error! return nullptr; } // Return the null shader language instance as default return getShaderLanguage(::detail::NULL_NAME); } //[-------------------------------------------------------] //[ Resource creation ] //[-------------------------------------------------------] Rhi::IRenderPass* NullRhi::createRenderPass(uint32_t numberOfColorAttachments, const Rhi::TextureFormat::Enum* colorAttachmentTextureFormats, Rhi::TextureFormat::Enum depthStencilAttachmentTextureFormat, uint8_t numberOfMultisamples RHI_RESOURCE_DEBUG_NAME_PARAMETER_NO_DEFAULT) { return RHI_NEW(mContext, RenderPass)(*this, numberOfColorAttachments, colorAttachmentTextureFormats, depthStencilAttachmentTextureFormat, numberOfMultisamples RHI_RESOURCE_DEBUG_PASS_PARAMETER); } Rhi::IQueryPool* NullRhi::createQueryPool([[maybe_unused]] Rhi::QueryType queryType, [[maybe_unused]] uint32_t numberOfQueries RHI_RESOURCE_DEBUG_NAME_MAYBE_UNUSED_PARAMETER_NO_DEFAULT) { // TODO(co) Implement me return nullptr; } Rhi::ISwapChain* NullRhi::createSwapChain(Rhi::IRenderPass& renderPass, Rhi::WindowHandle windowHandle, bool RHI_RESOURCE_DEBUG_NAME_PARAMETER_NO_DEFAULT) { // Sanity checks RHI_MATCH_CHECK(*this, renderPass) RHI_ASSERT(mContext, NULL_HANDLE != windowHandle.nativeWindowHandle, "Null: The provided native window handle must not be a null handle") // Create the swap chain return RHI_NEW(mContext, SwapChain)(renderPass, windowHandle RHI_RESOURCE_DEBUG_PASS_PARAMETER); } Rhi::IFramebuffer* NullRhi::createFramebuffer(Rhi::IRenderPass& renderPass, const Rhi::FramebufferAttachment* colorFramebufferAttachments, const Rhi::FramebufferAttachment* depthStencilFramebufferAttachment RHI_RESOURCE_DEBUG_NAME_PARAMETER_NO_DEFAULT) { // Sanity check RHI_MATCH_CHECK(*this, renderPass) // We don't keep a reference to the provided textures in here // -> Ensure a correct reference counter behaviour // Are there any color textures? const uint32_t numberOfColorAttachments = static_cast<RenderPass&>(renderPass).getNumberOfColorAttachments(); if (numberOfColorAttachments > 0) { // Loop through all color textures const Rhi::FramebufferAttachment* colorFramebufferAttachmentsEnd = colorFramebufferAttachments + numberOfColorAttachments; for (const Rhi::FramebufferAttachment* colorFramebufferAttachment = colorFramebufferAttachments; colorFramebufferAttachment < colorFramebufferAttachmentsEnd; ++colorFramebufferAttachment) { // Valid entry? if (nullptr != colorFramebufferAttachment->texture) { // TODO(co) Add security check: Is the given resource one of the currently used RHI? colorFramebufferAttachment->texture->addReference(); colorFramebufferAttachment->texture->releaseReference(); } } } // Add a reference to the used depth stencil texture if (nullptr != depthStencilFramebufferAttachment) { depthStencilFramebufferAttachment->texture->addReference(); depthStencilFramebufferAttachment->texture->releaseReference(); } // Create the framebuffer instance return RHI_NEW(mContext, Framebuffer)(renderPass RHI_RESOURCE_DEBUG_PASS_PARAMETER); } Rhi::IBufferManager* NullRhi::createBufferManager() { return RHI_NEW(mContext, BufferManager)(*this); } Rhi::ITextureManager* NullRhi::createTextureManager() { return RHI_NEW(mContext, TextureManager)(*this); } Rhi::IRootSignature* NullRhi::createRootSignature(const Rhi::RootSignature& rootSignature RHI_RESOURCE_DEBUG_NAME_PARAMETER_NO_DEFAULT) { return RHI_NEW(mContext, RootSignature)(*this, rootSignature RHI_RESOURCE_DEBUG_PASS_PARAMETER); } Rhi::IGraphicsPipelineState* NullRhi::createGraphicsPipelineState(const Rhi::GraphicsPipelineState& graphicsPipelineState RHI_RESOURCE_DEBUG_NAME_PARAMETER_NO_DEFAULT) { // Sanity checks RHI_ASSERT(mContext, nullptr != graphicsPipelineState.rootSignature, "Null: Invalid graphics pipeline state root signature") RHI_ASSERT(mContext, nullptr != graphicsPipelineState.graphicsProgram, "Null: Invalid graphics pipeline state graphics program") RHI_ASSERT(mContext, nullptr != graphicsPipelineState.renderPass, "Null: Invalid graphics pipeline state render pass") // Create graphics pipeline state uint16_t id = 0; if (GraphicsPipelineStateMakeId.CreateID(id)) { return RHI_NEW(mContext, GraphicsPipelineState)(*this, graphicsPipelineState, id RHI_RESOURCE_DEBUG_PASS_PARAMETER); } // Error: Ensure a correct reference counter behaviour graphicsPipelineState.rootSignature->addReference(); graphicsPipelineState.rootSignature->releaseReference(); graphicsPipelineState.graphicsProgram->addReference(); graphicsPipelineState.graphicsProgram->releaseReference(); graphicsPipelineState.renderPass->addReference(); graphicsPipelineState.renderPass->releaseReference(); return nullptr; } Rhi::IComputePipelineState* NullRhi::createComputePipelineState(Rhi::IRootSignature& rootSignature, Rhi::IComputeShader& computeShader RHI_RESOURCE_DEBUG_NAME_PARAMETER_NO_DEFAULT) { // Sanity checks RHI_MATCH_CHECK(*this, rootSignature) RHI_MATCH_CHECK(*this, computeShader) // Create the compute pipeline state uint16_t id = 0; if (ComputePipelineStateMakeId.CreateID(id)) { return RHI_NEW(mContext, ComputePipelineState)(*this, rootSignature, computeShader, id RHI_RESOURCE_DEBUG_PASS_PARAMETER); } // Error: Ensure a correct reference counter behaviour rootSignature.addReference(); rootSignature.releaseReference(); computeShader.addReference(); computeShader.releaseReference(); return nullptr; } Rhi::ISamplerState* NullRhi::createSamplerState(const Rhi::SamplerState& RHI_RESOURCE_DEBUG_NAME_PARAMETER_NO_DEFAULT) { return RHI_NEW(mContext, SamplerState)(*this RHI_RESOURCE_DEBUG_PASS_PARAMETER); } //[-------------------------------------------------------] //[ Resource handling ] //[-------------------------------------------------------] bool NullRhi::map(Rhi::IResource&, uint32_t, Rhi::MapType, uint32_t, Rhi::MappedSubresource&) { // Not supported by the null RHI return false; } void NullRhi::unmap(Rhi::IResource&, uint32_t) {} bool NullRhi::getQueryPoolResults(Rhi::IQueryPool&, uint32_t, uint8_t*, uint32_t, uint32_t, uint32_t, uint32_t) { return true; } //[-------------------------------------------------------] //[ Operation ] //[-------------------------------------------------------] void NullRhi::dispatchCommandBuffer(const Rhi::CommandBuffer& commandBuffer) { // Sanity check RHI_ASSERT(mContext, !commandBuffer.isEmpty(), "The null command buffer to dispatch mustn't be empty") // Dispatch command buffer dispatchCommandBufferInternal(commandBuffer); } //[-------------------------------------------------------] //[ Protected virtual Rhi::RefCount methods ] //[-------------------------------------------------------] void NullRhi::selfDestruct() { RHI_DELETE(mContext, NullRhi, this); } //[-------------------------------------------------------] //[ Private methods ] //[-------------------------------------------------------] void NullRhi::initializeCapabilities() { strcpy(mCapabilities.deviceName, "Null"); // Preferred swap chain texture format mCapabilities.preferredSwapChainColorTextureFormat = Rhi::TextureFormat::Enum::R8G8B8A8; mCapabilities.preferredSwapChainDepthStencilTextureFormat = Rhi::TextureFormat::Enum::D32_FLOAT; // Maximum number of viewports (always at least 1) mCapabilities.maximumNumberOfViewports = 1; // Maximum number of simultaneous render targets (if <1 render to texture is not supported) mCapabilities.maximumNumberOfSimultaneousRenderTargets = 8; // Maximum texture dimension mCapabilities.maximumTextureDimension = 42; // Maximum number of 1D texture array slices (usually 512, in case there's no support for 1D texture arrays it's 0) mCapabilities.maximumNumberOf1DTextureArraySlices = 42; // Maximum number of 2D texture array slices (usually 512, in case there's no support for 2D texture arrays it's 0) mCapabilities.maximumNumberOf2DTextureArraySlices = 42; // Maximum number of cube texture array slices (usually 512, in case there's no support for cube texture arrays it's 0) mCapabilities.maximumNumberOfCubeTextureArraySlices = 42; // Maximum texture buffer (TBO) size in texel (>65536, typically much larger than that of one-dimensional texture, in case there's no support for texture buffer it's 0) mCapabilities.maximumTextureBufferSize = mCapabilities.maximumStructuredBufferSize = 42; // Maximum indirect buffer size in bytes mCapabilities.maximumIndirectBufferSize = 128 * 1024; // 128 KiB // Maximum uniform buffer (UBO) size in bytes (usually at least 4096 * 16 bytes, in case there's no support for uniform buffer it's 0) // -> Let's use the DirectX 11 value: See https://msdn.microsoft.com/en-us/library/windows/desktop/ff819065(v=vs.85).aspx - "Resource Limits (Direct3D 11)" - "Number of elements in a constant buffer D3D11_REQ_CONSTANT_BUFFER_ELEMENT_COUNT (4096)" // -> One element = float4 = 16 bytes mCapabilities.maximumUniformBufferSize = 4096 * 16; // Maximum number of multisamples (always at least 1, usually 8) mCapabilities.maximumNumberOfMultisamples = 1; // Maximum anisotropy (always at least 1, usually 16) mCapabilities.maximumAnisotropy = 16; // Left-handed coordinate system with clip space depth value range 0..1 mCapabilities.upperLeftOrigin = mCapabilities.zeroToOneClipZ = true; // Individual uniforms ("constants" in Direct3D terminology) supported? If not, only uniform buffer objects are supported. mCapabilities.individualUniforms = true; // Instanced arrays supported? (shader model 3 feature, vertex array element advancing per-instance instead of per-vertex) mCapabilities.instancedArrays = true; // Draw instanced supported? (shader model 4 feature, build in shader variable holding the current instance ID) mCapabilities.drawInstanced = true; // Base vertex supported for draw calls? mCapabilities.baseVertex = true; // The null RHI has native multithreading mCapabilities.nativeMultithreading = true; // The null RHI has no shader bytecode support mCapabilities.shaderBytecode = false; // Is there support for vertex shaders (VS)? mCapabilities.vertexShader = true; // Maximum number of vertices per patch (usually 0 for no tessellation support or 32 which is the maximum number of supported vertices per patch) mCapabilities.maximumNumberOfPatchVertices = 32; // Maximum number of vertices a geometry shader can emit (usually 0 for no geometry shader support or 1024) mCapabilities.maximumNumberOfGsOutputVertices = 1024; // Is there support for fragment shaders (FS)? mCapabilities.fragmentShader = true; // Is there support for task shaders (TS) and mesh shaders (MS)? mCapabilities.meshShader = true; // Is there support for compute shaders (CS)? mCapabilities.computeShader = true; } //[-------------------------------------------------------] //[ Namespace ] //[-------------------------------------------------------] } // NullRhi //[-------------------------------------------------------] //[ Global functions ] //[-------------------------------------------------------] // Export the instance creation function #ifdef RHI_NULL_EXPORTS #define NULLRHI_FUNCTION_EXPORT GENERIC_FUNCTION_EXPORT #else #define NULLRHI_FUNCTION_EXPORT #endif NULLRHI_FUNCTION_EXPORT Rhi::IRhi* createNullRhiInstance(const Rhi::Context& context) { return RHI_NEW(context, NullRhi::NullRhi)(context); } #undef NULLRHI_FUNCTION_EXPORT
35.656026
501
0.587536
cofenberg
c79423b4a3e1f6d808ad197c16dd24e8336a8ac6
6,480
cpp
C++
examples/sobelfilter/xf_sobel_tb.cpp
lt23yuan/test
5fe36b0d1dd5b182fc03b7849d53a88936331860
[ "BSD-3-Clause" ]
null
null
null
examples/sobelfilter/xf_sobel_tb.cpp
lt23yuan/test
5fe36b0d1dd5b182fc03b7849d53a88936331860
[ "BSD-3-Clause" ]
null
null
null
examples/sobelfilter/xf_sobel_tb.cpp
lt23yuan/test
5fe36b0d1dd5b182fc03b7849d53a88936331860
[ "BSD-3-Clause" ]
null
null
null
/*************************************************************************** Copyright (c) 2016, Xilinx, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ***************************************************************************/ #include <stdio.h> #include <stdlib.h> #include "xf_headers.h" #include "xf_sobel_config.h" int main(int argc, char** argv) { if(argc != 2) { fprintf(stderr,"Invalid Number of Arguments!\nUsage:\n"); fprintf(stderr,"<Executable Name> <input image path> \n"); return -1; } char in[100], in1[100], out_hlsx[100], out_ocvx[100]; char out_errorx[100], out_hlsy[100], out_ocvy[100], out_errory[100]; cv::Mat in_img, in_gray, diff, hlsx_32F, hlsy_32F; cv::Mat c_grad_x, c_grad_y; cv::Mat c_grad_x_1, c_grad_y_1; cv::Mat hls_grad_x, hls_grad_y; cv::Mat diff_grad_x, diff_grad_y; // reading in the color image in_img = cv::imread(argv[1], 1); if(in_img.data == NULL) { fprintf(stderr,"Cannot open image at %s\n", in); return 0; } cvtColor(in_img, in_gray, CV_BGR2GRAY); ///////////////// Opencv Reference //////////////////////// int scale = 1; int delta = 0; #if (FILTER_WIDTH != 7) // create memory for output images hls_grad_x.create(in_gray.rows,in_gray.cols,CV_16S); hls_grad_y.create(in_gray.rows,in_gray.cols,CV_16S); diff_grad_x.create(in_gray.rows,in_gray.cols,CV_16S); diff_grad_y.create(in_gray.rows,in_gray.cols,CV_16S); int ddepth = CV_16S; typedef int16_t TYPE; #endif #if (FILTER_WIDTH == 7) // create memory for output images hls_grad_x.create(in_gray.rows,in_gray.cols,CV_32S); hls_grad_y.create(in_gray.rows,in_gray.cols,CV_32S); diff_grad_x.create(in_gray.rows,in_gray.cols,CV_32S); diff_grad_y.create(in_gray.rows,in_gray.cols,CV_32S); int ddepth = CV_32F; typedef int TYPE; #endif cv::Sobel( in_gray, c_grad_x_1, ddepth, 1, 0, FILTER_WIDTH, scale, delta, cv::BORDER_CONSTANT ); cv::Sobel( in_gray, c_grad_y_1, ddepth, 0, 1, FILTER_WIDTH, scale, delta, cv::BORDER_CONSTANT ); imwrite("out_ocvx.jpg", c_grad_x_1); imwrite("out_ocvy.jpg", c_grad_y_1); ////////////////// HLS TOP Function Call //////////////////////// #if (FILTER_WIDTH == 3 | FILTER_WIDTH == 5) ap_uint<8> *src_ptr = (ap_uint<8> *)in_gray.data; ap_uint<16> *dst_ptrx = (ap_uint<16> *)hls_grad_x.data; ap_uint<16> *dst_ptry = (ap_uint<16> *)hls_grad_y.data; #elif (FILTER_WIDTH == 7) ap_uint<8> *src_ptr = (ap_uint<8> *)in_gray.data; ap_uint<32> *dst_ptrx = (ap_uint<32> *)hls_grad_x.data; ap_uint<32> *dst_ptry = (ap_uint<32> *)hls_grad_y.data; #endif unsigned short height = in_gray.rows; unsigned short width = in_gray.cols; xF::Mat<IN_TYPE,HEIGHT,WIDTH,NPC1> imgInput(in_gray.rows,in_gray.cols); xF::Mat<OUT_TYPE,HEIGHT,WIDTH,NPC1> imgOutputx(in_gray.rows,in_gray.cols); xF::Mat<OUT_TYPE,HEIGHT,WIDTH,NPC1> imgOutputy(in_gray.rows,in_gray.cols); imgInput.copyTo(in_gray.data); #if __SDSCC__ TIME_STAMP_INIT #endif //xFSobel<XF_BORDER_CONSTANT,FILTER_WIDTH,IN_TYPE,OUT_TYPE,HEIGHT, WIDTH,NPC1>(imgInput, imgOutputx,imgOutputy); sobel_accel(imgInput, imgOutputx,imgOutputy); #if __SDSCC__ TIME_STAMP #endif hls_grad_x.data = (unsigned char *)imgOutputx.copyFrom(); hls_grad_y.data = (unsigned char *)imgOutputy.copyFrom(); imwrite("out_hlsx.jpg", hls_grad_x); imwrite("out_hlsy.jpg", hls_grad_y); ////////////////// Compute Absolute Difference //////////////////// #if (FILTER_WIDTH == 3 | FILTER_WIDTH == 5) absdiff(c_grad_x_1, hls_grad_x, diff_grad_x); absdiff(c_grad_y_1, hls_grad_y, diff_grad_y); #endif #if (FILTER_WIDTH == 7) c_grad_x_1.convertTo(c_grad_x, CV_32S); c_grad_y_1.convertTo(c_grad_y, CV_32S); absdiff(c_grad_x, hls_grad_x, diff_grad_x); absdiff(c_grad_y, hls_grad_y, diff_grad_y); #endif imwrite("out_errorx.jpg", diff_grad_x); imwrite("out_errory.jpg", diff_grad_y); // Find minimum and maximum differences. double minval=256,maxval=0; double minval1=256,maxval1=0; int cnt = 0, cnt1 =0; for(int i=0;i<in_img.rows;i++) { for(int j=0;j<in_img.cols;j++) { TYPE v = diff_grad_y.at<TYPE>(i,j); TYPE v1 = diff_grad_x.at<TYPE>(i,j); if (v>0) cnt++; if (minval > v ) minval = v; if (maxval < v) maxval = v; if (v1>0) cnt1++; if (minval1 > v1 ) minval1 = v1; if (maxval1 < v1) maxval1 = v1; } } float err_per = 100.0*(float)cnt/(in_img.rows*in_img.cols); float err_per1 = 100.0*(float)cnt1/(in_img.rows*in_img.cols); fprintf(stderr,"Minimum error in intensity = %f\n Maximum error in intensity = %f\n Percentage of pixels above error threshold = %f\n",minval,maxval,err_per); fprintf(stderr,"Minimum error in intensity = %f\n Maximum error in intensity = %f\n Percentage of pixels above error threshold = %f\n",minval1,maxval1,err_per1); in_img.~Mat(); in_gray.~Mat(); c_grad_x.~Mat(); c_grad_y.~Mat();; hls_grad_x.~Mat(); hls_grad_y.~Mat(); diff_grad_x.~Mat(); diff_grad_y.~Mat(); int ret=0; if(err_per > 0.0f) { printf("Test failed .... !!!\n"); ret = 1; }else { printf("Test Passed .... !!!\n"); ret = 0; } return ret; }
31.609756
162
0.696914
lt23yuan
c79a2d0280a7bd566deb803c269f52dde466fff2
5,714
cpp
C++
src/design_editor/reg/overriders/RelativeBoxes.cpp
TheMrButcher/opengl_lessons
76ac96c45773a54a85d49c6994770b0c3496303f
[ "MIT" ]
1
2016-10-25T21:15:16.000Z
2016-10-25T21:15:16.000Z
src/design_editor/reg/overriders/RelativeBoxes.cpp
TheMrButcher/gamebase
76ac96c45773a54a85d49c6994770b0c3496303f
[ "MIT" ]
375
2016-06-04T11:27:40.000Z
2019-04-14T17:11:09.000Z
src/design_editor/reg/overriders/RelativeBoxes.cpp
TheMrButcher/gamebase
76ac96c45773a54a85d49c6994770b0c3496303f
[ "MIT" ]
null
null
null
/** * Copyright (c) 2018 Slavnejshev Filipp * This file is licensed under the terms of the MIT license. */ #include "RelativeBoxes.h" #include "RelativeValueInUI.h" #include <reg/tools.h> #include <gamebase/impl/relpos/AligningOffset.h> #include <gamebase/impl/relpos/FixedOffset.h> namespace gamebase { namespace editor { void ComplexBoxInUI::serialize(impl::Serializer& s) const { s << "widthSource" << widthSource() << "heightSource" << heightSource() << "width" << m_widthValueInUI << "height" << m_heightValueInUI << "horOffset" << m_horOffsetInUI << "vertOffset" << m_vertOffsetInUI; } void ComplexBoxInUI::setOffset(impl::IRelativeOffset* offset) { if (offset) { if (auto aligningOffset = dynamic_cast<const impl::AligningOffset*>(offset)) { if (aligningOffset->horAlign() != impl::HorAlign::None || aligningOffset->vertAlign() != impl::VertAlign::None) std::cerr << "Warning: offset of box shouldn't contain any alignment" << std::endl; setOffset( aligningOffset->horOffset(), aligningOffset->vertOffset()); return; } else if (auto fixedOffset = dynamic_cast<const impl::FixedOffset*>(offset)) { Vec2 v = fixedOffset->get(); setOffset(pixels(v.x), pixels(v.y)); return; } else { std::cerr << "Warning: unknown type of offset! Replaced with zero" << std::endl; } } setOffset(zeroValue(), zeroValue()); } std::unique_ptr<impl::IObject> deserializeSquareBox(impl::Deserializer&) { return std::unique_ptr<impl::IObject>(new ComplexBoxInUI( identic(), identic(), impl::BoxSize::Min, impl::BoxSize::Min)); } std::unique_ptr<impl::IObject> deserializeRelativeBox(impl::Deserializer& deserializer) { using namespace impl; DESERIALIZE(RelativeValue, width); DESERIALIZE(RelativeValue, height); DESERIALIZE(std::shared_ptr<IRelativeOffset>, offset); std::unique_ptr<ComplexBoxInUI> result(new ComplexBoxInUI(width, height)); result->setOffset(offset.get()); return std::move(result); } std::unique_ptr<impl::IObject> deserializeFixedBox(impl::Deserializer& deserializer) { using namespace impl; DESERIALIZE(BoundingBox, box); return std::unique_ptr<IObject>(new ComplexBoxInUI( pixels(box.width()), pixels(box.height()), BoxSize::Width, BoxSize::Height, pixels(box.center().x), pixels(box.center().y))); } std::unique_ptr<impl::IObject> deserializeOffsettedBox(impl::Deserializer& deserializer) { using namespace impl; DESERIALIZE(std::shared_ptr<IRelativeOffset>, offset); std::unique_ptr<ComplexBoxInUI> result(new ComplexBoxInUI(identic(), identic())); result->setOffset(offset.get()); return std::move(result); } std::unique_ptr<impl::IObject> deserializePixelBox(impl::Deserializer& deserializer) { using namespace impl; DESERIALIZE(float, width); DESERIALIZE(float, height); return std::unique_ptr<IObject>(new ComplexBoxInUI( pixels(width), pixels(height))); } std::unique_ptr<impl::IObject> deserializeComplexBox(impl::Deserializer& deserializer) { using namespace impl; DESERIALIZE(RelativeValue, width); DESERIALIZE(RelativeValue, height); DESERIALIZE(BoxSize::Type, widthSource); DESERIALIZE(BoxSize::Type, heightSource); DESERIALIZE(RelativeValue, horOffset); DESERIALIZE(RelativeValue, vertOffset); return std::unique_ptr<IObject>(new ComplexBoxInUI( width, height, widthSource, heightSource, horOffset, vertOffset)); } std::unique_ptr<impl::IObject> deserializeComplexBoxInUI(impl::Deserializer& deserializer) { using namespace impl; DESERIALIZE(std::shared_ptr<RelativeValueInUI>, width); DESERIALIZE(std::shared_ptr<RelativeValueInUI>, height); DESERIALIZE(BoxSize::Type, widthSource); DESERIALIZE(BoxSize::Type, heightSource); DESERIALIZE(std::shared_ptr<RelativeValueInUI>, horOffset); DESERIALIZE(std::shared_ptr<RelativeValueInUI>, vertOffset); std::unique_ptr<IObject> result; if (isZero(*horOffset) && isZero(*vertOffset)) { if (width->type() == height->type()) { if (widthSource == BoxSize::Min && heightSource == BoxSize::Min && isIdentic(*width)) result.reset(new SquareBox()); if (width->type() == RelType::Pixels) result.reset(new PixelBox(width->valueFloat(), height->valueFloat())); } } if (!result && width->type() == RelType::Pixels && height->type() == RelType::Pixels && horOffset->type() == RelType::Pixels && vertOffset->type() == RelType::Pixels) { BoundingBox bb(width->valueFloat(), height->valueFloat(), Vec2(horOffset->valueFloat(), vertOffset->valueFloat())); result.reset(new FixedBox(bb)); } if (!result && widthSource == BoxSize::Width && heightSource == BoxSize::Height) { std::shared_ptr<IRelativeOffset> offset; if (horOffset->type() == RelType::Pixels && vertOffset->type() == RelType::Pixels) { if (horOffset->value() != 0 || vertOffset->value() != 0) offset.reset(new FixedOffset( horOffset->valueFloat(), vertOffset->valueFloat())); } else { offset.reset(new AligningOffset( HorAlign::None, VertAlign::None, horOffset->toRelativeValue(), vertOffset->toRelativeValue())); } result.reset(new RelativeBox( width->toRelativeValue(), height->toRelativeValue(), offset)); } if (!result) result.reset(new ComplexBox( width->toRelativeValue(), height->toRelativeValue(), widthSource, heightSource, horOffset->toRelativeValue(), vertOffset->toRelativeValue())); return std::move(result); } REGISTER_CLASS(ComplexBoxInUI); } }
36.864516
99
0.681309
TheMrButcher
c79a7df374db07a684110a7de92e2ea78812528f
554
cpp
C++
bloc/Ground.cpp
Dracks977/FDI-COBJ-
349900d8d4c9b704e47aa9354b12cf95ce0e327d
[ "Apache-2.0" ]
null
null
null
bloc/Ground.cpp
Dracks977/FDI-COBJ-
349900d8d4c9b704e47aa9354b12cf95ce0e327d
[ "Apache-2.0" ]
null
null
null
bloc/Ground.cpp
Dracks977/FDI-COBJ-
349900d8d4c9b704e47aa9354b12cf95ce0e327d
[ "Apache-2.0" ]
null
null
null
// // Ground.cpp for cpp in /home/annibal/cpp/cp_2/anniba_c/bloc // // Made by ANNIBAL Celine // Login <anniba_c@etna-alternance.net> // // Started on Mon Feb 13 09:41:25 2017 ANNIBAL Celine // Last update Tue Feb 14 09:54:38 2017 ANNIBAL Celine // #include "Ground.hh" Ground::Ground(char x) : ABloc(x), ASteppable(x) { } Ground::~Ground() { } Ground::Ground(const Ground&x) : ABloc(x._char) ,ASteppable(x._char) { } Ground &Ground::operator=(const Ground&x) { _char = x._char; return(*this); } bool Ground::isStep() { return(true); }
16.294118
68
0.66426
Dracks977
c7a1da19b39165485552bd529a2039817930d4c5
16,051
cpp
C++
src/racer/pacejka/mrun.cpp
3dhater/Racer
d7fe4014b1efefe981528547649dc397da7fa780
[ "Unlicense" ]
null
null
null
src/racer/pacejka/mrun.cpp
3dhater/Racer
d7fe4014b1efefe981528547649dc397da7fa780
[ "Unlicense" ]
null
null
null
src/racer/pacejka/mrun.cpp
3dhater/Racer
d7fe4014b1efefe981528547649dc397da7fa780
[ "Unlicense" ]
1
2021-01-03T16:16:47.000Z
2021-01-03T16:16:47.000Z
/* * Pacejka Player - visually checking Pacejka curves * 02-04-01: Created! * 16-10-01: Picked up the project again for some better editing. * NOTES: * (C) MarketGraph/RvG */ #include "main.h" #pragma hdrstop #include <d3/global.h> #include <racer/pacejka.h> #include <qlib/debug.h> DEBUG_ENABLE #define DRW Q_BC #define CAR_FNAME "data/cars/devtest/car.ini" #define CONTROLS_FILE "controls.ini" #define DEBUG_INI "debug.ini" #define MAX_GRAPH 3 // (Graph::MAX_PARAM) // Pacejka vars RPacejka pacejka; // Modeler vars // Menu enum { MAX_IO=4 }; cstring ioName[MAX_IO]={ "Open car","Revert","Save*","---" }; QButton *butIO[MAX_IO]; enum { MAX_MODIFY=1 }; cstring modifyName[MAX_MODIFY]= { "Enter numerically" }; QButton *butModify[MAX_MODIFY]; QProp *pInput[4]; // Input parameters QRadio *rFocus[4]; // Focus on Fx/Fy/Mz or all QRadio *rCoeff[18]; // Coeff to modify QCheck *cZoom; // Zoom functions? QProp *pCoeff; extern cstring appTitle; extern QTitleBar *title; // Graphics DGlobal dglobal; DGeode *model; DBoundingBox *bbox; // Pacejka editing enum Focus { FOCUS_NONE, FOCUS_FX, FOCUS_FY, FOCUS_MZ }; Graph *graph[MAX_GRAPH]; int curFocus=FOCUS_NONE; int curCoeff; bool fZoom; rfloat *coeffPtr; // Address of current coefficient rfloat coeffScale; // Maximum editing range rfloat coeffBase; // Base value qstring carName; // Last know car name // Misc char buf[256]; // Errors QMessageHandler defQErr; // Proto static void DisplayCoeffSliderValue(float v); void SetDefaults(); void exitfunc() { int i; // Write settings info->SetString("last.car",carName); info->Write(); QDELETE(info); // Free resources for(i=0;i<MAX_IO;i++)delete butIO[i]; for(i=0;i<MAX_MODIFY;i++)delete butModify[i]; if(model)delete model; } /******** * MENUS * ********/ void SetZoom() // Based on 'fZoom', set the graph ranges { if(fZoom) { graph[Graph::PARAM_FX]->minX=-2; graph[Graph::PARAM_FX]->maxX=2; graph[Graph::PARAM_FY]->minX=-20; graph[Graph::PARAM_FY]->maxX=20; graph[Graph::PARAM_MZ]->minX=-20; graph[Graph::PARAM_MZ]->maxX=20; } else { graph[Graph::PARAM_FX]->minX=-10; graph[Graph::PARAM_FX]->maxX=10; graph[Graph::PARAM_FY]->minX=-180; graph[Graph::PARAM_FY]->maxX=180; graph[Graph::PARAM_MZ]->minX=-180; graph[Graph::PARAM_MZ]->maxX=180; } } void SetFocus() // Get graph to the front { int i; for(i=0;i<MAX_GRAPH;i++) graph[i]->flags&=~Graph::SHOW_COEFF; for(i=0;i<MAX_GRAPH;i++) { if(curFocus==FOCUS_NONE||curFocus==i+1) graph[i]->flags&=~Graph::NO_FOCUS; else graph[i]->flags|=Graph::NO_FOCUS; } if(curFocus!=FOCUS_NONE) graph[curFocus-1]->flags|=Graph::SHOW_COEFF; else graph[0]->flags|=Graph::SHOW_COEFF; } void SetCoeffNames() // Based on 'curFocus', set the coefficient names { int i; cstring s; cstring coeffNameFx[18]= { "b0","b1","b2","b3","b4","b5","b6","b7","b8","b9","b10",0,0,0,0,0,0,0 }; cstring coeffNameFy[18]= { "a0","a1","a2","a3","a4","a5","a6","a7","a8","a9","a10","a111","a112", "a12","a13",0,0,0 }; cstring coeffNameMz[18]= { "c0","c1","c2","c3","c4","c5","c6","c7","c8","c9","c10", "c11","c12","c13","c14","c15","c16","c17" }; for(i=0;i<18;i++) { switch(curFocus) { case FOCUS_NONE: case FOCUS_FX: s=coeffNameFx[i]; break; case FOCUS_FY: s=coeffNameFy[i]; break; case FOCUS_MZ: s=coeffNameMz[i]; break; } if(!s)s="---"; rCoeff[i]->SetText((char*)s); rCoeff[i]->Invalidate(); } } void SetEditCoeff() // Determine which coefficient to edit { Graph *g; float scale,*p,base; switch(curFocus) { case FOCUS_NONE: case FOCUS_FX: g=graph[0]; scale=10; base=0; switch(curCoeff) { case 0: p=&g->pacejka->b0; scale=2; base=0; break; // OK case 1: p=&g->pacejka->b1; scale=50; base=-scale/2; break; case 2: p=&g->pacejka->b2; scale=3000; break; // OK case 3: p=&g->pacejka->b3; scale=2; base=-scale/2; break; case 4: p=&g->pacejka->b4; scale=500; base=0; break; // OK case 5: p=&g->pacejka->b5; scale=2; base=-scale/2; break; case 6: p=&g->pacejka->b6; scale=2; base=-scale/2; break; case 7: p=&g->pacejka->b7; scale=2; base=-scale/2; break; case 8: p=&g->pacejka->b8; scale=2; base=-scale/2; break; case 9: p=&g->pacejka->b9; scale=2; base=-scale/2; break; case 10: p=&g->pacejka->b10; scale=2; base=-scale/2; break; } break; case FOCUS_FY: g=graph[1]; scale=10; base=0; switch(curCoeff) { case 0: p=&g->pacejka->a0; scale=2; base=0; break; case 1: p=&g->pacejka->a1; scale=100; base=-scale/2; break; case 2: p=&g->pacejka->a2; scale=3000; base=0; break; case 3: p=&g->pacejka->a3; scale=3000; base=0; break; case 4: p=&g->pacejka->a4; scale=50; base=0; break; case 5: p=&g->pacejka->a5; scale=2; base=-scale/2; break; case 6: p=&g->pacejka->a6; scale=5; base=-scale/2; break; case 7: p=&g->pacejka->a7; scale=5; base=-scale/2; break; case 8: p=&g->pacejka->a8; scale=2; base=-scale/2; break; case 9: p=&g->pacejka->a9; scale=2; base=-scale/2; break; case 10: p=&g->pacejka->a10; scale=2; base=-scale/2; break; case 111: p=&g->pacejka->a111; scale=30; base=-scale/2; break; case 112: p=&g->pacejka->a112; scale=2; base=-scale/2; break; case 12: p=&g->pacejka->a12; scale=20; base=-scale/2; break; case 13: p=&g->pacejka->a13; scale=100; base=0; break; } break; case FOCUS_MZ: g=graph[2]; scale=10; base=0; switch(curCoeff) { case 0: p=&g->pacejka->c0; scale=5; base=-scale/2; break; case 1: p=&g->pacejka->c1; scale=10; base=-scale/2; break; case 2: p=&g->pacejka->c2; scale=30; base=-scale/2; break; case 3: p=&g->pacejka->c3; scale=3; base=-scale/2; break; case 4: p=&g->pacejka->c4; scale=20; base=-scale/2; break; case 5: p=&g->pacejka->c5; scale=2; base=-scale/2; break; case 6: p=&g->pacejka->c6; scale=2; base=-scale/2; break; case 7: p=&g->pacejka->c7; scale=2; base=-scale/2; break; case 8: p=&g->pacejka->c8; scale=15; base=-scale/2; break; case 9: p=&g->pacejka->c9; scale=50; base=-scale/2; break; case 10: p=&g->pacejka->c10; scale=2; base=-scale/2; break; case 11: p=&g->pacejka->c11; scale=1; base=-scale/2; break; case 12: p=&g->pacejka->c12; scale=1; base=-scale/2; break; case 13: p=&g->pacejka->c13; scale=2; base=-scale/2; break; case 14: p=&g->pacejka->c14; scale=2; base=-scale/2; break; case 15: p=&g->pacejka->c15; scale=5; base=-scale/2; break; case 16: p=&g->pacejka->c16; scale=3; base=-scale/2; break; case 17: p=&g->pacejka->c17; scale=5; base=-scale/2; break; } break; default: p=0; break; } // Copy over coefficient value pointer and scaling coeffPtr=p; coeffScale=scale; coeffBase=base; if(coeffPtr) { // Reflect value in pCoeff (the slider) pCoeff->SetPosition(1000.0*((*coeffPtr-coeffBase)/coeffScale)); DisplayCoeffSliderValue(*coeffPtr); } } void SetupMenus() { QRect r; int i; // IO r.x=Q_BC->GetX()-2; r.y=Q_BC->GetHeight()+Q_BC->GetY()+10; r.wid=150; r.hgt=35; for(i=0;i<MAX_IO;i++) { butIO[i]=new QButton(QSHELL,&r,ioName[i]); r.x+=r.wid+10; } // Focus radio buttons r.x=Q_BC->GetX()+Q_BC->GetWidth()+10; r.y=Q_BC->GetY()-2; r.wid=150; r.hgt=16; cstring focusName[4]={ "No focus","Focus Fx","Focus Fy","Focus Mz" }; for(i=0;i<4;i++) { rFocus[i]=new QRadio(QSHELL,&r,(string)focusName[i],1000); r.y+=r.hgt+2; } rFocus[0]->SetState(TRUE); // Zoom? cZoom=new QCheck(QSHELL,&r,"Zoom"); r.y+=r.hgt+2; // Coefficient radio buttons for(i=0;i<18;i++) { rCoeff[i]=new QRadio(QSHELL,&r,"coeff",1001); r.y+=r.hgt+2; } rCoeff[0]->SetState(TRUE); SetCoeffNames(); // Coefficient slider pCoeff=new QProp(QSHELL,&r); pCoeff->SetRange(0,1000); pCoeff->SetDisplayed(5,10); pCoeff->SetJump(1); r.y+=r.hgt+2; // Modify //r.x=Q_BC->GetX()+Q_BC->GetWidth()+10; r.y=Q_BC->GetY()-2; r.wid=150; r.hgt=30; for(i=0;i<MAX_MODIFY;i++) { butModify[i]=new QButton(QSHELL,&r,modifyName[i]); r.y+=r.hgt+5; } // Input parameters cstring sInput[]= { "Load","Slip ratio","Slip angle","Camber" }; int rangeMin[]={ 0,-10*100,-180,-20*100 }; int rangeMax[]={ 5000,10*100,180,20*100 }; r.x=32-2; r.y=Q_BC->GetHeight()+Q_BC->GetY()+20+40; r.wid=Q_BC->GetWidth()+4; r.hgt=20; for(i=0;i<4;i++) { pInput[i]=new QProp(QSHELL,&r); // All controls get a range from 0..1000 which is later transformed //pInput[i]->SetRange(rangeMin[i],rangeMax[i]); pInput[i]->SetRange(0,1000); pInput[i]->SetDisplayed(3,10); //pInput[i]->SetPosition((rangeMin[i]+rangeMax[i])/2); pInput[i]->SetJump(1); // Value is shown implicitly //pInput[i]->EnableShowValue(); r.y+=r.hgt+10; } } /********* * ERRORS * *********/ void apperr(string s) { QRect r(100,100,500,150); QMessageBox("Error",s,0,&r); if(defQErr)defQErr(s); } /********* * MODIFY * *********/ /********* * EVENTS * *********/ static void MapXYtoCtl(int x,int y) // Convert X/Y coords to controller input { x-=DRW->GetWidth()/2; y-=DRW->GetHeight()/2; } static void SetLoad(float v) { int j; //qdbg("SetLoad(%f)\n",v); for(j=0;j<MAX_GRAPH;j++) { graph[j]->pacejka->SetNormalForce(v); } sprintf(buf,"Load %.fN",v); pInput[0]->SetText(buf); } static void SetSlipRatio(float v) { int j; //qdbg("Slip ratio %.2f\n",v); for(j=0;j<MAX_GRAPH;j++) { graph[j]->pacejka->SetSlipRatio(v); } sprintf(buf,"Slipratio %.2f",v); pInput[1]->SetText(buf); } static void SetSlipAngle(float v) { int j; //qdbg("Slip angle %.2f\n",v); for(j=0;j<MAX_GRAPH;j++) { graph[j]->pacejka->SetSlipAngle(v); } sprintf(buf,"Slipangle %.2f",v); pInput[2]->SetText(buf); } static void SetCamber(float v) { int j; //qdbg("Camber %.2f\n",v); for(j=0;j<MAX_GRAPH;j++) { graph[j]->pacejka->SetCamber(v/RR_RAD2DEG); } sprintf(buf,"Camber %.2f",v); pInput[3]->SetText(buf); } static void DisplayCoeffSliderValue(float v) // Show the coefficient value in the coeff slider { sprintf(buf,"%.4f",v); pCoeff->SetText(buf); pCoeff->Invalidate(); } static void SetTitle() // Display car name and application title in the titlebar { sprintf(buf,"%s - %s",appTitle,carName.cstr()); title->SetTitle(buf); title->Invalidate(); } static void SelectCar() { char buf[80]; int i; strcpy(buf,carName); if(!QDlgString("Select car","Enter the car name",buf,sizeof(buf))) return; // Remember car name carName=buf; SetTitle(); for(i=0;i<MAX_GRAPH;i++) graph[i]->LoadFrom(carName); SetDefaults(); } static void Revert() { int i; if(QMessageBox("Revert", "Are you sure you want to revert to the last saved Pacejka set?")!=IDOK) return; qdbg("Reverting\n"); for(i=0;i<MAX_GRAPH;i++) graph[i]->LoadFrom(carName); } static void NumericEntry() { char buf[80]; int i; if(!coeffPtr)return; sprintf(buf,"%f",*coeffPtr); if(!QDlgString("Enter numerical","Enter the value",buf,sizeof(buf))) return; *coeffPtr=atof(buf); // Get slider corrected DisplayCoeffSliderValue(*coeffPtr); SetEditCoeff(); } bool event(QEvent *e) { int i,j; if(e->type==QEvent::CLICK||e->type==QEvent::CHANGE) { for(i=0;i<4;i++) { if(e->win==pInput[i]) { int n; float v; n=e->n; pInput[i]->SetPosition(n); pInput[i]->Paint(); // Pass parameter to graph input if(i==0) { SetLoad(n*10); } else if(i==1) { SetSlipRatio((float)n/100.0-5.0f); } else if(i==2) { SetSlipAngle((float)n/5.0-100.0f); } else if(i==3) { SetCamber((float)n/50.0-10.0f); } } } for(i=0;i<4;i++) { if(e->win==rFocus[i]) { curFocus=i; curCoeff=0; SetCoeffNames(); SetFocus(); // Select the first coefficient SetEditCoeff(); for(i=0;i<18;i++)rCoeff[i]->SetState(FALSE); rCoeff[curCoeff]->SetState(TRUE); return TRUE; } } // Coefficient selection? for(i=0;i<18;i++) { if(e->win==rCoeff[i]) { curCoeff=i; // Determine effects of this selection SetEditCoeff(); } } // Zoom in? if(e->win==cZoom) { fZoom=cZoom->GetState(); SetZoom(); return TRUE; } // Coeff edit? if(e->win==pCoeff) { if(coeffPtr) { // Calculate slider position back to value rfloat v; v=pCoeff->GetPosition(); v=v/(1000.0/coeffScale)+coeffBase; *coeffPtr=v; DisplayCoeffSliderValue(v); } } for(i=0;i<MAX_IO;i++) { if(e->win==butIO[i]) { if(i==0) { SelectCar(); return TRUE; } else if(i==1) { Revert(); return TRUE; } } } for(i=0;i<MAX_MODIFY;i++) { if(e->win==butModify[i]) { if(i==0) { NumericEntry(); } } } } if(e->type==QEvent::MOTIONNOTIFY) { } else if(e->type==QEvent::KEYPRESS) { if(e->n==QK_ESC) app->Exit(0); } return FALSE; } /*********** * HANDLING * ***********/ void SetupViewport(int w,int h) { glViewport(0,0,w,h); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(65.0,(GLfloat)w/(GLfloat)h,1.0,1000.0); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); } QDraw *GGetDrawable() { return DRW; } QCanvas *GGetCV() { return DRW->GetCanvas(); } void GSwap() { DRW->Swap(); } void SetDefaults() { // Set default slider positions pInput[0]->SetPosition(250); SetLoad(2500); pInput[1]->SetPosition(500); SetSlipRatio(0); pInput[2]->SetPosition(500); SetSlipAngle(0); pInput[3]->SetPosition(500); SetCamber(0); cZoom->SetState(TRUE); fZoom=TRUE; SetZoom(); curFocus=FOCUS_NONE; SetFocus(); curCoeff=0; SetEditCoeff(); } void idlefunc() { QVector3 *v; int j; //qdbg("---\n"); #ifdef WIN32 // Task swapping grinds to a halt on Win32, duh! QNap(1); #endif // Don't refresh while window is disabled. This happens // when a dialog gets on top, and redrawing doesn't work // correctly on a lot of buggy drivers on Win98. if(!Q_BC->IsEnabled())return; GGetCV()->Select(); SetupViewport(DRW->GetWidth(),DRW->GetHeight()); //GGetCV()->SetFont(app->GetSystemFont()); GGetCV()->Set2D(); GGetCV()->Set3D(); GGetCV()->Set2D(); glClearColor(.8,.8,.8,0); glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT); for(j=0;j<MAX_GRAPH;j++) { #ifdef ND_DRAW_ALL // Don't draw if we're focusing one 1 graph if(curFocus!=FOCUS_NONE) { if(curFocus!=j+1) continue; } #endif graph[j]->CalculatePoints(); graph[j]->Paint(); } // Redraw focus graph for depth ordering if(curFocus!=FOCUS_NONE) graph[curFocus-1]->Paint(); GSwap(); } void Setup() { float v; int j; defQErr=QSetErrorHandler(apperr); // GUI SetupMenus(); // Get window up app->RunPoll(); app->SetIdleProc(idlefunc); app->SetExitProc(exitfunc); app->SetEventProc(event); // Graphics bbox=new DBoundingBox(); // Get last known car info->GetString("last.car",carName); qdbg("last car='%s'\n",carName.cstr()); SetTitle(); // Data for(j=0;j<MAX_GRAPH;j++) { graph[j]=new Graph(j); graph[j]->LoadFrom(carName); } SetZoom(); SetDefaults(); } void Run() { Setup(); app->Run(); }
22.767376
76
0.578406
3dhater
c7a81945aff87e861add89a6e3e024632b3ef2ef
301
cpp
C++
Assignments/capitabazi-solution.cpp
mobilal951/DSA-Bootcamp-Cpp
a6d073388998cad98447a0837dbc1fcf5bf8b4c2
[ "MIT" ]
1
2022-02-11T16:12:36.000Z
2022-02-11T16:12:36.000Z
Assignments/capitabazi-solution.cpp
mobilal951/DSA-Bootcamp-Cpp
a6d073388998cad98447a0837dbc1fcf5bf8b4c2
[ "MIT" ]
null
null
null
Assignments/capitabazi-solution.cpp
mobilal951/DSA-Bootcamp-Cpp
a6d073388998cad98447a0837dbc1fcf5bf8b4c2
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); string c; getline(cin, c); for(int i=0;i<c.size();i++){ if( c[i] >= 'a' && c[i] <= 'z') cout<< (char)(c[i]-32); else cout<<endl; } return 0; };
15.842105
58
0.498339
mobilal951
c7aba5c291c6435fba54eab0fff1e3e42d0a0ea9
1,403
cpp
C++
engine/collision/Collider.cpp
ohms83/GLRayTrace
4a77049f0a41585727d47711a90287592667caf6
[ "Unlicense" ]
null
null
null
engine/collision/Collider.cpp
ohms83/GLRayTrace
4a77049f0a41585727d47711a90287592667caf6
[ "Unlicense" ]
null
null
null
engine/collision/Collider.cpp
ohms83/GLRayTrace
4a77049f0a41585727d47711a90287592667caf6
[ "Unlicense" ]
null
null
null
#include "Collider.h" #include <iostream> Collider::Collider() { } Collider::~Collider() { } bool Collider::checkSphereCollision(const glm::vec3& center1, float radius1, const glm::vec3& center2, float radius2) { float distance = glm::length(center1 - center2); return distance <= radius1 + radius2; } bool Collider::checkRaySphereCollision(const glm::vec3& rayOrg, const glm::vec3& rayDir, const glm::vec3& sphereCenter, float radius) { // https://en.wikipedia.org/wiki/Line%E2%80%93sphere_intersection glm::vec3 oc = rayOrg - sphereCenter; glm::vec3 u = glm::normalize(rayDir); float b = glm::dot(oc, u); float c = glm::dot(oc, oc) - (radius * radius); float h = (b * b) - c; if (h < 0) { return false; } // TODO: Return collision data // if (h > 0) // { // h = glm::sqrt(h); // float d1 = -b + h; // float d2 = -b - h; // float rayLength = glm::length(rayDir); // glm::vec3 p1 = rayOrg + (u * d1); // glm::vec3 p2 = rayOrg + (u * d2); // float dot1 = glm::dot(u, p1); // float dot2 = glm::dot(u, p2); // std::cout << "d1:" << d1 << " d2:" << d2 << " rayLength:" << rayLength << "\n"; // std::cout << "dot1:" << dot1 << " dot2:" << dot2 << std::endl; // } return true; }
28.06
90
0.518888
ohms83
c7b236b83ef964747711ab185db70ec3c00c6c76
1,076
hpp
C++
dometer/metrics/handler/prometheus/metric_cache.hpp
maxenglander/dometer
baf9ed81f9d1e8bb67750ac278af5a9e0c4b89b9
[ "MIT" ]
null
null
null
dometer/metrics/handler/prometheus/metric_cache.hpp
maxenglander/dometer
baf9ed81f9d1e8bb67750ac278af5a9e0c4b89b9
[ "MIT" ]
null
null
null
dometer/metrics/handler/prometheus/metric_cache.hpp
maxenglander/dometer
baf9ed81f9d1e8bb67750ac278af5a9e0c4b89b9
[ "MIT" ]
null
null
null
#pragma once #include "dometer/util/lru_map.hpp" #include "prometheus/counter.h" #include "prometheus/x/types.hpp" namespace util = dometer::util; namespace dometer::metrics::handler::prometheus { class metric_cache : public util::lru_map<::prometheus::x::AnyMetricPtr, ::prometheus::x::FamilyNameAndTimeSeriesCount> { class time_series_changer { public: time_series_changer(metric_cache&, bool); template <class MetricPtr, class Meta> void operator()(MetricPtr, Meta); private: metric_cache& parent; bool increment; }; public: metric_cache(size_t); metric_cache(metric_cache&&); metric_cache(const metric_cache&); protected: bool should_evict() override; private: time_series_changer decrement_time_series; time_series_changer increment_time_series; const size_t max_time_series; size_t num_time_series; }; }
29.888889
114
0.605948
maxenglander
c7b2cceb971767f5ea1d92625e9dd859c5da3a1a
2,379
cpp
C++
src/prod/src/Naming/EseStoreTestHelper.cpp
AnthonyM/service-fabric
c396ea918714ea52eab9c94fd62e018cc2e09a68
[ "MIT" ]
2,542
2018-03-14T21:56:12.000Z
2019-05-06T01:18:20.000Z
src/prod/src/Naming/EseStoreTestHelper.cpp
AnthonyM/service-fabric
c396ea918714ea52eab9c94fd62e018cc2e09a68
[ "MIT" ]
994
2019-05-07T02:39:30.000Z
2022-03-31T13:23:04.000Z
src/prod/src/Naming/EseStoreTestHelper.cpp
AnthonyM/service-fabric
c396ea918714ea52eab9c94fd62e018cc2e09a68
[ "MIT" ]
300
2018-03-14T21:57:17.000Z
2019-05-06T20:07:00.000Z
// ------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ #include "stdafx.h" #include "EseStoreTestHelper.h" using namespace Common; using namespace std; namespace Naming { namespace TestHelper { Common::GlobalWString EseStoreTestHelper::EseDirectoryPrefix = Common::make_global<std::wstring>(L"EseStoreTestFiles_"); void EseStoreTestHelper::CreateDirectories(int count) { for (int ix = 0; ix < count; ++ix) { Directory::Create(GetEseDirectory(ix)); } } void EseStoreTestHelper::DeleteDirectories(int count) { bool succeeded = false; int attempts = 0; while (!succeeded && attempts < 10) { succeeded = true; ++attempts; for (int ix = 0; ix < count; ++ix) { wstring directory = GetEseDirectory(ix); if (Directory::Exists(directory)) { Trace.WriteInfo(Constants::TestSource, "Deleting directory '{0}'", directory); auto error = Directory::Delete(directory, true); if(!error.IsSuccess()) { Trace.WriteWarning(Constants::TestSource, "Couldn't delete directory '{0}' due to {1}", directory, error); succeeded = false; Sleep(2000); break; } } } } } wstring EseStoreTestHelper::GetEseDirectory(int index) { wstring directory; StringWriter writer(directory); writer.Write(EseDirectoryPrefix); writer.Write(index); //writer.Write(L"\\"); wstring rootPath; Environment::GetEnvironmentVariable( wstring(L"TEMP"), rootPath, Environment::GetExecutablePath()); return Path::Combine(rootPath, directory); } } }
32.148649
134
0.474569
AnthonyM
c7b2f9c342e8d15f003bf9c159ae58f65a2797f0
2,235
hpp
C++
include/ip_list.hpp
MDFreak/md_util
6f3f983f57b85199ab874b67a8b6b7a9dcf528c8
[ "MIT" ]
null
null
null
include/ip_list.hpp
MDFreak/md_util
6f3f983f57b85199ab874b67a8b6b7a9dcf528c8
[ "MIT" ]
null
null
null
include/ip_list.hpp
MDFreak/md_util
6f3f983f57b85199ab874b67a8b6b7a9dcf528c8
[ "MIT" ]
null
null
null
/************************************************************************* | Filename..............: ip_list.hpp * Project...............: part of standard utilities * Autor.................: Martin Dorfner (MD) * Date .................: 20.11.2020 *----------------------------------------------------------------------- * Function: * provide a list containing network login data *----------------------------------------------------------------------- * Dependecies: * md_defines.h (utility intern) * linked_list.hpp (utility intern) * ip_list.cpp implementation ************************************************************************ * Version| Date | Changes | Autor *----------------------------------------------------------------------- * 0.1.0 |20.11.20| import from former project | MD *-----------------------------------------------------------------------*/ /* Header Digital Input */ #ifndef _IPLIST_HPP_ #define _IPLIST_HPP_ #include <linked_list.hpp> #define LOGINTXT_MAX_LEN 30 #define MDIP_DEBUG CFG_DEBUG_NONE //#define MDIP_DEBUG CFG_DEBUG_STARTUP //#define MDIP_DEBUG CFG_DEBUG_ACTIONS //#define MDIP_DEBUG CFG_DEBUG_DETAILS class ip_cell : public md_cell { protected: uint32_t _locIP = 0; uint32_t _gwIP = 0; uint32_t _snIP = 0; char _ssid[LOGINTXT_MAX_LEN + 1] = ""; char _pw [LOGINTXT_MAX_LEN + 1] = ""; public: ip_cell() ; ~ip_cell() ; void init(uint32_t locIP, uint32_t gwIP, uint32_t snIP, const char* ssid, const char* pw); uint32_t locIP() { return(_locIP); } uint32_t gwIP() { return(_gwIP); } uint32_t snIP() { return(_snIP); } void getSSID(char* ssid, const uint8_t maxlen); void getPW(char* pw, const uint8_t maxlen); }; // class ip_list : public md_list { private: ip_cell* _pFirst; ip_cell* _pLast; public: ip_list(); ~ip_list(); void append(uint32_t locIP, uint32_t gwIP, uint32_t snIP, const char* ssid, const char* pw); ip_cell* find(const char* ssid); }; #endif
31.041667
100
0.462192
MDFreak
c7b3f5aebf2227960a03ca749fc3a03f51d6062a
6,844
cpp
C++
fortune_weighted_points/algorithm/fortune.cpp
matheusdallrosa/voronoi-diagram-construction
46c08f6aa24f5cff74978eb45014c511cb8a3abb
[ "MIT" ]
2
2018-05-22T14:22:50.000Z
2020-12-29T20:25:25.000Z
fortune_weighted_points/algorithm/fortune.cpp
matheusdallrosa/voronoi-diagram-construction
46c08f6aa24f5cff74978eb45014c511cb8a3abb
[ "MIT" ]
null
null
null
fortune_weighted_points/algorithm/fortune.cpp
matheusdallrosa/voronoi-diagram-construction
46c08f6aa24f5cff74978eb45014c511cb8a3abb
[ "MIT" ]
null
null
null
#include <stdio.h> #include <math.h> #include <algorithm> #include <vector> #include "common/floating_point.h" #include "fortune_weighted_points/geom/hyperbole.h" #include "fortune_weighted_points/geom/distance.h" #include "inter_detector.h" #include "inter_queue.h" #include "boundary.h" #include "status.h" #include "fortune.h" #include "debug.h" /* Cancela as interseccões entre a fronteira dada suas vizinhas.*/ void cancel_intersections(Boundary b,closest_boundaries& neighbors,Status& status,InterQueue& inter_queue){ inter_queue.rmv_inter(b,neighbors.first); inter_queue.rmv_inter(b,neighbors.second); } /* Caso uma fronteira a seja vertical, e um dos sites de uma fronteira b está contido em a, então b deve ser inserida novamente no status. */ void reinsert(Boundary a,Boundary b,double W,Status& status,InterQueue& inter_queue){ if(a.is_vertical() && (a.my_point(b.highest()) || a.my_point(b.lowest()))){ status.add_boundary(b); closest_boundaries neighbors = status.neighbors(b); inter_queue.add_inter(InterDetector::detect(neighbors.first,b,W)); inter_queue.add_inter(InterDetector::detect(neighbors.second,b,W)); } } void make_insertions(Boundary a,double W,closest_boundaries& neighbors,Status& status,InterQueue& inter_queue){ inter_queue.add_inter(InterDetector::detect(neighbors.first,a,W)); inter_queue.add_inter(InterDetector::detect(neighbors.second,a,W)); } void new_edge(std::vector<Edge> &edges,Boundary &b){ if(b.is_vertical()) edges.push_back(Edge(b.get_id(),b.get_vertical_line(),b.highest(),b.lowest())); else edges.push_back(Edge(b.get_id(),b.get_hyperbole(),b.highest(),b.lowest())); } bool site_inter_comp(WSite s,Inter i){ double dy = s.y+s.get_weight()-i.mapp_y; if(cmpf(dy,0) == -1) return true; int y_sign = cmpf(dy*dy,i.mapp_dist_squared); if(y_sign) return (y_sign == -1); /* Quando um site e um vértice estão no ponto do plano, considero que o vértice vem antes. */ return cmpf(s.x,i.x) <= 0; } void fortune(std::vector<WSite> & wsites,double W, std::vector<Edge> &edges,std::vector<Vertice> &vertices){ if((int)wsites.size() == 1) return; //o diagrama é o plano inteiro. sort(wsites.begin(),wsites.end(),StarWSiteComp()); std::vector<WSite>::iterator site = wsites.begin(); Status status; InterQueue inter_queue; int bis_id = 0; WSite s0 = *(site++), s1 = *(site++); Point m_s1 = Point(s1.x,s1.y+s1.get_weight()); Boundary B01_minus = Boundary(bis_id,s0,s1,m_s1,MINUS); new_edge(edges,B01_minus); status.add_boundary(B01_minus); if(!B01_minus.is_vertical()) status.add_boundary(Boundary(bis_id,s0,s1,m_s1,PLUS)); if(DEBUG) { status.print(); printf("\n"); } while(site != wsites.end() || !inter_queue.is_empty()){ bis_id++; /*evento de site*/ if(site != wsites.end() && (inter_queue.is_empty() || site_inter_comp(*site,inter_queue.first()))){ WSite p = *site; /*mapeando o site p para sua fronteira(mapeada).*/ Point mp = Point(p.x,p.y+p.get_weight()); if(DEBUG) { printf("Evento do site:\n"); p.print(); } /* encontrar um pair de fronteiras tal que, a primeira fronteira do pair é a primeira fronteira à esquerda de p, e a segunda fronteira do pair é a primeira fronteira à direita de p. */ closest_boundaries closest_pair = status.closest_bound(mp); Boundary left_boundary = closest_pair.first; Boundary right_boundary = closest_pair.second; if(DEBUG) { printf("Fronteira da esquerda:\n"); left_boundary.print(); printf("\nFronteira da direita:\n"); right_boundary.print(); } bool on_right_bisector = false; /*encontrar a região q que contém mp.*/ WSite q = right_boundary.find_region(mp,on_right_bisector); /*criacão da parte Cpq- do bissetor Bpq*/ Boundary Cpq_minus = Boundary(bis_id,p,q,mp,MINUS), Cpq_plus; new_edge(edges,Cpq_minus); status.add_boundary(Cpq_minus); closest_boundaries neighbors = status.neighbors(Cpq_minus); make_insertions(Cpq_minus,W,neighbors,status,inter_queue); /* A parte Cpq+ só vai ser criada se Cpq não for uma reta vertical, e se p não está contido em right_boundary caso right_boundary seja vertical. */ if(!Cpq_minus.is_vertical() && !on_right_bisector){ Cpq_plus = Boundary(bis_id,p,q,mp,PLUS); status.add_boundary(Cpq_plus); make_insertions(Cpq_plus,W,neighbors,status,inter_queue); } /*verificando se existe interseccão entre as duas fronteiras.*/ InterCheck check = inter_queue.check(right_boundary,left_boundary); if(check.exists){ StarBoundaryComp side_check; /*caso as duas fronteiras estejam nos extremos do status, talvez não seja necessário cancelar a interseccão.*/ if(side_check.comp(mp,right_boundary) == side_check.comp(mp,left_boundary)){ /*Checar se parte do círculo com centro em p está contido no círculo com centro em check.inter*/ double k = check.inter.mapp_weight-W; double dist_p_inter = Distance::sq_two_points(p,check.inter); double k_prime = dist_p_inter-check.inter.mapp_dist_squared+k*k; if(cmpf(dist_p_inter,check.inter.mapp_dist_squared) == 1 || cmpf(k_prime,0) == 1 || cmpf(k_prime*k_prime,4.*k*k*check.inter.mapp_dist_squared) == -1){ inter_queue.rmv_inter(check.inter); } } else inter_queue.rmv_inter(check.inter); } site++; } /*evento de vértice.*/ else{ Inter inter = inter_queue.next(); if(DEBUG){ printf("Evento do Vértice:\n"); inter.print(); } Boundary Cqr = inter.get_Cqr(), Crs = inter.get_Crs(); inter_queue.rmv_inter(Cqr,Crs); Boundary Cqs = Boundary(bis_id,inter.tangent[1],inter.tangent[2],inter); new_edge(edges,Cqs); vertices.push_back(Vertice(vertices.size(),std::vector<int>({Cqr.get_id(),Crs.get_id(),Cqs.get_id()}),inter.x,inter.y)); closest_boundaries Cqr_neigh = status.neighbors(Cqr); closest_boundaries Crs_neigh = status.neighbors(Crs); cancel_intersections(Cqr,Cqr_neigh,status,inter_queue); cancel_intersections(Cqr,Crs_neigh,status,inter_queue); status.rmv_boundary(Cqr); cancel_intersections(Crs,Cqr_neigh,status,inter_queue); cancel_intersections(Crs,Crs_neigh,status,inter_queue); status.rmv_boundary(Crs); reinsert(Cqr,Crs,W,status,inter_queue); reinsert(Crs,Cqr,W,status,inter_queue); status.add_boundary(Cqs); closest_boundaries neighbors = status.neighbors(Cqs); make_insertions(Cqs,W,neighbors,status,inter_queue); } if(DEBUG) inter_queue.print(); if(DEBUG) status.print(); } }
38.666667
126
0.68235
matheusdallrosa
c7b4ae8d784c9502673c855f4b2675a7bb7b8fa4
318
cpp
C++
src/logging/abstract_logger.cpp
AndrSar/scgicxx
7ef793fd245ea8b629eb966fc1f3466c29c914e7
[ "BSL-1.0" ]
null
null
null
src/logging/abstract_logger.cpp
AndrSar/scgicxx
7ef793fd245ea8b629eb966fc1f3466c29c914e7
[ "BSL-1.0" ]
null
null
null
src/logging/abstract_logger.cpp
AndrSar/scgicxx
7ef793fd245ea8b629eb966fc1f3466c29c914e7
[ "BSL-1.0" ]
null
null
null
#include "../include/logging/abstract_logger.hpp" namespace scgicxx { namespace logging { abstract_logger::abstract_logger(level_enum level) : level(level) { } level_enum abstract_logger::get_level() const { return level; } void abstract_logger::set_level(level_enum level) { this->level = level; } } }
12.230769
65
0.732704
AndrSar
c7c10c8eb480e3d3656b4b9480a53d2868293798
1,072
hpp
C++
src/core/material.hpp
AndreJFBico/RadRts_BGFX
c8d37d95e68e2fc2b3db09a94f2817533e4aa700
[ "MIT" ]
null
null
null
src/core/material.hpp
AndreJFBico/RadRts_BGFX
c8d37d95e68e2fc2b3db09a94f2817533e4aa700
[ "MIT" ]
null
null
null
src/core/material.hpp
AndreJFBico/RadRts_BGFX
c8d37d95e68e2fc2b3db09a94f2817533e4aa700
[ "MIT" ]
null
null
null
#pragma once #include <functional> #include <variant> #include <bgfx/bgfx.h> #include "materials/wireframe.hpp" #include "materials/texture.hpp" // Base where all the material types rely upon struct Material { using MaterialCustomContent = std::variant<wireframe::Wireframe, Texture>; using MaterialFunctor = std::function<void(Material& mat, MaterialCustomContent& content)>; MaterialCustomContent content = wireframe::Wireframe(); bgfx::ProgramHandle program = { 0 }; uint64_t state = 0; MaterialFunctor customInit = [](Material& mat, MaterialCustomContent& content) {}; MaterialFunctor customUpdate = [](Material& mat, MaterialCustomContent& content) {}; MaterialFunctor customDestroy = [](Material& mat, MaterialCustomContent& content) {}; Material() {} Material( MaterialCustomContent& customContent , MaterialFunctor& customInit , MaterialFunctor& customUpdate , MaterialFunctor& customDestroy); }; void init(Material& mat); void update(Material& mat); void destroy(Material& mat);
30.628571
95
0.718284
AndreJFBico
c7c44a6abbdcbf6bb15047f5fe72ad6b7b8a165e
2,154
cpp
C++
source/directinput/MouseState.cpp
HeavenWu/slimdx
e014bb34b89bbf694d01c8f6d6b6dfa3cba58aac
[ "MIT" ]
85
2015-04-06T05:37:10.000Z
2022-03-22T19:53:03.000Z
source/directinput/MouseState.cpp
HeavenWu/slimdx
e014bb34b89bbf694d01c8f6d6b6dfa3cba58aac
[ "MIT" ]
10
2016-03-17T11:18:24.000Z
2021-05-11T09:21:43.000Z
source/directinput/MouseState.cpp
HeavenWu/slimdx
e014bb34b89bbf694d01c8f6d6b6dfa3cba58aac
[ "MIT" ]
45
2015-09-14T03:54:01.000Z
2022-03-22T19:53:09.000Z
#include "stdafx.h" /* * Copyright (c) 2007-2012 SlimDX Group * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include <windows.h> #include <dinput.h> #include "MouseState.h" using namespace System; namespace SlimDX { namespace DirectInput { MouseState::MouseState() { pressedButtons = gcnew array<bool>( 8 ); releasedButtons = gcnew array<bool>( 8 ); } MouseState::MouseState( int x, int y, int z ) { X = x; Y = y; Z = z; pressedButtons = gcnew array<bool>( 8 ); releasedButtons = gcnew array<bool>( 8 ); } MouseState::MouseState( const DIMOUSESTATE2 &state ) { pressedButtons = gcnew array<bool>( 8 ); releasedButtons = gcnew array<bool>( 8 ); AssignState( state ); } void MouseState::AssignState( const DIMOUSESTATE2 &state ) { X = state.lX; Y = state.lY; Z = state.lZ; for( int i = 0; i < 8; i++ ) { if( ( state.rgbButtons[i] & 0x80 ) != 0 ) { pressedButtons[i] = true; releasedButtons[i] = false; } else { pressedButtons[i] = false; releasedButtons[i] = true; } } } } }
27.615385
80
0.675487
HeavenWu
c7c8e1eb09250e5bbe96bb11c05c1f31774a8719
2,299
hpp
C++
NightEngine2/src/Core/Message/MessageObjectList.hpp
rittikornt/NightEngine2
14004b48d1708736373010a3fe47d05d876e0baa
[ "MIT" ]
2
2020-03-09T06:24:46.000Z
2022-02-04T23:09:23.000Z
NightEngine2/src/Core/Message/MessageObjectList.hpp
rittikornt/NightEngine2
14004b48d1708736373010a3fe47d05d876e0baa
[ "MIT" ]
null
null
null
NightEngine2/src/Core/Message/MessageObjectList.hpp
rittikornt/NightEngine2
14004b48d1708736373010a3fe47d05d876e0baa
[ "MIT" ]
2
2020-09-07T03:04:36.000Z
2022-02-04T23:09:24.000Z
/*! @file MessageObjectList.hpp @author Rittikorn Tangtrongchit @brief Contain the Interface of MessageObjectList */ #pragma once #include <sstream> #include <glm/vec3.hpp> #include "Core/Message/MessageObject.hpp" #include "Core/Message/MessageTypeEnum.hpp" //Enum List namespace NightEngine { struct TestMessage : public MessageObject { //Constructor TestMessage(bool toggle, int incrementAmount) : MessageObject(MessageType::MSG_TEST), m_toggle(toggle) , m_incrementAmount(incrementAmount) {} //Override Double dispatch MSG_GENERATE_METHOD_DECL() bool m_toggle = false; int m_incrementAmount = 1; }; struct PlayerUpdateMessage : public MessageObject { enum class UpdateType : unsigned char { HEALTHCHANGED, MPCHANGED }; //Constructor PlayerUpdateMessage(UpdateType type, unsigned amount) :MessageObject(MessageType::MSG_PLAYERUPDATE), m_updateType(type), m_updateAmount(amount) {} //Override Double dispatch MSG_GENERATE_METHOD_DECL() UpdateType m_updateType; unsigned m_updateAmount; }; struct GameShouldCloseMessage : public MessageObject { //Constructor GameShouldCloseMessage(bool shouldClose) : MessageObject(MessageType::MSG_GAMESHOULDQUIT), m_shouldClose(shouldClose) {} //Override Double dispatch MSG_GENERATE_METHOD_DECL() bool m_shouldClose; }; //! @brief For sending message to DevConsole struct LogMessage : public MessageObject { //Constructor LogMessage(std::string& str) :MessageObject(MessageType::MSG_LOGMESSAGE), m_string(str) {} //Override Double dispatch MSG_GENERATE_METHOD_DECL() std::string m_string; }; //! @brief For sending message to DevConsole struct TransformMessage : public MessageObject { enum class TransformType : unsigned char { TRANSLATE, ROTATE, SCALE }; //Constructor TransformMessage(const std::string& targetName ,TransformType type, glm::vec3 amount) :MessageObject(MessageType::MSG_TRANSFORMMESSAGE) , m_targetName(targetName),m_type(type), m_amount(amount) {} //Override Double dispatch MSG_GENERATE_METHOD_DECL() std::string m_targetName; TransformType m_type; glm::vec3 m_amount; }; } // Message
22.320388
95
0.717268
rittikornt
c7cf2b1dd64353d0c655ce2615b7facda498a300
7,604
cpp
C++
GraphHPC/mst_reference_mpi.cpp
zaic/mst
455134f212c597da85aaa5fac1ff6ce87982b04d
[ "MIT" ]
null
null
null
GraphHPC/mst_reference_mpi.cpp
zaic/mst
455134f212c597da85aaa5fac1ff6ce87982b04d
[ "MIT" ]
null
null
null
GraphHPC/mst_reference_mpi.cpp
zaic/mst
455134f212c597da85aaa5fac1ff6ce87982b04d
[ "MIT" ]
null
null
null
#include <vector> #include <mpi.h> #include <float.h> #include <stdlib.h> #include <assert.h> #include "defs.h" #define UINT32_MAX (0xffffffff) using namespace std; /* returns global number of edge */ edge_id_t edge_to_global(edge_id_t edge, graph_t *G) { int rank = G->rank; int size = G->nproc; edge_id_t g_edge = 0; for(int i = 0; i < rank && i < size; ++i) { g_edge += G->num_edges_of_any_process[i]; } return (g_edge + edge); } /* Convert MST implementation output to GraphHPC-2015 forest_t data type. forest_t will be used in validation * NOTE: isolated vertex is also tree, such tree must be represented as separate element of trees_mst vector with zero-length edges list * FIXME: If you change MST output data structure, you must change this function */ typedef vector<vector<edge_id_t > > result_t; result_t trees; extern "C" void convert_to_output(graph_t *G, void *result, forest_t *trees_output) { result_t &trees_mst = *reinterpret_cast<result_t*>(result); int size, rank; int tree_size = 0; int MPI_TAG = 99; edge_id_t edge_buf; MPI_Status status; MPI_Comm_size(MPI_COMM_WORLD,&size); MPI_Comm_rank(MPI_COMM_WORLD,&rank); for(int tree_count = 0; (unsigned int)tree_count < trees_mst.size(); ++tree_count) //trees loop for(int proc_count = 1; proc_count < size; ++proc_count) //processes loop if(rank == proc_count || rank == 0) { MPI_TAG = tree_count; //send to 0-process number of edges in tree if (rank == proc_count) { tree_size = trees_mst[tree_count].size(); MPI_Send(&tree_size, 1, MPI_INT, 0, MPI_TAG, MPI_COMM_WORLD); } // 0-process recieve tree_size from any process else { MPI_Recv(&tree_size, 1, MPI_INT, proc_count, MPI_TAG, MPI_COMM_WORLD, &status); } // 0-process recieve edge_id from any process for(int edge_count = 0; edge_count < tree_size; ++edge_count) //edges loop { MPI_TAG = edge_count; if(rank == proc_count) { MPI_Send(&(trees_mst[tree_count])[edge_count], 1, MPI_UINT64_T, 0, MPI_TAG, MPI_COMM_WORLD); } else { MPI_Recv(&edge_buf, 1, MPI_UINT64_T, proc_count, MPI_TAG, MPI_COMM_WORLD, &status); trees_mst[tree_count].push_back(edge_buf); } } } if (rank == 0) { trees_output->p_edge_list = (edge_id_t *)malloc(trees_mst.size()*2 * sizeof(edge_id_t)); edge_id_t number_of_edges = 0; for (vertex_id_t i = 0; i < trees_mst.size(); i++) number_of_edges += trees_mst[i].size(); trees_output->edge_id = (edge_id_t *)malloc(number_of_edges * sizeof(edge_id_t)); trees_output->p_edge_list[0] = 0; trees_output->p_edge_list[1] = trees_mst[0].size(); for (vertex_id_t i = 1; i < trees_mst.size(); i++) { trees_output->p_edge_list[2*i] = trees_output->p_edge_list[2*i-1]; trees_output->p_edge_list[2*i +1] = trees_output->p_edge_list[2*i-1] + trees_mst[i].size(); } int k = 0; for (vertex_id_t i = 0; i < trees_mst.size(); i++) { for (edge_id_t j = 0; j < trees_mst[i].size(); j++) { trees_output->edge_id[k] = trees_mst[i][j]; k++; } } trees_output->numTrees = trees_mst.size(); trees_output->numEdges = number_of_edges; } } extern "C" void init_mst(graph_t *G) { G->num_edges_of_any_process = (edge_id_t*) malloc (G->nproc * sizeof(edge_id_t)); edge_id_t * edges_to_send = (edge_id_t*) malloc (G->nproc * sizeof(edge_id_t)); assert(G->num_edges_of_any_process); for(int i = 0; i < G->nproc; ++i) edges_to_send[i] = G->local_m; MPI_Alltoall(edges_to_send, 1, MPI_UINT64_T, G->num_edges_of_any_process, 1, MPI_UINT64_T, MPI_COMM_WORLD); if(edges_to_send) free(edges_to_send); } /* MPI MST reference implementation. Prim's algorithm */ extern "C" void* MST(graph_t *G) { trees.clear(); int rank = G->rank, size = G->nproc; vertex_id_t TotVertices = G->n; // marked edges are those that lead to vertices already in the tree vector<uint8_t> marked_edges(G->local_m, 0); // marked vertices are local edges already in the tree vector<uint8_t> marked_vertices(G->local_n, 0); // start with first vertex on first node vertex_id_t root = 0; do { // start a new tree trees.push_back(vector<edge_id_t>()); // local queue of vertices vector<vertex_id_t> queue; // keep track of last added edge to mark edges vertex_id_t last_vertex = root; while (true) { if (VERTEX_OWNER(last_vertex, TotVertices, size) == G->rank) { // last vertex is ours - put it in the queue and mark vertex_id_t last_local_vertex = VERTEX_LOCAL(last_vertex, TotVertices, size, rank); marked_vertices[last_local_vertex] = 1; queue.push_back(last_local_vertex); } // mark edges that lead to the last added vertex for (edge_id_t j = 0; j < G->local_m; j++) { if (G->endV[j] == last_vertex) { marked_edges[j] = 1; } } // determine our best candidate edge struct { double weight; int rank; edge_id_t edge; } best; best.weight = DBL_MAX; for (vertex_id_t i = 0; i < queue.size(); i++) { for (edge_id_t j = G->rowsIndices[queue[i]]; j < G->rowsIndices[queue[i] + 1]; j++) { // skip marked edges if (!marked_edges[j]) { // check if this edge is better than what we have up to now if (best.weight == DBL_MAX || G->weights[j] < best.weight) { best.weight = G->weights[j]; best.edge = j; } } } } // reduce and determine global best edge best.rank = G->rank; MPI_Allreduce(MPI_IN_PLACE, &best, 1, MPI_DOUBLE_INT, MPI_MINLOC, MPI_COMM_WORLD); if (best.weight == DBL_MAX) { // no suitable edge found, finish this tree break; } else { if (best.rank == G->rank) { // we have the best edge trees.back().push_back(edge_to_global(best.edge,G)); last_vertex = G->endV[best.edge]; } MPI_Bcast(&last_vertex, 1, MPI_UINT32_T, best.rank, MPI_COMM_WORLD); } } // find root of a new tree root = UINT32_MAX; for (vertex_id_t i = 0; i < G->local_n; i++) { if (!marked_vertices[i]) { root = VERTEX_TO_GLOBAL(i, TotVertices, size, rank); break; } } MPI_Allreduce(MPI_IN_PLACE, &root, 1, MPI_UINT32_T, MPI_MIN, MPI_COMM_WORLD); } while (root!=UINT32_MAX); return &trees; } extern "C" void finalize_mst(graph_t* G) { if (G->num_edges_of_any_process) free(G->num_edges_of_any_process); }
38.795918
136
0.555234
zaic
c7d20952e1aa470763b449627804d6af76cf7fbd
1,716
cpp
C++
include/types/has_interface.cpp
nathanmullenax83/rhizome
e7410341fdc4d38ab5aaecc55c94d3ac6efd51da
[ "MIT" ]
1
2020-07-11T14:53:38.000Z
2020-07-11T14:53:38.000Z
include/types/has_interface.cpp
nathanmullenax83/rhizome
e7410341fdc4d38ab5aaecc55c94d3ac6efd51da
[ "MIT" ]
1
2020-07-04T16:45:49.000Z
2020-07-04T16:45:49.000Z
include/types/has_interface.cpp
nathanmullenax83/rhizome
e7410341fdc4d38ab5aaecc55c94d3ac6efd51da
[ "MIT" ]
null
null
null
#include "has_interface.hpp" namespace rhizome { namespace types { HasInterface::HasInterface( string const &name ) : interface_name(name) { } bool HasInterface::contains( Thing *t ) const { return t->has_interface(interface_name); } // Thing impl string HasInterface::rhizome_type() const { return "tc.HasInterface"; } void HasInterface::serialize_to( size_t level, std::ostream &out ) const { (void)level; out << " has " << interface_name; } bool HasInterface::has_interface( string const &name ) { return name==rhizome_type()||name=="tc"||name=="Thing"; } Thing * HasInterface::clone() const { return new HasInterface(interface_name); } string unfamiliar_method( string const &name, string const &rt, Thing *arg) { stringstream err; err << "Attempted to invoke " << name << " on " << rt << " "; err << "but " << rt << " is unfamiliar with that method."; err << " The argument was:\n"; if( arg != NULL ){ arg->serialize_to(1,err); } else { err << "()"; } return err.str(); } Thing * HasInterface::invoke( Thing *context, string const &method, Thing *arg ) { (void)context; if( method=="contains" || method=="has") { return new rhizome::types::Bool(contains(arg)); } throw runtime_error(unfamiliar_method(method,rhizome_type(),arg)); } } }
28.6
85
0.501748
nathanmullenax83
c7d37d2de0058f78f0b09da1d2a593349c99160a
7,889
cpp
C++
mp/src/game/server/hl1/hl1_monstermaker.cpp
tyabus/source-sdk-2013-hl1dm
b500739c541232bceea77d5d10da085c05f34633
[ "Unlicense" ]
4
2021-10-03T05:16:55.000Z
2021-12-28T16:49:27.000Z
tf2_src/game/server/hl1/hl1_monstermaker.cpp
Counter2828/TeamFortress2
1b81dded673d49adebf4d0958e52236ecc28a956
[ "MIT" ]
null
null
null
tf2_src/game/server/hl1/hl1_monstermaker.cpp
Counter2828/TeamFortress2
1b81dded673d49adebf4d0958e52236ecc28a956
[ "MIT" ]
3
2022-02-02T18:09:58.000Z
2022-03-06T18:54:39.000Z
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: An entity that creates NPCs in the game. // //=============================================================================// #include "cbase.h" #include "entityapi.h" #include "entityoutput.h" #include "ai_basenpc.h" #include "hl1_monstermaker.h" #include "mapentities.h" BEGIN_DATADESC( CNPCMaker ) DEFINE_KEYFIELD( m_iMaxNumNPCs, FIELD_INTEGER, "monstercount" ), DEFINE_KEYFIELD( m_iMaxLiveChildren, FIELD_INTEGER, "MaxLiveChildren" ), DEFINE_KEYFIELD( m_flSpawnFrequency, FIELD_FLOAT, "delay" ), DEFINE_KEYFIELD( m_bDisabled, FIELD_BOOLEAN, "StartDisabled" ), DEFINE_KEYFIELD( m_iszNPCClassname, FIELD_STRING, "monstertype" ), DEFINE_FIELD( m_cLiveChildren, FIELD_INTEGER ), DEFINE_FIELD( m_flGround, FIELD_FLOAT ), // Inputs DEFINE_INPUTFUNC( FIELD_VOID, "Spawn", InputSpawnNPC ), DEFINE_INPUTFUNC( FIELD_VOID, "Enable", InputEnable ), DEFINE_INPUTFUNC( FIELD_VOID, "Disable", InputDisable ), DEFINE_INPUTFUNC( FIELD_VOID, "Toggle", InputToggle ), // Outputs DEFINE_OUTPUT( m_OnSpawnNPC, "OnSpawnNPC" ), // Function Pointers DEFINE_THINKFUNC( MakerThink ), END_DATADESC() LINK_ENTITY_TO_CLASS( monstermaker, CNPCMaker ); //----------------------------------------------------------------------------- // Purpose: Spawn //----------------------------------------------------------------------------- void CNPCMaker::Spawn( void ) { SetSolid( SOLID_NONE ); m_cLiveChildren = 0; Precache(); // If I can make an infinite number of NPC, force them to fade if ( m_spawnflags & SF_NPCMAKER_INF_CHILD ) { m_spawnflags |= SF_NPCMAKER_FADE; } //Start on? if ( m_bDisabled == false ) { SetThink ( &CNPCMaker::MakerThink ); SetNextThink( gpGlobals->curtime + m_flSpawnFrequency ); } else { //wait to be activated. SetThink ( &CBaseEntity::SUB_DoNothing ); } m_flGround = 0; } //----------------------------------------------------------------------------- // Purpose: Returns whether or not it is OK to make an NPC at this instant. //----------------------------------------------------------------------------- bool CNPCMaker::CanMakeNPC( void ) { if ( m_iMaxLiveChildren > 0 && m_cLiveChildren >= m_iMaxLiveChildren ) {// not allowed to make a new one yet. Too many live ones out right now. return false; } if ( !m_flGround ) { // set altitude. Now that I'm activated, any breakables, etc should be out from under me. trace_t tr; UTIL_TraceLine ( GetAbsOrigin(), GetAbsOrigin() - Vector ( 0, 0, 2048 ), MASK_NPCSOLID_BRUSHONLY, this, COLLISION_GROUP_NONE, &tr ); m_flGround = tr.endpos.z; } Vector mins = GetAbsOrigin() - Vector( 34, 34, 0 ); Vector maxs = GetAbsOrigin() + Vector( 34, 34, 0 ); maxs.z = GetAbsOrigin().z; //Only adjust for the ground if we want it if ( ( m_spawnflags & SF_NPCMAKER_NO_DROP ) == false ) { mins.z = m_flGround; } CBaseEntity *pList[128]; int count = UTIL_EntitiesInBox( pList, 128, mins, maxs, FL_CLIENT|FL_NPC ); if ( count ) { //Iterate through the list and check the results for ( int i = 0; i < count; i++ ) { //Don't build on top of another entity if ( pList[i] == NULL ) continue; //If one of the entities is solid, then we can't spawn now if ( ( pList[i]->GetSolidFlags() & FSOLID_NOT_SOLID ) == false ) return false; } } return true; } //----------------------------------------------------------------------------- // Purpose: If this had a finite number of children, return true if they've all // been created. //----------------------------------------------------------------------------- bool CNPCMaker::IsDepleted() { if ( (m_spawnflags & SF_NPCMAKER_INF_CHILD) || m_iMaxNumNPCs > 0 ) return false; return true; } //----------------------------------------------------------------------------- // Purpose: Toggle the spawner's state //----------------------------------------------------------------------------- void CNPCMaker::Toggle( void ) { if ( m_bDisabled ) { Enable(); } else { Disable(); } } //----------------------------------------------------------------------------- // Purpose: Start the spawner //----------------------------------------------------------------------------- void CNPCMaker::Enable( void ) { // can't be enabled once depleted if ( IsDepleted() ) return; m_bDisabled = false; SetThink ( &CNPCMaker::MakerThink ); SetNextThink( gpGlobals->curtime ); } //----------------------------------------------------------------------------- // Purpose: Stop the spawner //----------------------------------------------------------------------------- void CNPCMaker::Disable( void ) { m_bDisabled = true; SetThink ( NULL ); } //----------------------------------------------------------------------------- // Purpose: Input handler that spawns an NPC. //----------------------------------------------------------------------------- void CNPCMaker::InputSpawnNPC( inputdata_t &inputdata ) { MakeNPC(); } //----------------------------------------------------------------------------- // Purpose: Input hander that starts the spawner //----------------------------------------------------------------------------- void CNPCMaker::InputEnable( inputdata_t &inputdata ) { Enable(); } //----------------------------------------------------------------------------- // Purpose: Input hander that stops the spawner //----------------------------------------------------------------------------- void CNPCMaker::InputDisable( inputdata_t &inputdata ) { Disable(); } //----------------------------------------------------------------------------- // Purpose: Input hander that toggles the spawner //----------------------------------------------------------------------------- void CNPCMaker::InputToggle( inputdata_t &inputdata ) { Toggle(); } //----------------------------------------------------------------------------- // Purpose: Precache the target NPC //----------------------------------------------------------------------------- void CNPCMaker::Precache( void ) { BaseClass::Precache(); UTIL_PrecacheOther( STRING( m_iszNPCClassname ) ); } //----------------------------------------------------------------------------- // Purpose: Creates the NPC. //----------------------------------------------------------------------------- void CNPCMaker::MakeNPC( void ) { if (!CanMakeNPC()) { return; } CBaseEntity *pent = (CBaseEntity*)CreateEntityByName( STRING(m_iszNPCClassname) ); if ( !pent ) { Warning("NULL Ent in NPCMaker!\n" ); return; } m_OnSpawnNPC.FireOutput( this, this ); pent->SetLocalOrigin( GetAbsOrigin() ); pent->SetLocalAngles( GetAbsAngles() ); pent->AddSpawnFlags( SF_NPC_FALL_TO_GROUND ); if ( m_spawnflags & SF_NPCMAKER_FADE ) { pent->AddSpawnFlags( SF_NPC_FADE_CORPSE ); } DispatchSpawn( pent ); pent->SetOwnerEntity( this ); m_cLiveChildren++;// count this NPC if (!(m_spawnflags & SF_NPCMAKER_INF_CHILD)) { m_iMaxNumNPCs--; if ( IsDepleted() ) { // Disable this forever. Don't kill it because it still gets death notices SetThink( NULL ); SetUse( NULL ); } } } //----------------------------------------------------------------------------- // Purpose: Creates a new NPC every so often. //----------------------------------------------------------------------------- void CNPCMaker::MakerThink ( void ) { SetNextThink( gpGlobals->curtime + m_flSpawnFrequency ); MakeNPC(); } //----------------------------------------------------------------------------- // Purpose: // Input : *pVictim - //----------------------------------------------------------------------------- void CNPCMaker::DeathNotice( CBaseEntity *pVictim ) { // ok, we've gotten the deathnotice from our child, now clear out its owner if we don't want it to fade. m_cLiveChildren--; }
26.742373
134
0.489416
tyabus
c7d85acbae86781f0222764777ee57a817799559
10,458
cpp
C++
net/socket_lib_old_bound_io_thread.cpp
AlexRuzin/CPP_API
404e2c298244e0e29cf06b8e1def4ed59a149cb2
[ "MIT" ]
14
2018-01-04T18:30:59.000Z
2021-07-07T15:15:15.000Z
net/socket_lib_old_bound_io_thread.cpp
AlexRuzin/CPP_API
404e2c298244e0e29cf06b8e1def4ed59a149cb2
[ "MIT" ]
null
null
null
net/socket_lib_old_bound_io_thread.cpp
AlexRuzin/CPP_API
404e2c298244e0e29cf06b8e1def4ed59a149cb2
[ "MIT" ]
6
2018-08-31T03:45:43.000Z
2019-06-05T02:55:46.000Z
#define _WINSOCKAPI_ #include <WinSock2.h> #include <Windows.h> #include <vector> #include "socket_lib.h" #include "../../_api/common/mem.h" #include "../../_api/common/str.h" #include "../../_api/api.h" #pragma comment (lib, "ws2_32.lib") using namespace socket_tools; socket_tools::SOCKET_THREAD_ENTRY __st_thread_conv socket_data::wait_thread(__in const __this_ptr This) { socket_tools::data *new_data; while (TRUE) { LPVOID buffer; UINT buffer_size; socket_tools::ER_WAIT_AND_READ wait_status = socket_tools::wait_and_read( This->get_socket(), socket_tools::_timeout_s, socket_tools::_timeout_ms, &buffer, &buffer_size); switch (wait_status) { case ER_WAIT_OK: new_data = new socket_tools::data(buffer, buffer_size, This->get_socket(), INVALID_SOCKET); This->handler(new_data, This); return; case ER_WAIT_FAIL: break; case ER_WAIT_NOTHING_RECEIVED: break; case ER_WAIT_TIMEOUT: continue; default: break; } } // Close socket, cleanup delete This; } socket_data::SOCKET_DATA_ERROR socket_tools::socket_data::wait_and_dispatch( __in const SOCKET rx_socket, __in const socket_data::f_handler handler) { if (rx_socket == INVALID_SOCKET || handler == NULL) return WAIT_FAIL; this->handler = handler; this->wait_and_read_thread = socket_tools::start_thread((LPTHREAD_START_ROUTINE)wait_thread, this); if (this->wait_and_read_thread == NULL) return WAIT_FAIL; return WAIT_OK; } socket_data::socket_data(__in PINIT_SOCKET_DATA init_data_param) { if (init_data_param == NULL) return; this->init_data = (PINIT_SOCKET_DATA)init_data_param; socket_handle = INVALID_SOCKET; wait_and_read_thread = INVALID_HANDLE_VALUE; ip = NULL; domain = NULL; port = init_data_param->port; if (init_data_param->type == server_type::TYPE_IP) { this->ip = init_data_param->ip; } else if (init_data_param->type == server_type::TYPE_DOMAIN) { struct hostent *host_info = gethostbyname((const char *)init_data_param->domain->to_lpstr()); struct in_addr address; mem::zeromem(&address, sizeof(struct in_addr)); address.S_un.S_addr = *(u_long *)host_info->h_addr_list[0]; this->ip = new str_string(inet_ntoa(address)); } else { return; } if (socket_tools::init_wsastartup == true) { if (socket_tools::wsadata == NULL) { socket_tools::wsadata = (WSADATA *)mem::malloc(sizeof(WSADATA)); ERROR_CODE wsa_status = WSAStartup(MAKEWORD(2, 2), socket_tools::wsadata); if (wsa_status) return; } } SOCKET tx_socket = INVALID_SOCKET; tx_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (tx_socket == INVALID_SOCKET) return; struct sockaddr_in address; mem::zeromem(&address, sizeof(struct sockaddr_in)); address.sin_addr.S_un.S_addr = inet_addr(this->ip->to_lpstr()); address.sin_family = AF_INET; address.sin_port = htons(init_data_param->port); ST_ERROR socket_status = connect(tx_socket, (const sockaddr *)&address, sizeof(const sockaddr)); if (socket_status == SOCKET_ERROR) { return; } this->socket_handle = tx_socket; return; } class socket_tools::socket_bind { private: // Sockets SOCKET a; SOCKET b; // socket_data class (optional) socket_data *sa; socket_data *sb; // Bind state bool bind_state; // Callbacks socket_tools::error_callback error_handler; // Defs typedef VOID BIND_THREAD; // Buffers LPVOID buffer_a; LPVOID buffer_b; CRITICAL_SECTION *lock; typedef bool IO_MODE; //true: listen on a. false: listen on b. typedef struct { SOCKET a; SOCKET b; IO_MODE mode; socket_bind *This; } IO_INFO, *PIO_INFO; PIO_INFO info_a, info_b; HANDLE thread_a; HANDLE thread_b; static socket_bind::BIND_THREAD __declspec(noreturn) __st_thread_conv socket_bind::bound_io_thread(PIO_INFO info); // Error handler. Cleans up and dispatches to error_handler callback VOID socket_bind::error_handler_local(VOID); // Data handler. Data is passed to this function. If it is NULL, it is bypassed. socket_tools::data_callback data_handler; public: // Ctors/Dtors. a is generally a client (obtained through listen), b is a server (obtained through connect). socket_bind(socket_data *a, socket_data *b, error_callback error_handler, data_callback data_handler) : a(INVALID_SOCKET), b(INVALID_SOCKET), error_handler(error_handler), data_handler(data_handler), lock(NULL), thread_a(INVALID_HANDLE_VALUE), thread_b(INVALID_HANDLE_VALUE), sa(a), sb(b), buffer_a(NULL), buffer_b(NULL) { if (a->get_socket() == INVALID_SOCKET || b->get_socket() == INVALID_SOCKET) return; this->a = sa->get_socket(); this->b = sb->get_socket(); this->lock = (PCRITICAL_SECTION)mem::malloc(sizeof(CRITICAL_SECTION)); cInitializeCriticalSection(this->lock); // Fix this shit this->info_a = (PIO_INFO)mem::malloc(sizeof(IO_INFO)); this->info_b = (PIO_INFO)mem::malloc(sizeof(IO_INFO)); info_a->a = info_b->a = this->a; info_a->b = info_b->b = this->b; info_a->This = info_b->This = this; info_a->mode = true; info_b->mode = false; this->thread_a = start_thread((LPTHREAD_START_ROUTINE)bound_io_thread, info_a); this->thread_b = start_thread((LPTHREAD_START_ROUTINE)bound_io_thread, info_b); this->bind_state = true; } socket_bind(SOCKET a, SOCKET b, error_callback error_handler, data_callback data_handler) : a(a), b(b), error_handler(error_handler), data_handler(data_handler), lock(NULL), thread_a(INVALID_HANDLE_VALUE), thread_b(INVALID_HANDLE_VALUE), sa(NULL), sb(NULL), buffer_a(NULL), buffer_b(NULL) { this->lock = (PCRITICAL_SECTION)mem::malloc(sizeof(CRITICAL_SECTION)); cInitializeCriticalSection(this->lock); this->info_a = (PIO_INFO)mem::malloc(sizeof(IO_INFO)); this->info_b = (PIO_INFO)mem::malloc(sizeof(IO_INFO)); info_a->a = info_b->a = this->a; info_a->b = info_b->b = this->b; info_a->This = info_b->This = this; info_a->mode = true; info_b->mode = false; this->thread_a = start_thread((LPTHREAD_START_ROUTINE)bound_io_thread, info_a); this->thread_b = start_thread((LPTHREAD_START_ROUTINE)bound_io_thread, info_b); this->bind_state = true; } ~socket_bind(VOID) { mem::free(this->lock); cTerminateThread(this->thread_a, 0); cTerminateThread(this->thread_b, 0); //cCloseHandle(this->thread_a); //cCloseHandle(this->thread_b); if (this->sa != NULL) delete sa; if (this->sb != NULL) delete sb; if (this->a != INVALID_SOCKET) closesocket(a); if (this->b != INVALID_SOCKET) closesocket(b); } // Creates threads //BIND_THREAD // Sync VOID socket_bind::sync(bool state) { switch (state) { case true: cEnterCriticalSection(this->lock); return; case false: cLeaveCriticalSection(this->lock); return; } } bool socket_bind::get_bind_state(VOID) { return this->bind_state; } }; socket_bind::BIND_THREAD __declspec(noreturn) __st_thread_conv socket_tools::socket_bind::bound_io_thread(PIO_INFO info) { cSleep(10); SOCKET listener, recipient; switch (info->mode) { case true: //a->b (wait and read on a) listener = info->a; recipient = info->b; //Sleep(INFINITE); break; case false: listener = info->b; recipient = info->a; } printf("[+] I/O BIND: listener: 0x%08x. recipient: 0x%08x\n", listener, recipient); while (TRUE) { socket_tools::data *new_data; LPVOID buffer; UINT buffer_size; //printf("0x%08x mode: %d\n", listener, info->mode); socket_tools::ER_WAIT_AND_READ wait_status = socket_tools::wait_and_read(listener, socket_tools::_timeout_s, socket_tools::_timeout_ms, &buffer, &buffer_size); //info->This->sync(true); switch (wait_status) { case ER_WAIT_NOTHING_RECEIVED: //info->This->sync(false); continue; case ER_WAIT_OK: // Send data new_data = new socket_tools::data(buffer, buffer_size, listener, recipient); info->This->data_handler(new_data); //info->This->sync(false); continue; case ER_WAIT_FAIL: info->This->error_handler(&listener, &recipient, info->This); cSleep(INFINITE); case ER_WAIT_TIMEOUT: //info->This->sync(false); continue; } } } socket_tools::socket_bind *socket_tools::bind_sockets(SOCKET a, SOCKET b, socket_data *sa, socket_data *sb, error_callback error_handler, data_callback data_handler) { if (error_handler == NULL) return NULL; socket_tools::socket_bind *bound_sockets = new socket_tools::socket_bind(sa, sb, error_handler, data_handler); return bound_sockets; } socket_tools::ER_WAIT_AND_READ socket_tools::wait_and_read(__in SOCKET rx_socket, __in const TIME32 time_s, __in const TIME32 time_u, __inout LPVOID *buffer, __out PUINT buffer_size) { if (rx_socket == INVALID_SOCKET) return ER_WAIT_FAIL; *buffer = NULL; *buffer_size = 0; struct timeval timed; mem::zeromem(&timed, sizeof(struct timeval)); timed.tv_sec = time_s; timed.tv_usec = time_u; fd_set read_flags, write_flags; FD_ZERO(&read_flags); FD_ZERO(&write_flags); FD_SET(0, &write_flags); FD_SET(rx_socket, &read_flags); BYTE rx_buffer[recv_buf_size]; while (TRUE) { } /* PUCHAR rx_buffer = (PUCHAR)mem::malloc(str::ASCII_CHAR); UINT rx_buffer_length = str::ASCII_CHAR; while (TRUE) { mem::zeromem(rx_buffer_new, recv_buf_size); INT select_status = select(rx_socket, &read_flags, NULL, NULL, &timed); if (!select_status) { if (select_status == SOCKET_ERROR) { mem::free(rx_buffer); return ER_WAIT_FAIL; } else if (read_flags.fd_count == 0) { if (rx_buffer_length == str::ASCII_CHAR) { mem::free(rx_buffer); return ER_WAIT_TIMEOUT; } break; } break; } UCHAR byte = 0; UINT rxd = recv(rx_socket, (char *)&byte, sizeof(UCHAR), 0); if (rxd != sizeof(UCHAR)) break; rx_buffer[rx_buffer_length - 1] = byte; PUCHAR new_buffer = (PUCHAR)mem::malloc(rx_buffer_length + rxd); mem::copy(new_buffer, rx_buffer, rx_buffer_length); mem::free(rx_buffer); rx_buffer = new_buffer; rx_buffer_length++; } if (rx_buffer_length == 1) { mem::free(rx_buffer); return ER_WAIT_NOTHING_RECEIVED; } *buffer = rx_buffer; *buffer_size = rx_buffer_length; return ER_WAIT_OK;*/ } HANDLE socket_tools::start_thread(__in const LPTHREAD_START_ROUTINE oep, __in const LPVOID parameter) { if (oep == NULL) return INVALID_HANDLE_VALUE; HANDLE thread_handle = cCreateThread( NULL, 0, oep, parameter, 0, NULL); return thread_handle; }
27.163636
120
0.710461
AlexRuzin
93a6f07a625009e6086938069f03b462a55635f7
896
cpp
C++
ConsoleApplication14/ConsoleApplication14/ConsoleApplication14.cpp
Hramkanvas/needandnotneed
f28ef4a4be428370e2148883c06126f5be9ccd4e
[ "MIT" ]
1
2019-12-28T13:57:09.000Z
2019-12-28T13:57:09.000Z
ConsoleApplication14/ConsoleApplication14/ConsoleApplication14.cpp
Hramkanvas/needandnotneed
f28ef4a4be428370e2148883c06126f5be9ccd4e
[ "MIT" ]
null
null
null
ConsoleApplication14/ConsoleApplication14/ConsoleApplication14.cpp
Hramkanvas/needandnotneed
f28ef4a4be428370e2148883c06126f5be9ccd4e
[ "MIT" ]
null
null
null
// ConsoleApplication14.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <iostream> #include <cmath> #include <math.h> using namespace std; int mxdiflg( const char **firstArray, size_t firstArrayLength, const char **secondArray, size_t secondArrayLength) { int xMax = 0, yMax = 0, xMin = 0, yMin = 0; while (*firstArray != '\0' || *secondArray != '\0') { if (*firstArray != '\0') { if (xMax < sizeof(*firstArray)) xMax = *firstArray; if (xMin > sizeof(*firstArray)) xMin = *firstArray ++firstArray; } if (*secondArray != '\0') { if (yMax < sizeof(*secondArray)) yMax = *secondArray; if (yMin > sizeof(*secondArray)) yMin = *secondArray ++secondArray; } } if (xMax == 0 && yMax == 0) return -1; return abs(xMax - yMin) >= abs(yMax - xMin) ? abs(xMax - yMin) : abs(yMax - xMin); } int main() { return 0; }
22.4
83
0.626116
Hramkanvas
93b2cace6c42eb54077548e5a420ef9e9ac8ca7e
6,206
cpp
C++
sussit.cpp
csaether/sussit
6471af56b0dea8ffb7d84a5c063d10e3e9b00d9d
[ "BSD-3-Clause-Clear" ]
null
null
null
sussit.cpp
csaether/sussit
6471af56b0dea8ffb7d84a5c063d10e3e9b00d9d
[ "BSD-3-Clause-Clear" ]
null
null
null
sussit.cpp
csaether/sussit
6471af56b0dea8ffb7d84a5c063d10e3e9b00d9d
[ "BSD-3-Clause-Clear" ]
null
null
null
// sussit.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <string.h> #include <errno.h> #include <sys/wait.h> #ifdef WIN32 int _tmain(int argc, _TCHAR* argv[]) #else int main(int argc, char *argv[]) #endif // <directory> [p | pr | pc | r | c] [minutes] [samplespercycle] [avgN] /* directory - will add "vizdata-<version>-", always write event log p - picoscope or live source, only write event log pr - picoscope or live source, + write raw sample data pc - picoscope or live source, + write cycle data and sample bursts pb - + cycle burst r - use raw sample data source c - use cycle data source minutes - minute limit for picoscope data, defaults to forever if not present */ { sussChanges susser; dataSamples *dsp = 0; // bug if not set somewhere later string argname, basefname; if ( argc > 1 ) { argname = argv[1]; } else { cout << "Usage: <directory> [p | pr | pc | r | c] [minutes] [samplespercycle] [avgN]" << endl; return 1; } bool writesamples = false; bool writecycles = false; bool writebursts = false; bool samplesource = false; bool picosource = false; char ct; if ( argname.empty() ) { picosource = true; // everything else false - no output files } else if ( argc > 2 ) { ct = argv[2][0]; if ( ct == 'p' ) { picosource = true; // this just means adc on electrum if ( argv[2][1] == 'r' ) { writesamples = true; } else if ( argv[2][1] == 'c' ) { writecycles = true; writebursts = true; } else if ( argv[2][1] == 'b' ) { writebursts = true; } } else if ( ct == 'r' ) { samplesource = true; writecycles = true; } } int minutes = 0; if ( argc > 3 ) { minutes = atoi( argv[3] ); } if ( argc > 4 ) { SamplesPerCycle = atoi( argv[4] ); } if ( argc > 5 ) { AvgNSamples = atoi( argv[5] ); if ( AvgNSamples == 0 ) { AvgNSamples = 1; } } // this is for picoscope and actual sample rate will be calculated // by looking at zero crossings on the first set of samples. If // this initial guess is way off that will probably not work right. int spsec = SamplesPerCycle*60; int nsecsper = 1000000000/spsec; // needs to be multiple of 50 nanosecs - why the 200, instead of 100? nsecsper = (nsecsper/200)*200; spsec = (1000000000/nsecsper); SamplesPerCycle = spsec/60; cout << SamplesPerCycle << " spc, " << nsecsper/2 << " nanosecs per sample, "; cout << AvgNSamples << " oversampling" << endl; fileSource fs; dataSamples ds; #ifdef WIN32 picoScope ps; #else adcSource as; #endif if ( !argname.empty() && picosource ) { // Looks like we have a valid directory, at least susser.setBaseDirectory( argname ); if ( !susser.setBaseFilename() ) { return 1; } basefname = susser.getBaseFilename(); } else { // kind of forgot what this branch is about.. basefname = "../"; basefname += argname; } if ( picosource ) { #ifdef WIN32 dsp = &ps; #else dsp = &as; #endif if ( writesamples ) { susser.setRawOut( true ); } } else { try { // reading either raw sample or cycle data to process if ( argname.empty() ) { throw sExc("Need a filename, dude"); } string fname(basefname); if ( samplesource ) { fname += "-raw.dat"; fs.open( fname.c_str() ); dsp = &fs; } else { // open stream for cycle data in fname += "-cyc.dat"; susser.openCyclesIn( fname.c_str() ); dsp = &ds; } } catch ( sExc &x ) { cout << x.msg() << endl; return 1; } catch ( exception &x ) { cout << x.what() << endl; return 1; } } try { // catch errors before forking dsp->setup(); if ( !basefname.empty() ) { susser.setConsOut( true ); } if ( writecycles ) { susser.setCycleOut( true ); } if ( writebursts ) { susser.setBurstOut( true ); } susser.setEventsOut( true ); } catch ( sExc &x ) { cout << x.msg() << endl; return 2; } catch ( exception &x ) { cout << x.what() << endl; return 2; } #ifdef forkit pid_t fpid; int exitsts; while ( true ) { fpid = fork(); if ( fpid == 0 ) { // the child break; } if ( fpid < 0 ) { cout << strerror(errno) << endl; } fpid = wait( &exitsts ); if ( fpid < 0 ) { cout << strerror(errno) << endl; return 3; } if ( WIFEXITED(exitsts) && WEXITSTATUS(exitsts) == 0 ) { cout << "normal exit" << endl; return 0; } // cannot refork until fixes to keep cyclenum advancing // probably need to open file in child and parse to get last one // probably need to open output files in child in order // to fork more than once - is it adc or regular files // making trouble? return 4; } #endif // the child, if forked - call the main method that will do the work // until something goes wrong or told to stop try { susser.processData( dsp, minutes*60*60 ); } catch ( sExc &x ) { cout << x.msg() << endl; return 1; } catch ( exception &x ) { cout << x.what() << endl; return 2; } return 0; }
27.954955
103
0.488398
csaether
93b7b5d43683b610bc14bf8cc044005e031d8e14
783
cpp
C++
WRK-V1.2/TOOLS/crt/src/cin.cpp
intj-t/openvmsft
0d17fbce8607ab2b880be976c2e86d8cfc3e83bb
[ "Intel" ]
null
null
null
WRK-V1.2/TOOLS/crt/src/cin.cpp
intj-t/openvmsft
0d17fbce8607ab2b880be976c2e86d8cfc3e83bb
[ "Intel" ]
null
null
null
WRK-V1.2/TOOLS/crt/src/cin.cpp
intj-t/openvmsft
0d17fbce8607ab2b880be976c2e86d8cfc3e83bb
[ "Intel" ]
null
null
null
// cin -- initialize standard input stream #include <fstream> #include <iostream> #pragma warning(disable: 4074) #pragma init_seg(compiler) static std::_Init_locks initlocks; _STD_BEGIN // OBJECT DECLARATIONS __PURE_APPDOMAIN_GLOBAL static filebuf fin(_cpp_stdin); __PURE_APPDOMAIN_GLOBAL extern _CRTDATA2 istream cin(&fin); _MRTIMP2 istream& __cdecl _Cin_func() { return cin; } // INITIALIZATION CODE struct _Init_cin { // ensures that cin is initialized __CLR_OR_THIS_CALL _Init_cin() { // initialize cin _Ptr_cin = &cin; cin.tie(_Ptr_cout); } }; __PURE_APPDOMAIN_GLOBAL static _Init_cin init_cin; _STD_END /* * Copyright (c) 1992-2005 by P.J. Plauger. ALL RIGHTS RESERVED. * Consult your license regarding permissions and restrictions. V4.05:0009 */
21.75
65
0.754789
intj-t
93b831781e97af174ec8a26f9af1d365d6ad7ea4
4,750
cpp
C++
Source/UEImgui/Private/ImguiWrap/ImguiResourceManager.cpp
ZhuRong-HomoStation/UEImgui
a4cf1fb940d3898a3ed6c48648f8ab2e6739975a
[ "MIT" ]
36
2020-12-25T05:57:39.000Z
2022-03-15T16:09:16.000Z
Source/UEImgui/Private/ImguiWrap/ImguiResourceManager.cpp
zhurongjun/UEImgui
a4cf1fb940d3898a3ed6c48648f8ab2e6739975a
[ "MIT" ]
11
2020-12-31T14:03:14.000Z
2021-03-05T07:19:06.000Z
Source/UEImgui/Private/ImguiWrap/ImguiResourceManager.cpp
zhurongjun/UEImgui
a4cf1fb940d3898a3ed6c48648f8ab2e6739975a
[ "MIT" ]
10
2020-12-24T07:14:38.000Z
2022-03-15T06:45:08.000Z
#include "ImguiWrap/ImguiResourceManager.h" #include "imgui.h" #include "Logging.h" #include "Config/ImguiConfig.h" #include "ImguiWrap/ImguiContext.h" #include "Slate/SlateTextureAtlasInterface.h" FImguiResource::FImguiResource(const FName& InName, UTexture* SourceObject) : Name(InName) , Source(SourceObject) { check(SourceObject != nullptr); } UImguiResourceManager::UImguiResourceManager() : CurrentResIdx(1) , DefaultFont(nullptr) { _InitDefaultFont(); } UImguiResourceManager& UImguiResourceManager::Get() { static UImguiResourceManager* Ins = nullptr; if (!Ins) { Ins = NewObject<UImguiResourceManager>(); Ins->AddToRoot(); } return *Ins; } ImTextureID UImguiResourceManager::AddResource(FName InResName, UTexture* SourceObj) { // find resource auto FoundRes = NamedResourceMap.Find(InResName); if (FoundRes) { UE_LOG(LogUEImgui, Warning, TEXT("UImguiResourceManager::AddResource : resource %s has exist!!!"), *InResName.ToString()); return reinterpret_cast<ImTextureID>((SIZE_T)*FoundRes); } // add resource int32 GotId = CurrentResIdx++; AllResource.Add(GotId, FImguiResource(InResName, (UTexture*)SourceObj)); NamedResourceMap.Add(InResName, GotId); return reinterpret_cast<ImTextureID>((SIZE_T)GotId); } bool UImguiResourceManager::IsResourceExist(FName InResName) { return NamedResourceMap.Find(InResName) != nullptr; } bool UImguiResourceManager::IsResourceExist(ImTextureID InID) { return AllResource.Find((int32)reinterpret_cast<SIZE_T>(InID)) != nullptr; } FImguiResource* UImguiResourceManager::FindResource(FName InResName) { auto FoundID = NamedResourceMap.Find(InResName); if (!FoundID) return nullptr; return AllResource.Find(*FoundID); } FImguiResource* UImguiResourceManager::FindResource(ImTextureID InResId) { return AllResource.Find((int32)reinterpret_cast<SIZE_T>(InResId)); } void UImguiResourceManager::ReleaseResource(FName InResName) { auto FoundRes = NamedResourceMap.Find(InResName); if (FoundRes) { AllResource.Remove(*FoundRes); NamedResourceMap.Remove(InResName); } } void UImguiResourceManager::ReleaseResource(ImTextureID InID) { int32 UEId = (int32)reinterpret_cast<SIZE_T>(InID); auto FoundRes = AllResource.Find(UEId); if (FoundRes) { NamedResourceMap.Remove(FoundRes->Name); AllResource.Remove(UEId); } } void UImguiResourceManager::BeginDestroy() { Super::BeginDestroy(); _ShutDownDefaultFont(); } void UImguiResourceManager::_InitDefaultFont() { DefaultFont = IM_NEW(ImFontAtlas); // get unreal default font #if WITH_EDITOR const FCompositeFont* CompositeFont = FCoreStyle::Get(). GetWidgetStyle<FTextBlockStyle>("NormalText").Font.GetCompositeFont(); FString FontPath = CompositeFont->DefaultTypeface.Fonts[0].Font.GetFontFilename(); FString FallbackPath = CompositeFont->FallbackTypeface.Typeface.Fonts[0].Font.GetFontFilename(); // add font DefaultFont->AddFontFromFileTTF( TCHAR_TO_UTF8(*FontPath), 15.0f, nullptr, DefaultFont->GetGlyphRangesDefault()); ImFontConfig FontConfig = {}; FontConfig.MergeMode = true; FontConfig.SizePixels = 15.0f; DefaultFont->AddFontFromFileTTF( TCHAR_TO_UTF8(*FallbackPath), 15.0f, &FontConfig, DefaultFont->GetGlyphRangesChineseFull()); #else if (UImguiConfig::Get()->FontPath.IsEmpty()) { DefaultFont->AddFontDefault(); } else { DefaultFont->AddFontFromFileTTF( TCHAR_TO_UTF8(*UImguiConfig::Get()->FontPath), 15.0f, nullptr, DefaultFont->GetGlyphRangesDefault()); ImFontConfig FontConfig = {}; FontConfig.MergeMode = true; FontConfig.SizePixels = 15.0f; DefaultFont->AddFontFromFileTTF( TCHAR_TO_UTF8(*UImguiConfig::Get()->FontPath), 15.0f, &FontConfig, DefaultFont->GetGlyphRangesChineseFull()); } #endif // get texture info unsigned char* Pixels; int Width, Height, Bpp; DefaultFont->GetTexDataAsRGBA32(&Pixels, &Width, &Height, &Bpp); // copy to UTexture2D UTexture2D* Texture = UTexture2D::CreateTransient(Width, Height, EPixelFormat::PF_B8G8R8A8, TEXT("Imgui_DefaultFont")); Texture->UpdateResource(); FUpdateTextureRegion2D* TextureRegion = new FUpdateTextureRegion2D(0, 0, 0, 0, Width, Height); auto DataCleanup = [](uint8* Data, const FUpdateTextureRegion2D* UpdateRegion) { delete UpdateRegion; }; Texture->UpdateTextureRegions(0, 1u, TextureRegion, Bpp * Width, Bpp, Pixels, DataCleanup); // add to resource map AllResource.Add((int32)EGlobalImguiTextureId::DefaultFont, FImguiResource("DefaultFont", Texture)); NamedResourceMap.Add("DefaultFont", (int32)EGlobalImguiTextureId::DefaultFont); // setup font DefaultFont->TexID = reinterpret_cast<ImTextureID>(EGlobalImguiTextureId::DefaultFont); } void UImguiResourceManager::_ShutDownDefaultFont() { IM_DELETE(DefaultFont); }
28.787879
124
0.762737
ZhuRong-HomoStation
93bc62aad3e862b55661de0c9a3e14edc8cefffe
411
cpp
C++
RangeQueries/RangeUpdateQueries/short_m.cpp
0x5eba/CSES-solutions
c18b66262f5dbef44b58d793f5185c3d0cf3a77c
[ "MIT" ]
27
2019-12-23T21:20:00.000Z
2022-02-06T04:28:27.000Z
RangeQueries/RangeUpdateQueries/short_m.cpp
0x5eba/CSES-solutions
c18b66262f5dbef44b58d793f5185c3d0cf3a77c
[ "MIT" ]
2
2020-04-14T21:40:43.000Z
2020-09-06T11:15:42.000Z
RangeQueries/RangeUpdateQueries/short_m.cpp
0x5eba/CSES-solutions
c18b66262f5dbef44b58d793f5185c3d0cf3a77c
[ "MIT" ]
9
2020-05-22T08:00:29.000Z
2021-09-14T09:01:58.000Z
#include<iostream> using namespace std;typedef long long ll;ll t[10000000];int N,Q,v,q,l,z,u,a; ll query(int r){ll s=0;for(;r>=0;r=(r&(r+1))-1)s+=t[r];return s;} void update(int i,int m){for(;i<N;i=i|(i+1))t[i]+=m;} int main(){cin>>N>>Q;for(a=0;a<N;++a){cin>>v;update(a,v);update(a+1,-v);}for(a=0;a<Q;++a){cin>>q;if(q==1){cin>>l>>z>>u;l--;z--;update(l,u);update(z+1,-u);}else{cin>>l;l--;cout<<query(l)<<'\n';}}}
82.2
195
0.579075
0x5eba
93bdb02753841f4a453f0a068372e893379bcf3d
2,860
cc
C++
test/TestGenomicRange.cc
yiq/SubcloneSeeker
e01e9bc8425899581d64edc491461f65c9f7e0b0
[ "MIT" ]
7
2015-04-28T04:42:08.000Z
2022-02-02T10:39:44.000Z
test/TestGenomicRange.cc
yiq/SubcloneSeeker
e01e9bc8425899581d64edc491461f65c9f7e0b0
[ "MIT" ]
1
2018-12-27T07:45:04.000Z
2018-12-27T07:45:04.000Z
test/TestGenomicRange.cc
yiq/SubcloneSeeker
e01e9bc8425899581d64edc491461f65c9f7e0b0
[ "MIT" ]
5
2015-02-25T02:47:49.000Z
2019-11-25T10:16:08.000Z
/** * @file Unit tests for class GenomicLocation * * @see GenomicLocation * @author Yi Qiao */ /* The MIT License (MIT) Copyright (c) 2013 Yi Qiao 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: all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <iostream> #include "GenomicRange.h" #include "common.h" using namespace SubcloneSeeker; SUITE(testGenomicRange) { TEST(ObjectCreation) { GenomicRange loc; CHECK( true /* object creation should always pass */); } TEST(RangeOverlap) { GenomicRange range[8]; range[0].chrom=1; range[0].position=300; range[0].length=400; range[1].chrom=1; range[1].position=200; range[1].length=600; range[2].chrom=1; range[2].position=400; range[2].length=200; range[3].chrom=1; range[3].position=100; range[3].length=400; range[4].chrom=1; range[4].position=500; range[4].length=400; range[5].chrom=1; range[5].position=0; range[5].length=50; range[6].chrom=1; range[6].position=950; range[6].length=50; range[7].chrom=2; range[7].position=300; range[7].length=500; for(int i=0; i<5; i++) { for(int j=0; j<5; j++) { CHECK(range[i].overlaps(range[j])); } for(int j=5; j<8; j++) { CHECK(not range[i].overlaps(range[j])); } } CHECK(range[1] < range[0]); CHECK(range[2] > range[0]); CHECK(range[3] < range[0]); CHECK(range[4] > range[0]); CHECK(range[5] < range[0]); CHECK(range[6] > range[0]); CHECK(range[7] > range[0]); } TEST(RangeCompare) { GenomicRange range; range.chrom=2; range.position=1000; range.length=1000; GenomicLocation loc1, loc2, loc3, loc4; loc1.chrom=1; loc1.position = 2000; loc2.chrom=2; loc2.position=500; loc3.chrom=2; loc3.position=1500; loc4.chrom=3; loc4.position = 500; CHECK( range > loc1 ); CHECK(not ( range < loc1 )); CHECK(range > loc2); CHECK(not ( range < loc2 )); CHECK(range < loc3); CHECK(not ( range > loc3 )); CHECK(range < loc4); CHECK(not ( range > loc4 )); } } TEST_MAIN
23.636364
77
0.686713
yiq
93bf279a4b02823d7bf2d21a84dce6e5d64c2731
234
cpp
C++
Source/Minigold/Minigold.cpp
Entalpi/unreal-project
71de6292591f45a0855f90a0da5d13a48caabfaa
[ "MIT" ]
null
null
null
Source/Minigold/Minigold.cpp
Entalpi/unreal-project
71de6292591f45a0855f90a0da5d13a48caabfaa
[ "MIT" ]
null
null
null
Source/Minigold/Minigold.cpp
Entalpi/unreal-project
71de6292591f45a0855f90a0da5d13a48caabfaa
[ "MIT" ]
null
null
null
// Copyright 1998-2019 Epic Games, Inc. All Rights Reserved. #include "Minigold.h" #include "Modules/ModuleManager.h" IMPLEMENT_PRIMARY_GAME_MODULE( FDefaultGameModuleImpl, Minigold, "Minigold" ); DEFINE_LOG_CATEGORY(LogMinigold)
26
78
0.799145
Entalpi
93bf28aee7c2c78c4d286ab4c84f4d78140e7a47
29,635
cpp
C++
src/game/server/swarm/asw_squadformation.cpp
BlueNovember/alienswarm-reactivedrop
ffaca58157f9fdd36e5c48e8d7d34d8ca958017e
[ "CC0-1.0" ]
null
null
null
src/game/server/swarm/asw_squadformation.cpp
BlueNovember/alienswarm-reactivedrop
ffaca58157f9fdd36e5c48e8d7d34d8ca958017e
[ "CC0-1.0" ]
null
null
null
src/game/server/swarm/asw_squadformation.cpp
BlueNovember/alienswarm-reactivedrop
ffaca58157f9fdd36e5c48e8d7d34d8ca958017e
[ "CC0-1.0" ]
null
null
null
#include "cbase.h" #include "asw_marine.h" #include "asw_marine_profile.h" #include "ai_hint.h" #include "asw_marine_hint.h" #include "asw_weapon_healgrenade_shared.h" #include "asw_shieldbug.h" #include "asw_boomer_blob.h" #include "ai_network.h" #include "triggers.h" // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" ConVar asw_marine_ai_followspot( "asw_marine_ai_followspot", "0", FCVAR_CHEAT ); ConVar asw_follow_hint_max_range( "asw_follow_hint_max_range", "300", FCVAR_CHEAT ); ConVar asw_follow_hint_max_z_dist( "asw_follow_hint_max_z_dist", "120", FCVAR_CHEAT ); ConVar asw_follow_use_hints( "asw_follow_use_hints", "2", FCVAR_CHEAT, "0 = follow formation, 1 = use hints when in combat, 2 = always use hints" ); ConVar asw_follow_hint_debug( "asw_follow_hint_debug", "0", FCVAR_CHEAT ); ConVar asw_follow_velocity_predict( "asw_follow_velocity_predict", "0.3", FCVAR_CHEAT, "Marines travelling in diamond follow formation will predict their leader's movement ahead by this many seconds" ); ConVar asw_follow_threshold( "asw_follow_threshold", "40", FCVAR_CHEAT, "Marines in diamond formation will move after leader has moved this much" ); ConVar asw_squad_debug( "asw_squad_debug", "1", FCVAR_CHEAT, "Draw debug overlays for squad movement" ); #define OUT_OF_BOOMER_BOMB_RANGE FLT_MAX void CASW_SquadFormation::LevelInitPostEntity() { BaseClass::LevelInitPostEntity(); CHintCriteria hintCriteria; hintCriteria.SetHintType( HINT_FOLLOW_WAIT_POINT ); #ifdef HL2_HINTS m_bLevelHasFollowHints = ( CAI_HintManager::FindHint( vec3_origin, hintCriteria ) != NULL ); #else m_bLevelHasFollowHints = ( MarineHintManager()->GetHintCount() > 0 ); #endif Msg( "Level has follow hints %d\n", m_bLevelHasFollowHints ); } unsigned int CASW_SquadFormation::Add( CASW_Marine *pMarine ) { AssertMsg( !!m_hLeader.Get(), "A CASW_SquadFormation has no leader!\n" ); if ( pMarine == Leader() ) { AssertMsg1( false, "Tried to set %s to follow itself!\n", pMarine->GetMarineProfile()->GetShortName() ); return INVALID_SQUADDIE; } unsigned slot = Find(pMarine); if ( IsValid( slot ) ) { AssertMsg2( false, "Tried to double-add %s to squad (already in slot %d)\n", pMarine->GetMarineProfile()->GetShortName(), slot ); return slot; } else { for ( slot = 0 ; slot < MAX_SQUAD_SIZE; ++slot ) { if ( !Squaddie(slot) ) { m_hSquad[slot] = pMarine; return slot; } } // if we're down here, the squad is full! AssertMsg2( false, "Tried to add %s to %s's squad, but that's full! (How?)\n", pMarine->GetMarineProfile()->GetShortName(), m_hLeader->GetMarineProfile()->GetShortName() ); return INVALID_SQUADDIE; } } bool CASW_SquadFormation::Remove( unsigned int slotnum ) { Assert(IsValid(slotnum)); if ( Squaddie(slotnum) ) { m_hSquad[slotnum] = NULL; return true; } else { return false; } } bool CASW_SquadFormation::Remove( CASW_Marine *pMarine, bool bIgnoreAssert ) { unsigned slot = Find(pMarine); if ( IsValid(slot) ) { m_hSquad[slot] = NULL; return true; } else { AssertMsg1( bIgnoreAssert, "Tried to remove marine %s from squad, but wasn't a member.\n", pMarine->GetMarineProfile()->GetShortName() ); return false; } } const Vector CASW_SquadFormation::s_MarineFollowOffset[MAX_SQUAD_SIZE]= { Vector( -60, -70, 0 ), Vector( -120, 0, 0 ), Vector( -60, 70, 0 ) }; const float CASW_SquadFormation::s_MarineFollowDirection[MAX_SQUAD_SIZE]= { -70, 180, 70 }; // position offsets when standing around a heal beacon const Vector CASW_SquadFormation::s_MarineBeaconOffset[MAX_SQUAD_SIZE]= { Vector( 30, -52, 0 ), Vector( -52, 0, 0 ), Vector( 30, 52, 0 ) }; const float CASW_SquadFormation::s_MarineBeaconDirection[MAX_SQUAD_SIZE]= { -70, 180, 70 }; float CASW_SquadFormation::GetYaw( unsigned slotnum ) { if ( m_bStandingInBeacon[slotnum] ) { return s_MarineBeaconDirection[slotnum]; } else if ( m_bFleeingBoomerBombs[ slotnum ] ) { CASW_Marine *pMarine = Squaddie( slotnum ); if ( pMarine ) { return pMarine->ASWEyeAngles()[ YAW ]; } return 0.0f; } else if ( m_bLevelHasFollowHints && asw_follow_use_hints.GetBool() && Leader() && ( Leader()->IsInCombat() || asw_follow_use_hints.GetInt() == 2 ) ) { #ifdef HL2_HINTS if ( m_hFollowHint[ slotnum ].Get() ) { // if ( m_bRearGuard[ slotnum ] ) // { // return m_hFollowHint[ slotnum ]->Yaw() + 180.0f; // } return m_hFollowHint[ slotnum ]->Yaw(); } #else if ( m_nMarineHintIndex[ slotnum ] != INVALID_HINT_INDEX ) { // if ( m_bRearGuard[ slotnum ] ) // { // return m_hFollowHint[ slotnum ]->Yaw() + 180.0f; // } return MarineHintManager()->GetHintYaw( m_nMarineHintIndex[ slotnum ] ); } #endif else { return anglemod( m_flCurrentForwardAbsoluteEulerYaw + s_MarineFollowDirection[ slotnum ] ); // CASW_Marine *pMarine = Squaddie( slotnum ); // if ( pMarine ) // { // return pMarine->ASWEyeAngles()[ YAW ]; // } // return 0.0f; } } // face our formation direction return anglemod( m_flCurrentForwardAbsoluteEulerYaw + s_MarineFollowDirection[ slotnum ] ); } #if 1 void CASW_SquadFormation::RecomputeFollowerOrder( const Vector &vProjectedLeaderPos, QAngle qLeaderAim ) ///< reorganize the follower slots so that each follower has the least distance to move { VPROF("CASW_Marine::RecomputeFollowerOrder"); //#pragma message("TODO: this algorithm should be SIMD optimized.") // all the possible orderings of three followers ( 3! == 6 ) const static uint8 sFollowerOrderings[6][MAX_SQUAD_SIZE] = { { 0, 1, 2 }, { 0, 2, 1 }, { 1, 0, 2 }, { 1, 2, 0 }, { 2, 0, 1 }, { 2, 1, 0 } }; // keep track of how well each order scored float fOrderingScores[6] = { FLT_MAX, FLT_MAX, FLT_MAX, FLT_MAX, FLT_MAX, FLT_MAX }; // score each permutation in turn. (This is an experimental dirty algo, // and will be SIMDied if we actually go this route) qLeaderAim[ PITCH ] = 0; matrix3x4_t matLeader; Vector vecLeaderAim = GetLdrAnglMatrix( vProjectedLeaderPos, qLeaderAim, &matLeader ); Vector vProjectedFollowPos[ MAX_SQUAD_SIZE ]; for ( int i = 0 ; i < MAX_SQUAD_SIZE ; ++i ) { if ( m_bLevelHasFollowHints && asw_follow_use_hints.GetBool() && m_hLeader.Get() && ( m_hLeader->IsInCombat() || asw_follow_use_hints.GetInt() == 2 ) ) { #ifdef HL2_HINTS if ( m_hFollowHint[i].Get() ) { // in combat, follow positions come from nearby hint nodes vProjectedFollowPos[i] = m_hFollowHint[i]->GetAbsOrigin(); } #else if ( m_nMarineHintIndex[i] != INVALID_HINT_INDEX ) { // in combat, follow positions come from nearby hint nodes vProjectedFollowPos[i] = MarineHintManager()->GetHintPosition( m_nMarineHintIndex[i] ); } #endif else { CASW_Marine *pMarine = Squaddie( i ); if ( pMarine ) { vProjectedFollowPos[i] = pMarine->GetAbsOrigin(); } } } else { // when not in combat, use our fixed follow offsets VectorTransform( s_MarineFollowOffset[i], matLeader, vProjectedFollowPos[i] ); } } for ( int permute = 0 ; permute < 6 ; ++permute ) { // each marine is scored by how far he'd have to move to get to his follow position. // movement perpendicular to the leader's aim vector is weighed more heavily than // movement along it. lowest score wins. float score = 0; for ( int follower = 0 ; follower < MAX_SQUAD_SIZE ; ++follower ) { const int iFollowSlot = sFollowerOrderings[permute][follower]; const CASW_Marine * RESTRICT pFollower = Squaddie(follower); if ( pFollower ) { /* Vector vecTransformedOffset; VectorTransform( s_MarineFollowOffset[iFollowSlot], matLeader, vecTransformedOffset ); Vector traverse = vecTransformedOffset - pFollower->GetAbsOrigin(); */ Vector traverse = vProjectedFollowPos[iFollowSlot] - pFollower->GetAbsOrigin(); // score += traverse.Length2D(); traverse.z = 0; score += ( traverse + traverse - traverse.ProjectOnto(vecLeaderAim) ).Length(); } } fOrderingScores[ permute ] = score; } // once done, figure out the best scoring alternative, int iBestPermute = 0; for ( int ii = 1 ; ii < 6 ; ++ii ) { iBestPermute = ( fOrderingScores[ ii ] >= fOrderingScores[ iBestPermute ] ) ? iBestPermute : ii; } // and use it if ( iBestPermute != 0 ) { // (some change is needed) CASW_Marine * RESTRICT pOldFollowers[ MAX_SQUAD_SIZE ] = {0}; for ( int ii = 0 ; ii < MAX_SQUAD_SIZE ; ++ii ) // copy off the current array as we're about to permute it { pOldFollowers[ii] = m_hSquad[ii]; } for ( int ii = 0 ; ii < MAX_SQUAD_SIZE ; ++ii ) { m_hSquad[ii] = pOldFollowers[ sFollowerOrderings[iBestPermute][ii] ]; } // Msg( "\n" ); if ( asw_marine_ai_followspot.GetBool() ) { static float colors[3][3] = { { 255, 127, 127 }, { 127, 255, 127 }, { 127, 127, 255 } }; for ( int ii = 0 ; ii < MAX_SQUAD_SIZE ; ++ii ) { NDebugOverlay::HorzArrow( m_hSquad[ii]->GetAbsOrigin(), m_vFollowPositions[ii], 3, colors[ii][0], colors[ii][1], colors[ii][2], 196, false, 0.35f ); } } } } #endif Vector CASW_SquadFormation::GetLdrAnglMatrix( const Vector &origin, const QAngle &ang, matrix3x4_t * RESTRICT pout ) RESTRICT { Vector vecLeaderAim; { // "forward" is actual movement velocity if available, facing otherwise float leaderVelSq = m_vLastLeaderVelocity.LengthSqr(); if ( leaderVelSq > 1.0f ) { vecLeaderAim = m_vLastLeaderVelocity * FastRSqrtFast(leaderVelSq); VectorMatrix( vecLeaderAim, *pout ); pout->SetOrigin( origin ); } else { AngleMatrix( ang, origin, *pout ); MatrixGetColumn( *pout, 0, vecLeaderAim ); } } m_vCachedForward = vecLeaderAim; if (m_vCachedForward[1] == 0 && m_vCachedForward[0] == 0) { m_flCurrentForwardAbsoluteEulerYaw = 0; } else { m_flCurrentForwardAbsoluteEulerYaw = (atan2(vecLeaderAim[1], vecLeaderAim[0]) * (180.0 / M_PI)); m_flCurrentForwardAbsoluteEulerYaw = fsel( m_flCurrentForwardAbsoluteEulerYaw, m_flCurrentForwardAbsoluteEulerYaw, m_flCurrentForwardAbsoluteEulerYaw + 360 ); } return vecLeaderAim; } // returns OUT_OF_BOOMER_BOMB_RANGE if not within blast radius of any boomer bomb float GetClosestBoomerBlobDistSqr( const Vector &vecPosition ) { float flClosestBoomerBlobDistSqr = OUT_OF_BOOMER_BOMB_RANGE; for( int iBoomerBlob = 0; iBoomerBlob < g_aExplosiveProjectiles.Count(); iBoomerBlob++ ) { CBaseEntity *pExplosive = g_aExplosiveProjectiles[ iBoomerBlob ]; const float flExplosiveRadius = 240.0f; // bad hardcoded to match boomer blob radius float flDistSqr = pExplosive->GetAbsOrigin().DistToSqr( vecPosition ); if( flDistSqr < Square( flExplosiveRadius ) && flDistSqr < flClosestBoomerBlobDistSqr ) { flClosestBoomerBlobDistSqr = flDistSqr; } } return flClosestBoomerBlobDistSqr; } bool WithinBoomerBombRadius( const Vector &vecPosition ) { return ( GetClosestBoomerBlobDistSqr( vecPosition ) < OUT_OF_BOOMER_BOMB_RANGE ); } void CASW_SquadFormation::UpdateFollowPositions() { VPROF("CASW_SquadFormation::UpdateFollowPositions"); CASW_Marine * RESTRICT pLeader = Leader(); if ( !pLeader ) { AssertMsg1(false, "Tried to update positions for a squad with no leader and %d followers.\n", Count() ); return; } m_flLastSquadUpdateTime = gpGlobals->curtime; if ( m_bLevelHasFollowHints && asw_follow_use_hints.GetBool() && ( pLeader->IsInCombat() || asw_follow_use_hints.GetInt() ) ) { FindFollowHintNodes(); } QAngle angLeaderFacing = pLeader->EyeAngles(); angLeaderFacing[PITCH] = 0; matrix3x4_t matLeaderFacing; Vector vProjectedLeaderPos = pLeader->GetAbsOrigin() + pLeader->GetAbsVelocity() * asw_follow_velocity_predict.GetFloat(); GetLdrAnglMatrix( vProjectedLeaderPos, angLeaderFacing, &matLeaderFacing ); for ( int i = 0 ; i < MAX_SQUAD_SIZE ; ++i ) { CASW_Marine *pMarine = Squaddie( i ); if ( !pMarine ) continue; m_bStandingInBeacon[i] = false; m_bFleeingBoomerBombs[ i ] = false; CBaseEntity *pBeaconToStandIn = NULL; // check for nearby heal beacons if ( IHealGrenadeAutoList::AutoList().Count() > 0 && pMarine->GetHealth() < pMarine->GetMaxHealth() ) { const float flHealGrenadeDetectionRadius = 600.0f; for ( int g = 0; g < IHealGrenadeAutoList::AutoList().Count(); ++g ) { const CUtlVector< IHealGrenadeAutoList* > &grenades = IHealGrenadeAutoList::AutoList(); CBaseEntity *pBeacon = grenades[g]->GetEntity(); if ( pBeacon && pBeacon->GetAbsOrigin().DistTo( pMarine->GetAbsOrigin() ) < flHealGrenadeDetectionRadius ) { pBeaconToStandIn = pBeacon; break; } } } if ( pBeaconToStandIn ) { m_vFollowPositions[i] = pBeaconToStandIn->GetAbsOrigin() + s_MarineBeaconOffset[i]; m_bStandingInBeacon[i] = true; } else if( g_aExplosiveProjectiles.Count() ) { bool bSafeNodeFound = false; bool bUnsafeNodeFound = false; float flClosestSafeNodeDistSqr = FLT_MAX; float flBestUnsafeNodeDistSqr = 0.0f; Vector vecClosestSafeNode; Vector vecBestUnsafeNode; const float k_flMaxSearchDistance = 300.0f; for( int iNode = 0; iNode < pMarine->GetNavigator()->GetNetwork()->NumNodes(); iNode++ ) { CAI_Node *pAiNode = pMarine->GetNavigator()->GetNetwork()->GetNode( iNode ); Vector vecNodeLocation = pAiNode->GetOrigin(); if( vecNodeLocation.DistToSqr( pMarine->GetAbsOrigin() ) > Square( k_flMaxSearchDistance ) ) continue; bool bNodeTaken = false; for( int iSlot = 0; iSlot < MAX_SQUAD_SIZE; iSlot++ ) { if ( iSlot != i && vecNodeLocation.DistToSqr( m_vFollowPositions[ iSlot ] ) < Square( 30.0f ) ) // don't let marines get too close, even if nodes are close { bNodeTaken= true; break; } } if( !bNodeTaken ) { float flClosestBoomerBlobDistSqr = GetClosestBoomerBlobDistSqr( vecNodeLocation ); if( flClosestBoomerBlobDistSqr == OUT_OF_BOOMER_BOMB_RANGE ) { // if closer than the previous closest node, and the current node isn't taken, reserve it float flSafeNodeDistSqr = vecNodeLocation.DistToSqr( pMarine->GetAbsOrigin() ); if ( flSafeNodeDistSqr < flClosestSafeNodeDistSqr ) { flClosestSafeNodeDistSqr = flSafeNodeDistSqr; bSafeNodeFound = true; vecClosestSafeNode = vecNodeLocation; } } else { if( flClosestBoomerBlobDistSqr > flBestUnsafeNodeDistSqr ) { flBestUnsafeNodeDistSqr = flClosestBoomerBlobDistSqr; bUnsafeNodeFound = true; vecBestUnsafeNode = vecNodeLocation; } } } } if( bSafeNodeFound ) { m_vFollowPositions[ i ] = vecClosestSafeNode; m_bFleeingBoomerBombs[ i ] = true; } else if( bUnsafeNodeFound ) { m_vFollowPositions[ i ] = vecBestUnsafeNode; m_bFleeingBoomerBombs[ i ] = true; } } else if ( m_bLevelHasFollowHints && asw_follow_use_hints.GetBool() && ( pLeader->IsInCombat() || asw_follow_use_hints.GetInt() == 2 ) ) { #ifdef HL2_HINTS if ( m_hFollowHint[i].Get() ) { m_vFollowPositions[i] = m_hFollowHint[i]->GetAbsOrigin(); } #else if ( m_nMarineHintIndex[i] != INVALID_HINT_INDEX ) { m_vFollowPositions[i] = MarineHintManager()->GetHintPosition( m_nMarineHintIndex[i] ); } #endif else { if ( pMarine ) { m_vFollowPositions[i] = pMarine->GetAbsOrigin(); } } } else { VectorTransform( s_MarineFollowOffset[i], matLeaderFacing, m_vFollowPositions[i] ); } if ( asw_marine_ai_followspot.GetBool() ) { static float colors[3][3] = { { 255, 64, 64 }, { 64, 255, 64 }, { 64, 64, 255 } }; NDebugOverlay::HorzArrow( pLeader->GetAbsOrigin(), m_vFollowPositions[i], 3, colors[i][0], colors[i][1], colors[i][2], 255, false, 0.35f ); } } m_flLastLeaderYaw = pLeader->EyeAngles()[ YAW ]; m_vLastLeaderPos = pLeader->GetAbsOrigin(); m_vLastLeaderVelocity = pLeader->GetAbsVelocity(); } bool CASW_SquadFormation::SanityCheck() const { CASW_Marine *pLeader = Leader(); Assert( pLeader ); if ( !pLeader ) return false; // for each slot, make sure no dups, and that leader is not following self for ( int testee = 0 ; testee < MAX_SQUAD_SIZE ; ++testee ) { CASW_Marine *pTest = m_hSquad[testee]; Assert( pLeader != pTest ); // am not leader if ( pLeader == pTest ) return false; if ( pTest ) { for ( int i = (testee+1)%MAX_SQUAD_SIZE ; i != testee ; i = (i + 1)%MAX_SQUAD_SIZE ) { Assert( m_hSquad[i] != pTest ); // am not in array twice if ( m_hSquad[i] == pTest ) return false; } } } return true; } // For such a tiny array, a linear search is actually the fastest // way to go unsigned int CASW_SquadFormation::Find( CASW_Marine *pMarine ) const { Assert( pMarine != Leader() ); for ( int i = 0 ; i < MAX_SQUAD_SIZE ; ++i ) { if ( m_hSquad[i] == pMarine ) return i; } return INVALID_SQUADDIE; } void CASW_SquadFormation::ChangeLeader( CASW_Marine *pNewLeader, bool bUpdateLeaderPos ) { // if the squad has no leader, become the leader CASW_Marine *pOldLeader = Leader(); if ( !pOldLeader ) { Leader( pNewLeader ); return; } // if we're trying to wipe out the leader, do so if there are no followers if ( !pNewLeader ) { AssertMsg2( Count() == 0, "Tried to unset squad leader %s, but squad has %d followers\n", pNewLeader->GetMarineProfile()->GetShortName(), Count() ); Leader(NULL); return; } if ( pOldLeader == pNewLeader ) { AssertMsg1( false, "Tried to reset squad leader to its current value (%s)\n", pNewLeader->GetMarineProfile()->GetShortName() ); return; } // if the new leader was previously a follower, swap with the old leader int slot = Find( pNewLeader ); if ( IsValid(slot) ) { m_hSquad[slot] = pOldLeader; Leader( pNewLeader ); } else { // make the old leader a follower Leader( pNewLeader ); Add( pOldLeader ); } if ( bUpdateLeaderPos ) { m_flLastLeaderYaw = pNewLeader->EyeAngles()[ YAW ]; m_vLastLeaderPos = pNewLeader->GetAbsOrigin(); m_vLastLeaderVelocity = pNewLeader->GetAbsVelocity(); m_flLastSquadUpdateTime = gpGlobals->curtime; } else { m_flLastSquadUpdateTime = 0; } } void CASW_SquadFormation::LevelInitPreEntity() { Reset(); } void CASW_SquadFormation::Reset() { m_hLeader = NULL; for ( int i = 0 ; i < MAX_SQUAD_SIZE ; ++i ) { m_hSquad[i] = NULL; m_bRearGuard[i] = false; m_bStandingInBeacon[i] = false; m_bFleeingBoomerBombs[ i ] = false; #ifdef HL2_HINTS m_hFollowHint[i] = NULL; #else m_nMarineHintIndex[i] = INVALID_HINT_INDEX; #endif } m_flLastSquadUpdateTime = 0; m_bLevelHasFollowHints = false; m_vLastLeaderVelocity.Zero(); } //----------------------------------------------------------------------------- // Purpose: Sorts AI nodes by proximity to leader //----------------------------------------------------------------------------- CASW_Marine *g_pSortLeader = NULL; #ifdef HL2_HINTS int CASW_SquadFormation::FollowHintSortFunc( CAI_Hint* const *pHint1, CAI_Hint* const *pHint2 ) #else int CASW_SquadFormation::FollowHintSortFunc( HintData_t* const *pHint1, HintData_t* const *pHint2 ) #endif { int nDist1 = (int) (*pHint1)->GetAbsOrigin().DistToSqr( g_pSortLeader->GetAbsOrigin() ); int nDist2 = (int) (*pHint2)->GetAbsOrigin().DistToSqr( g_pSortLeader->GetAbsOrigin() ); return ( nDist1 - nDist2 ); } //----------------------------------------------------------------------------- // Purpose: Finds the set of hint nodes to use when following during combat //----------------------------------------------------------------------------- void CASW_SquadFormation::FindFollowHintNodes() { CASW_Marine *pLeader = Leader(); if ( !pLeader ) return; // evaluate each squaddie individually to see if his node should be updated for ( int slotnum = 0; slotnum < MAX_SQUAD_SIZE; slotnum++ ) { CASW_Marine *pMarine = Squaddie( slotnum ); if ( !pMarine ) { #ifdef HL2_HINTS m_hFollowHint[slotnum] = NULL; #else m_nMarineHintIndex[slotnum] = INVALID_HINT_INDEX; #endif continue; } bool bNeedNewNode = ( pMarine->GetAbsOrigin().DistTo( pLeader->GetAbsOrigin() ) > asw_follow_hint_max_range.GetFloat() ); if ( !bNeedNewNode ) { bNeedNewNode = !pMarine->FVisible( pLeader ); } // find shield bug (if any) nearest each marine const float k_flShieldbugScanRangeSqr = 400.0f * 400.0f; CASW_Shieldbug *pClosestShieldbug = NULL; float flClosestShieldBugDistSqr = k_flShieldbugScanRangeSqr; if ( pMarine->IsAlive() ) { for( int iShieldbug = 0; iShieldbug < IShieldbugAutoList::AutoList().Count(); iShieldbug++ ) { CASW_Shieldbug *pShieldbug = static_cast< CASW_Shieldbug* >( IShieldbugAutoList::AutoList()[ iShieldbug ] ); if( pShieldbug && pShieldbug->IsAlive() ) { float flDistSqr = pMarine->GetAbsOrigin().DistToSqr( pShieldbug->GetAbsOrigin() ); if( flDistSqr < flClosestShieldBugDistSqr ) { flClosestShieldBugDistSqr = flDistSqr; pClosestShieldbug = pShieldbug; } } } } if ( !bNeedNewNode && !pClosestShieldbug ) continue; // find a new node #ifdef HL2_HINTS CHintCriteria hintCriteria; hintCriteria.SetHintType( HINT_FOLLOW_WAIT_POINT ); hintCriteria.AddIncludePosition( pLeader->GetAbsOrigin(), asw_follow_hint_max_range.GetFloat() ); hintCriteria.AddExcludePosition( pLeader->GetAbsOrigin(), 80.0f ); CUtlVector< CAI_Hint * > hints; CAI_HintManager::FindAllHints( pLeader, pLeader->GetAbsOrigin(), hintCriteria, &hints ); #else CUtlVector< HintData_t* > hints; MarineHintManager()->FindHints( pLeader->GetAbsOrigin(), 80.0f, asw_follow_hint_max_range.GetFloat(), &hints ); #endif int nCount = hints.Count(); float flMovementYaw = pLeader->GetOverallMovementDirection(); int iClosestFlankingNode = INVALID_HINT_INDEX; float flClosestFlankingNodeDistSqr = FLT_MAX; CBaseTrigger *pEscapeVolume = pLeader->IsInEscapeVolume(); if ( pEscapeVolume && pEscapeVolume->CollisionProp() ) { // remove hints that aren't in the escape volume bounds for ( int i = nCount - 1; i >= 0; i-- ) { if ( !pEscapeVolume->CollisionProp()->IsPointInBounds( hints[ i ]->GetAbsOrigin() ) ) { hints.Remove( i ); nCount--; } else if ( asw_follow_hint_debug.GetBool() ) { NDebugOverlay::Box( hints[ i ]->GetAbsOrigin(), -Vector( 5, 5, 0 ), Vector( 5, 5, 5 ), 255, 0, 0, 255, 3.0f ); } } } else { // remove hints that are in front of the leader's overall direction of movement // TODO: turn this into a hint filter for ( int i = nCount - 1; i >= 0; i-- ) { Vector vecDir = ( hints[ i ]->GetAbsOrigin() - pLeader->GetAbsOrigin() ).Normalized(); float flYaw = UTIL_VecToYaw( vecDir ); flYaw = AngleDiff( flYaw, flMovementYaw ); bool bRemoveNode = false; if ( flYaw < 85.0f && flYaw > -85.0f ) { bRemoveNode = true; // remove hints that are in front of the leader's overall direction of movement, // unless we need to use them to get the AI to flank a shieldbug if( pClosestShieldbug ) { // if any of the marines are close, don't delete nodes behind the shieldbug float flShieldbugDistSqr = hints[ i ]->GetAbsOrigin().DistToSqr( pClosestShieldbug->GetAbsOrigin() ); if( flShieldbugDistSqr < k_flShieldbugScanRangeSqr ) { // preserve the node if it's behind the shieldbug Vector vecShieldBugToNode, vecShieldbugFacing; vecShieldBugToNode = hints[ i ]->GetAbsOrigin() - pClosestShieldbug->GetAbsOrigin(); QAngle angFacing = pClosestShieldbug->GetAbsAngles(); AngleVectors( angFacing, &vecShieldbugFacing ); vecShieldbugFacing.z = 0; vecShieldBugToNode.z = 0; VectorNormalize( vecShieldbugFacing ); VectorNormalize( vecShieldBugToNode ); float flForwardDot = vecShieldbugFacing.Dot( vecShieldBugToNode ); if( flForwardDot < 0.5f ) // if node is 60 degrees or more away from shieldbug's facing... { float flDistSqr = hints[ i ]->GetAbsOrigin().DistToSqr( pMarine->GetAbsOrigin() ); bool bHasLOS = pMarine->TestShootPosition( pMarine->GetAbsOrigin(), hints[ i ]->GetAbsOrigin() ); // if closer than the previous closest node, and the current node isn't taken, reserve it if( flDistSqr < flClosestFlankingNodeDistSqr && bHasLOS ) { bool flNodeTaken = false; for( int iSlot = 0; iSlot < MAX_SQUAD_SIZE; iSlot++ ) { #ifdef HL2_HINTS if ( iSlot != slotnum && hints[ i ] == m_hFollowHint[ iSlot ].Get() ) #else if ( iSlot != slotnum && hints[ i ]->m_nHintIndex == m_nMarineHintIndex[ iSlot ] ) #endif { flNodeTaken = true; break; } } if( !flNodeTaken ) { iClosestFlankingNode = hints[ i ]->m_nHintIndex; flClosestFlankingNodeDistSqr = flDistSqr; bRemoveNode = false; } } } } } } // if zdiff is too great, remove float flZDiff = fabs( hints[ i ]->GetAbsOrigin().z - pLeader->GetAbsOrigin().z ); if ( flZDiff > asw_follow_hint_max_z_dist.GetFloat() ) { bRemoveNode = true; } if( bRemoveNode ) { hints.Remove( i ); nCount--; } } } g_pSortLeader = pLeader; hints.Sort( CASW_SquadFormation::FollowHintSortFunc ); // if this marine is close to a shield bug, grab a flanking node if( !pEscapeVolume && pClosestShieldbug && iClosestFlankingNode != INVALID_HINT_INDEX ) { m_nMarineHintIndex[ slotnum ] = iClosestFlankingNode; continue; } // find the first node not used by another other squaddie int nNode = 0; for ( int i = 0; i < MAX_SQUAD_SIZE; i++ ) { bool bValidNode = true; while ( nNode < hints.Count() ) { for ( int k = 0; k < MAX_SQUAD_SIZE; k++ ) { #ifdef HL2_HINTS if ( k != slotnum && hints[ nNode ] == m_hFollowHint[k].Get() ) #else if ( k != slotnum && hints[ nNode ]->m_nHintIndex == m_nMarineHintIndex[ k ] ) #endif { bValidNode = false; break; } } if ( bValidNode ) { #ifdef HL2_HINTS m_hFollowHint[ slotnum ] = hints[ nNode ]; #else m_nMarineHintIndex[ slotnum ] = hints[ nNode ]->m_nHintIndex; #endif nNode++; break; } nNode++; } } } } bool CASW_SquadFormation::ShouldUpdateFollowPositions() const { // update if a heal beacon was placed/removed if ( m_iLastHealBeaconCount != IHealGrenadeAutoList::AutoList().Count() ) return true; bool bBoomerBombs = g_aExplosiveProjectiles.Count() > 0; // leader's more than epsilon from previous position, // and we haven't updated in a quarter second. // force a reupdate if leader's velocity has changed by 50% or more or boomer bombs are deployed return ( Leader() && ( gpGlobals->curtime > m_flLastSquadUpdateTime + 0.33f || ( Leader()->GetAbsVelocity() - m_vLastLeaderVelocity ).LengthSqr() * FastRecip(m_vLastLeaderVelocity.LengthSqr() ) > ( 0.5f * 0.5f ) || ( Leader()->GetAbsVelocity().IsZeroFast() && !m_vLastLeaderVelocity.IsZeroFast() ) ) && ( Leader()->GetAbsOrigin().DistToSqr(m_vLastLeaderPos) > Sqr(asw_follow_threshold.GetFloat()) || bBoomerBombs ) ); } void CASW_SquadFormation::DrawDebugGeometryOverlays() { if ( !asw_squad_debug.GetBool() ) return; CASW_Marine *pLeader = Leader(); if ( !pLeader ) return; for ( int i = 0; i < MAX_SQUAD_SIZE; i++ ) { CASW_Marine *pMarine = Squaddie( i ); if ( pMarine ) { NDebugOverlay::Line( pMarine->WorldSpaceCenter(), pLeader->WorldSpaceCenter(), 63, 63, 63, false, 0.05f ); #ifdef HL2_HINTS if ( m_hFollowHint[ i ].Get() ) { NDebugOverlay::Line( pMarine->WorldSpaceCenter(), m_hFollowHint[ i ]->GetAbsOrigin(), 255, 255, 63, false, 0.05f ); NDebugOverlay::EntityText( pMarine->entindex(), i * 2, CFmtStr( "Node: %d wc: %d node: %d pos: %f %f %f", m_hFollowHint[ i ]->GetNodeId(), m_hFollowHint[i]->GetWCId(), m_hFollowHint[i]->GetNode() ? m_hFollowHint[i]->GetNode()->GetId() : -1, m_hFollowHint[i]->GetAbsOrigin().x, m_hFollowHint[i]->GetAbsOrigin().y, m_hFollowHint[i]->GetAbsOrigin().z ), 0.05f, 255, 255, 255, 255 ); } #endif } } /* int max_marines = ASWGameResource()->GetMaxMarineResources(); for ( int i=0;i<max_marines;i++ ) { CASW_Marine_Resource* pMR = ASWGameResource()->GetMarineResource( i ); if ( !pMR ) continue; CASW_Marine *pMarine = pMR->GetMarineEntity(); if ( !pMarine ) continue; NDebugOverlay::EntityText( pMarine->entindex(), 0, CFmtStr( "Squad slot: %d", p ), 0.05f, 255, 255, 255, 255 ); } */ } CASW_SquadFormation g_ASWSquadFormation;
31.161935
203
0.649671
BlueNovember
93ca2e05aed8828a593a45c7365891fb06507dcf
426
hpp
C++
ZumoKit/NativeLibs/universal/include/card_callback.hpp
zumo/zumokit-ios
6981dbeaec723262c400d5b3872ace2e08f17997
[ "MIT" ]
null
null
null
ZumoKit/NativeLibs/universal/include/card_callback.hpp
zumo/zumokit-ios
6981dbeaec723262c400d5b3872ace2e08f17997
[ "MIT" ]
null
null
null
ZumoKit/NativeLibs/universal/include/card_callback.hpp
zumo/zumokit-ios
6981dbeaec723262c400d5b3872ace2e08f17997
[ "MIT" ]
null
null
null
// AUTOGENERATED FILE - DO NOT MODIFY! // This file generated by Djinni from user.djinni #pragma once #include "exceptions.hpp" namespace zumo { struct Card; /** Callback interface used by methods in User class. */ class CardCallback { public: virtual ~CardCallback() {} virtual void on_error(const ::zumo::ZumoKitException & e) = 0; virtual void on_success(const Card & card) = 0; }; } // namespace zumo
18.521739
66
0.697183
zumo
93ca6241ad4d403fa0bc94d84106af5665e3047b
392
cpp
C++
Server/HttpHandlerHolder/HttpHandlerHolder.cpp
Dnnd/tp-http-server
ef76152ac740227c09c6a073aaa5858e36a4b536
[ "MIT" ]
1
2019-02-12T12:45:28.000Z
2019-02-12T12:45:28.000Z
Server/HttpHandlerHolder/HttpHandlerHolder.cpp
Dnnd/tp-http-server
ef76152ac740227c09c6a073aaa5858e36a4b536
[ "MIT" ]
null
null
null
Server/HttpHandlerHolder/HttpHandlerHolder.cpp
Dnnd/tp-http-server
ef76152ac740227c09c6a073aaa5858e36a4b536
[ "MIT" ]
null
null
null
#include <QtNetwork/QTcpSocket> #include "HttpHandlerHolder.h" #include "../HttpHandler/HttpHandler.h" Handler *HttpHandlerHolder::createHandler(QTcpSocket *socket, QObject *parent) const { Handler *handler = new HttpHandler(documentRoot_, socket, parent); return handler; } HttpHandlerHolder::HttpHandlerHolder(QString documentRoot) : documentRoot_{std::move(documentRoot)} { }
28
86
0.772959
Dnnd
93d02202e8fe7f3a088b7b77831cd67cb2d441d9
31
cpp
C++
Inheritance/MyLowestClass.cpp
joshy409/Code-Design-and-Data-Structures
7c095242fe0dc0c6b0319dc07ac4c99b4c6d204f
[ "MIT" ]
null
null
null
Inheritance/MyLowestClass.cpp
joshy409/Code-Design-and-Data-Structures
7c095242fe0dc0c6b0319dc07ac4c99b4c6d204f
[ "MIT" ]
null
null
null
Inheritance/MyLowestClass.cpp
joshy409/Code-Design-and-Data-Structures
7c095242fe0dc0c6b0319dc07ac4c99b4c6d204f
[ "MIT" ]
null
null
null
#include "MyLowestClass.h"
5.166667
26
0.677419
joshy409
93d02a96652b15c9de8bc5a4745afb5ad6d538f2
1,686
cpp
C++
1021.cpp
YukiMuraRindon/LeetcodePractice
3c9f84b677e4bc7be1d6b54009768d25536c4c12
[ "MIT" ]
null
null
null
1021.cpp
YukiMuraRindon/LeetcodePractice
3c9f84b677e4bc7be1d6b54009768d25536c4c12
[ "MIT" ]
null
null
null
1021.cpp
YukiMuraRindon/LeetcodePractice
3c9f84b677e4bc7be1d6b54009768d25536c4c12
[ "MIT" ]
null
null
null
/* 有效括号字符串为空 ("")、"(" + A + ")" 或 A + B,其中 A 和 B 都是有效的括号字符串,+ 代表字符串的连接。例如,"","()","(())()" 和 "(()(()))" 都是有效的括号字符串。 如果有效字符串 S 非空,且不存在将其拆分为 S = A+B 的方法,我们称其为原语(primitive),其中 A 和 B 都是非空有效括号字符串。 给出一个非空有效字符串 S,考虑将其进行原语化分解,使得:S = P_1 + P_2 + ... + P_k,其中 P_i 是有效括号字符串原语。 对 S 进行原语化分解,删除分解中每个原语字符串的最外层括号,返回 S 。   示例 1: 输入:"(()())(())" 输出:"()()()" 解释: 输入字符串为 "(()())(())",原语化分解得到 "(()())" + "(())", 删除每个部分中的最外层括号后得到 "()()" + "()" = "()()()"。 示例 2: 输入:"(()())(())(()(()))" 输出:"()()()()(())" 解释: 输入字符串为 "(()())(())(()(()))",原语化分解得到 "(()())" + "(())" + "(()(()))", 删除每隔部分中的最外层括号后得到 "()()" + "()" + "()(())" = "()()()()(())"。 示例 3: 输入:"()()" 输出:"" 解释: 输入字符串为 "()()",原语化分解得到 "()" + "()", 删除每个部分中的最外层括号后得到 "" + "" = ""。   提示: S.length <= 10000 S[i] 为 "(" 或 ")" S 是一个有效括号字符串 */ #include<iostream> using namespace std; class Solution { public: string removeOuterParentheses(string S) { int num=0; string result=""; int start=1,end=0; for(int i=0;i<S.length();i++){ if(S[i]=='(') num++; else num--; if(num==0){//分解第一部分 end=i;//标记结束位置 result = result + S.substr(start,end-start);//拼接字符串 这里用+=可以明显减少内存消耗 //cout<<start<<" | "<<end<<" | "<<S.substr(start,end-start)<<endl; start=end+2;//继续进行 } } return result; } }; int main(){ Solution s ; s.removeOuterParentheses("(()())(())(()(()))"); return 0; } /* 思路:通过记录括号匹配来进行分解,每当num==0时说明这一段的括号是匹配的,这时把起始位置字符,最终位置字符 中间的串取出来拼接到结果集里面即可 参考了题解 执行结果: 通过 显示详情 执行用时 : 20 ms , 在所有 C++ 提交中击败了 12.51% 的用户 内存消耗 : 48.5 MB , 在所有 C++ 提交中击败了 8.62% 的用户 */
19.37931
112
0.467378
YukiMuraRindon
93d74d5d46700833a72a4416b64d3d05d998fa18
6,856
cpp
C++
ODFAEG/src/odfaeg/Core/utilities.cpp
Mechap/ODFAEG
ad4bf026ee7055aaf168c5a8e3dc57baaaf42e40
[ "Zlib" ]
null
null
null
ODFAEG/src/odfaeg/Core/utilities.cpp
Mechap/ODFAEG
ad4bf026ee7055aaf168c5a8e3dc57baaaf42e40
[ "Zlib" ]
1
2020-02-14T14:19:44.000Z
2020-12-04T17:39:17.000Z
ODFAEG/src/odfaeg/Core/utilities.cpp
Mechap/ODFAEG
ad4bf026ee7055aaf168c5a8e3dc57baaaf42e40
[ "Zlib" ]
2
2021-05-23T13:45:28.000Z
2021-07-24T13:36:13.000Z
#include "../../../include/odfaeg/Core/utilities.h" #include <iostream> #include <filesystem> namespace odfaeg { namespace core { using namespace std; using namespace sf; std::vector<std::string> split(const std::string& stringToBeSplitted, const std::string& delimeter) { std::vector<std::string> splittedString; int startIndex = 0; int endIndex = 0; while( (endIndex = stringToBeSplitted.find(delimeter, startIndex)) < stringToBeSplitted.size() ) { std::string val = stringToBeSplitted.substr(startIndex, endIndex - startIndex); splittedString.push_back(val); startIndex = endIndex + delimeter.size(); } if(startIndex < stringToBeSplitted.size()) { std::string val = stringToBeSplitted.substr(startIndex); splittedString.push_back(val); } return splittedString; } float conversionStringFloat(std::string str) { std::stringstream ss(str); float f; ss >> f; return f; } std::string conversionFloatString(float f) { std::stringstream ss; ss << f; return ss.str(); } Int32 conversionStringInt(std::string str) { std::stringstream ss(str); Int32 i; ss >> i; return i; } std::string conversionUIntString(const unsigned int& ui) { std::stringstream ss; ss << ui; return ss.str(); } std::string conversionIntString(Int32 i) { std::stringstream ss; ss << i; return ss.str(); } Int64 conversionStringLong(std::string str) { std::stringstream ss(str); Int64 i; ss >> i; return i; } sf::Uint64 conversionStringULong(std::string str) { std::stringstream ss(str); sf::Uint64 i; ss >> i; return i; } std::string conversionLongString(Int64 i) { std::stringstream ss; ss << i; return ss.str(); } int conversionStringToHex(std::string str) { return strtoul(str.c_str(), NULL, 16); } void findFiles (std::string keyword, std::vector<std::string>& files, std::string startDir) { #if defined (ODFAEG_SYSTEM_LINUX) if (DIR* current = opendir(startDir.c_str())) { dirent* ent; while ((ent = readdir(current)) != NULL) { if (strcmp(ent->d_name, ".") && strcmp(ent->d_name, "..")) { std::string path(ent->d_name); if (ent->d_type == DT_DIR) { findFiles(keyword, files, path); } else if (path.find(keyword) != std::string::npos) { files.push_back(path); } } } closedir(current); } #else if defined (ODFAEG_SYSTEM_WINDOWS) if (DIR* current = opendir(startDir.c_str())) { dirent* ent; while ((ent = readdir(current)) != NULL) { if (strcmp(ent->d_name, ".") && strcmp(ent->d_name, "..")) { std::string path = startDir + "\\" + std::string(ent->d_name); struct stat st; stat(path.c_str(), &st); //std::cout<<"path : "<<path<<" keyword : "<<keyword<<std::endl; if (S_ISDIR(st.st_mode)) { findFiles(keyword, files, path); } else { std::vector<std::string> parts = split(keyword, " "); for (unsigned int i = 0; i < parts.size(); i++) { if (path.find(parts[i]) != std::string::npos) { bool contains = false; for (unsigned int j = 0; j < files.size() && !contains; j++) { if (files[j] == path) contains = true; } if (!contains) { files.push_back(path); } } } if (keyword == "*") { //path = std::string(ent->d_name); files.push_back(path); } } } } } #endif } bool is_number(const std::string& s) { std::string abs; if (!s.empty() && s.at(0) == '-') { abs = s.substr(1, s.length() - 1); } else { abs = s; } return !abs.empty() && std::find_if(abs.begin(), abs.end(), [](char c) { return !std::isdigit(c); }) == abs.end(); } /// Try to find in the Haystack the Needle - ignore case int findString(const std::string & strHaystack, const std::string & strNeedle) { if(strNeedle > strHaystack) { return false; } int e = 0, indx = -1; for (unsigned int i = 0; i < strHaystack.size(); i++) { if (strHaystack.at(i) == strNeedle.at(e)) { if (e == 0) { indx = i; } e++; if (e == strNeedle.size()) { return indx; } else { e = 0; } } } return -1; } std::string getCurrentPath() { /*char cCurrentPath[FILENAME_MAX]; _getcwd(cCurrentPath,sizeof(cCurrentPath));*/ return std::filesystem::current_path(); } void memmv(void* src, void* dst, size_t size) { char* tmp = new char[size]; char* csrc = (char*) src; char* cdst = (char*) dst; for (unsigned int i = 0; i < size; i++) { tmp[i] = csrc[i]; } for (unsigned int i = 0; i < size; i++) { cdst[i] = tmp[i]; } dst = cdst; delete tmp; } } }
36.468085
108
0.402713
Mechap
93dad0738fb741b34ecb19c95bc2a1b6f8f486cf
14,798
cpp
C++
qtfred/src/ui/dialogs/ShipInitialStatusDialog.cpp
trgswe/fs2open.github.com
a159eba0cebca911ad14a118412fddfe5be8e9f8
[ "Unlicense" ]
null
null
null
qtfred/src/ui/dialogs/ShipInitialStatusDialog.cpp
trgswe/fs2open.github.com
a159eba0cebca911ad14a118412fddfe5be8e9f8
[ "Unlicense" ]
1
2019-02-03T04:53:12.000Z
2019-02-03T04:53:12.000Z
qtfred/src/ui/dialogs/ShipInitialStatusDialog.cpp
trgswe/fs2open.github.com
a159eba0cebca911ad14a118412fddfe5be8e9f8
[ "Unlicense" ]
1
2021-05-31T01:41:35.000Z
2021-05-31T01:41:35.000Z
#include "ShipInitialStatusDialog.h" #include "globalincs/alphacolors.h" #include "ui_ShipInitialStatus.h" #include "object/objectdock.h" #include <globalincs/linklist.h> #include <mission/object.h> #include <ui/util/SignalBlockers.h> #include <QCloseEvent> namespace fso { namespace fred { namespace dialogs { ShipInitialStatusDialog::ShipInitialStatusDialog(QWidget* parent, EditorViewport* viewport, bool multi) : QDialog(parent), ui(new Ui::ShipInitialStatusDialog()), _model(new ShipInitialStatusDialogModel(this, viewport, multi)), _viewport(viewport) { ui->setupUi(this); connect(this, &QDialog::accepted, _model.get(), &ShipInitialStatusDialogModel::apply); connect(this, &QDialog::rejected, _model.get(), &ShipInitialStatusDialogModel::reject); connect(_model.get(), &AbstractDialogModel::modelChanged, this, &ShipInitialStatusDialog::updateUI); // Velocity connect(ui->velocitySpinBox, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged), this, &ShipInitialStatusDialog::velocityChanged); // Dockpoint List connect(ui->dockpointList, &QListWidget::currentItemChanged, this, &ShipInitialStatusDialog::dockChanged); connect(ui->dockeeComboBox, static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged), this, &ShipInitialStatusDialog::dockeeComboChanged); connect(ui->dockeePointComboBox, static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged), this, &ShipInitialStatusDialog::dockeePointChanged); connect(ui->hullSpinBox, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged), this, &ShipInitialStatusDialog::hullChanged); connect(ui->hasShieldCheckBox, &QCheckBox::stateChanged, this, &ShipInitialStatusDialog::hasShieldChanged); connect(ui->shieldHullSpinBox, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged), this, &ShipInitialStatusDialog::shieldHullChanged); connect(ui->forceShieldsCheckBox, &QCheckBox::stateChanged, this, &ShipInitialStatusDialog::forceShieldChanged); connect(ui->shipLockCheckBox, &QCheckBox::stateChanged, this, &ShipInitialStatusDialog::shipLockChanged); connect(ui->weaponLockCheckBox, &QCheckBox::stateChanged, this, &ShipInitialStatusDialog::weaponLockChanged); connect(ui->primaryLockCheckBox, &QCheckBox::stateChanged, this, &ShipInitialStatusDialog::primaryLockChanged); connect(ui->secondaryLockCheckBox, &QCheckBox::stateChanged, this, &ShipInitialStatusDialog::secondaryLockChanged); connect(ui->turretLockCheckBox, &QCheckBox::stateChanged, this, &ShipInitialStatusDialog::turretLockChanged); connect(ui->afterburnerLockCheckBox, &QCheckBox::stateChanged, this, &ShipInitialStatusDialog::afterburnerLockChanged); connect(ui->subsystemList, &QListWidget::currentRowChanged, this, &ShipInitialStatusDialog::subsystemChanged); connect(ui->subIntegritySpinBox, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged), this, &ShipInitialStatusDialog::subIntegrityChanged); connect(ui->cargoEdit, &QLineEdit::editingFinished, this, &ShipInitialStatusDialog::cargoChanged); connect(ui->colourComboBox, static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged), this, &ShipInitialStatusDialog::colourChanged); updateUI(); // Resize the dialog to the minimum size resize(QDialog::sizeHint()); } ShipInitialStatusDialog::~ShipInitialStatusDialog() = default; void ShipInitialStatusDialog::closeEvent(QCloseEvent* event) { if (_model->query_modified()) { auto button = _viewport->dialogProvider->showButtonDialog(DialogType::Question, "Changes detected", "Do you want to keep your changes?", { DialogButton::Yes, DialogButton::No, DialogButton::Cancel }); if (button == DialogButton::Cancel) { event->ignore(); return; } if (button == DialogButton::Yes) { accept(); return; } } QDialog::closeEvent(event); } void ShipInitialStatusDialog::updateUI() { util::SignalBlockers blockers(this); auto value = _model->getVelocity(); if (value != BLANKFIELD) { ui->velocitySpinBox->setValue(value); } else { ui->velocitySpinBox->setSpecialValueText("-"); } value = _model->getHull(); if (value != BLANKFIELD) { ui->hullSpinBox->setValue(value); } else { ui->hullSpinBox->setSpecialValueText("-"); } value = _model->getHasShield(); ui->hasShieldCheckBox->setCheckState(Qt::CheckState(value)); if (_model->getHasShield()) { ui->shieldHullSpinBox->setEnabled(true); } else { ui->shieldHullSpinBox->setEnabled(false); } value = _model->getShieldHull(); if (value != BLANKFIELD) { ui->shieldHullSpinBox->setValue(value); } else { ui->shieldHullSpinBox->setSpecialValueText("-"); } updateFlags(); updateDocks(); updateDockee(); updateSubsystems(); ui->colourComboBox->clear(); if (_model->m_use_teams) { int i = 0; ui->colourComboBox->setEnabled(true); ui->colourComboBox->addItem("none", i); ++i; for (auto& Team_Name : Team_Names) { ui->colourComboBox->addItem(Team_Name.c_str(), i); i++; } auto currentText = _model->getColour(); ui->colourComboBox->setCurrentIndex(ui->colourComboBox->findText(currentText.c_str())); } } void ShipInitialStatusDialog::updateFlags() { auto value = _model->getForceShield(); ui->forceShieldsCheckBox->setCheckState(Qt::CheckState(value)); value = _model->getShipLocked(); ui->shipLockCheckBox->setCheckState(Qt::CheckState(value)); value = _model->getWeaponLocked(); ui->weaponLockCheckBox->setCheckState(Qt::CheckState(value)); value = _model->getPrimariesDisabled(); ui->primaryLockCheckBox->setCheckState(Qt::CheckState(value)); value = _model->getSecondariesDisabled(); ui->secondaryLockCheckBox->setCheckState(Qt::CheckState(value)); value = _model->getTurretsDisabled(); ui->turretLockCheckBox->setCheckState(Qt::CheckState(value)); value = _model->getAfterburnerDisabled(); ui->afterburnerLockCheckBox->setCheckState(Qt::CheckState(value)); } void ShipInitialStatusDialog::updateDocks() { auto index = ui->dockpointList->currentIndex(); ui->dockpointList->clear(); if (!_model->m_multi_edit) { for (int dockpoint = 0; dockpoint < _model->getnum_dock_points(); dockpoint++) { auto newItem = new QListWidgetItem; newItem->setText( model_get_dock_name(Ship_info[Ships[_model->getShip()].ship_info_index].model_num, dockpoint)); newItem->setData(Qt::UserRole, dockpoint); ui->dockpointList->addItem(newItem); } } ui->dockpointList->setCurrentIndex(index); if (cur_docker_point < 0) { // clear the dropdowns list_dockees(-1); list_dockee_points(-1); } else { // populate with all possible dockees list_dockees( model_get_dock_index_type(Ship_info[Ships[_model->getShip()].ship_info_index].model_num, cur_docker_point)); // see if there's a dockee here if (_model->getdockpoint_array()[cur_docker_point].dockee_shipnum >= 0) { // select the dockee ui->dockeeComboBox->setCurrentIndex(ui->dockeeComboBox->findText( Ships[_model->getdockpoint_array()[cur_docker_point].dockee_shipnum].ship_name)); } else { ui->dockeeComboBox->setCurrentIndex(0); } } } void ShipInitialStatusDialog::updateDockee() { if (cur_dockee < 0) { // clear the dropdown list_dockee_points(-1); } else { // populate with dockee points list_dockee_points(cur_dockee); if (_model->getdockpoint_array()[cur_docker_point].dockee_point < 0) { // select the dockpoint dockeePointChanged(0); } // see if there's a dockpoint here if (_model->getdockpoint_array()[cur_docker_point].dockee_point >= 0) { // select the dockpoint ui->dockeePointComboBox->setCurrentIndex(ui->dockeePointComboBox->findText( model_get_dock_name(Ship_info[Ships[cur_dockee].ship_info_index].model_num, _model->getdockpoint_array()[cur_docker_point].dockee_point))); } } } void ShipInitialStatusDialog::list_dockees(int dock_types) { // enable/disable dropdown ui->dockeeComboBox->setEnabled((dock_types >= 0)); // clear the existing dockees ui->dockeeComboBox->clear(); // that might be all we need to do if (dock_types < 0) return; // populate with potential dockees // add "nothing" ui->dockeeComboBox->addItem("Nothing", QVariant(int(-1))); // add ships for (object* objp = GET_FIRST(&obj_used_list); objp != END_OF_LIST(&obj_used_list); objp = GET_NEXT(objp)) { if ((objp->type == OBJ_SHIP) || (objp->type == OBJ_START)) { int ship = get_ship_from_obj(objp); // mustn't be the same ship if (ship == _model->getShip()) { continue; } // mustn't also be docked elsewhere bool docked_elsewhere = false; for (int i = 0; i < _model->getnum_dock_points(); i++) { // don't erroneously check the same point if (i == cur_docker_point) { continue; } // see if this ship is also on a different dockpoint if (_model->getdockpoint_array()[i].dockee_shipnum == ship) { docked_elsewhere = true; break; } } if (docked_elsewhere) { continue; } // docking must be valid if (!ship_docking_valid(_model->getShip(), ship) && !ship_docking_valid(ship, _model->getShip())) { continue; } // dock types must match if (!(model_get_dock_types(Ship_info[Ships[ship].ship_info_index].model_num) & dock_types)) { continue; } // add to list ui->dockeeComboBox->addItem(Ships[ship].ship_name, QVariant(int(ship))); } } } void ShipInitialStatusDialog::list_dockee_points(int shipnum) { ship* shipp = &Ships[_model->getShip()]; ship* other_shipp = &Ships[shipnum]; // enable/disable dropdown ui->dockeePointComboBox->setEnabled((shipnum >= 0)); // clear the existing dockee points ui->dockeePointComboBox->clear(); // that might be all we need to do if (shipnum < 0) { return; } // get the required dock type(s) int dock_type = model_get_dock_index_type(Ship_info[shipp->ship_info_index].model_num, cur_docker_point); // populate with the right kind of dockee points for (int i = 0; i < model_get_num_dock_points(Ship_info[other_shipp->ship_info_index].model_num); i++) { // make sure this dockpoint is not occupied by someone else object* docked_objp = dock_find_object_at_dockpoint(&Objects[other_shipp->objnum], i); if ((docked_objp != nullptr) && (docked_objp != &Objects[shipp->objnum])) continue; // make sure its type matches if (!(model_get_dock_index_type(Ship_info[other_shipp->ship_info_index].model_num, i) & dock_type)) continue; // add to list ui->dockeePointComboBox->addItem(model_get_dock_name(Ship_info[other_shipp->ship_info_index].model_num, i), QVariant(int(i))); } } void ShipInitialStatusDialog::updateSubsystems() { ship_subsys* ptr; auto index = ui->subsystemList->currentIndex(); ui->subsystemList->clear(); if (!_model->m_multi_edit) { ui->subsystemList->setEnabled(true); ui->subIntegritySpinBox->setEnabled(true); if (_model->getShip_has_scannable_subsystems()) { ui->cargoEdit->setEnabled(true); } for (ptr = GET_FIRST(&Ships[_model->getShip()].subsys_list); ptr != END_OF_LIST(&Ships[_model->getShip()].subsys_list); ptr = GET_NEXT(ptr)) { auto newItem = new QListWidgetItem; newItem->setText(ptr->system_info->subobj_name); ui->subsystemList->addItem(newItem); } ui->subsystemList->setCurrentIndex(index); } else { ui->subsystemList->setEnabled(false); ui->subIntegritySpinBox->setEnabled(false); ui->cargoEdit->setEnabled(false); } auto value = _model->getDamage(); ui->subIntegritySpinBox->setValue(value); auto cargovalue = _model->getCargo(); ui->cargoEdit->setText(cargovalue.c_str()); } void ShipInitialStatusDialog::velocityChanged(int value) { _model->setVelocity(value); } void ShipInitialStatusDialog::hullChanged(int value) { _model->setHull(value); } void ShipInitialStatusDialog::hasShieldChanged(int state) { _model->setHasShield(state); } void ShipInitialStatusDialog::shieldHullChanged(int value) { _model->setShieldHull(value); } void ShipInitialStatusDialog::forceShieldChanged(int state) { _model->setForceShield(state); } void ShipInitialStatusDialog::shipLockChanged(int state) { _model->setShipLocked(state); } void ShipInitialStatusDialog::weaponLockChanged(int state) { _model->setWeaponLocked(state); } void ShipInitialStatusDialog::primaryLockChanged(int state) { _model->setPrimariesDisabled(state); } void ShipInitialStatusDialog::secondaryLockChanged(int state) { _model->setSecondariesDisabled(state); } void ShipInitialStatusDialog::turretLockChanged(int state) { _model->setTurretsDisabled(state); } void ShipInitialStatusDialog::afterburnerLockChanged(int state) { _model->setAfterburnerDisabled(state); } void ShipInitialStatusDialog::dockChanged(QListWidgetItem* current) { cur_docker_point = current->data(Qt::UserRole).value<int>(); updateUI(); } void ShipInitialStatusDialog::dockeeComboChanged(int index) { auto dockeeData = ui->dockeeComboBox->itemData(index).value<int>(); cur_dockee = dockeeData; _model->setDockee(cur_docker_point, dockeeData); } void ShipInitialStatusDialog::dockeePointChanged(int index) { auto dockeeData = ui->dockeePointComboBox->itemData(index).value<int>(); cur_dockee_point = dockeeData; _model->setDockeePoint(cur_docker_point, dockeeData); } void ShipInitialStatusDialog::subsystemChanged(int index) { _model->change_subsys(index); } void ShipInitialStatusDialog::subIntegrityChanged(int value) { _model->setDamage(value); } void ShipInitialStatusDialog::cargoChanged() { _model->setCargo(ui->cargoEdit->text().toStdString()); } void ShipInitialStatusDialog::colourChanged(int index) { _model->setColour(ui->colourComboBox->itemText(index).toStdString()); } } // namespace dialogs } // namespace fred } // namespace fso
33.404063
119
0.684755
trgswe
93de8771c2d80df71642549251e05045b038008c
3,595
cpp
C++
Sources/ImageTool.cpp
KTXSoftware/hake
f118e0a902546d3355cb337c29928135c886c3bd
[ "Zlib" ]
2
2017-11-26T22:33:38.000Z
2018-05-11T21:58:38.000Z
Sources/ImageTool.cpp
KTXSoftware/hake
f118e0a902546d3355cb337c29928135c886c3bd
[ "Zlib" ]
null
null
null
Sources/ImageTool.cpp
KTXSoftware/hake
f118e0a902546d3355cb337c29928135c886c3bd
[ "Zlib" ]
null
null
null
#include "ImageTool.h" #include "Files.h" #include "KhaExporter.h" #include "stb_image.h" #include "stb_image_write.h" #include <algorithm> #include <cmath> using namespace kmd; using namespace kake; namespace { typedef unsigned char u8; typedef unsigned int u32; int k_round(float value) { return (int)std::floor(value + 0.5f); } u32 sample(u32* image, int w, int h, float x, float y) { float posx = x * w; float posy = y * h; int xx = (int)posx; int yy = (int)posy; xx = std::min(std::max(0, xx), w - 1); yy = std::min(std::max(0, yy), h - 1); return image[yy * w + xx]; } u32* scale(u32* image, int sw, int sh, int dw, int dh) { u32* data = new u32[dw * dh]; for (int y = 0; y < dh; ++y) { for (int x = 0; x < dw; ++x) { data[y * dw + x] = sample(image, sw, sh, (float)x / (float)dw, (float)y / (float)dh); } } return data; } u8* removeColor(u8* image, int w, int h, int red, int green, int blue) { for (int y = 0; y < h; ++y) { for (int x = 0; x < w; ++x) { if ( image[y * w * 4 + x * 4 + 0] == red && image[y * w * 4 + x * 4 + 1] == green && image[y * w * 4 + x * 4 + 2] == blue ) { image[y * w * 4 + x * 4 + 3] = 0; } } } return image; } } void hake::exportImage(Path from, Path to, Json::Value& asset, bool premultiplyAlpha) { if (!Files::exists(to.parent())) Files::createDirectories(to.parent()); if (!premultiplyAlpha && (!asset.has("scale") || asset["scale"].number() == 1 || asset["scale"].number() == 0) && !asset.has("background")) KhaExporter::copyFile(from, to); else { int w; int h; int comp; u8* image = stbi_load(from.toString().c_str(), &w, &h, &comp, 4); if (image == nullptr) throw std::runtime_error("Could not read image."); if (premultiplyAlpha) { for (int y = 0; y < h; ++y) { for (int x = 0; x < w; ++x) { float alpha = image[y * w * 4 + x * 4 + 3] / 255.0f; image[y * w * 4 + x * 4 + 0] = k_round(image[y * w * 4 + x * 4 + 0] * alpha); image[y * w * 4 + x * 4 + 1] = k_round(image[y * w * 4 + x * 4 + 1] * alpha); image[y * w * 4 + x * 4 + 2] = k_round(image[y * w * 4 + x * 4 + 2] * alpha); } } } if (asset.has("scale") && asset["scale"].number() != 0 && asset["scale"].number() != 1) { image = (u8*)scale((u32*)image, w, h, w * asset["scale"].number(), h * asset["scale"].number()); w *= asset["scale"].number(); h *= asset["scale"].number(); } // BufferedImage outImage = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_4BYTE_ABGR); // Graphics2D g2d = (Graphics2D)outImage.getGraphics(); // if (asset.circle) { // RenderingHints hints = new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); // g2d.addRenderingHints(hints); // g2d.setColor(new Color(1.0f, 1.0f, 1.0f, 0.0f)); // g2d.fillRect(0, 0, image.getWidth(null), image.getHeight(null)); // g2d.setColor(Color.BLACK); // g2d.fillOval(0, 0, image.getWidth(null), image.getHeight(null)); // g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP)); // } // g2d.drawImage(image, 0, 0, null); // g2d.dispose(); if (asset.has("background")) { int red = asset["background"]["red"].number(); int green = asset["background"]["green"].number(); int blue = asset["background"]["blue"].number(); image = removeColor(image, w, h, red, green, blue); } stbi_write_png(to.toString().c_str(), w, h, 4, image, 0); } }
33.598131
174
0.560779
KTXSoftware
93e0e0453873453db5020f9322d933c27702be79
294
cpp
C++
json-parser002/lib/json_exception.cpp
syohex/cpp-study
598c2afbe77c6d4ba88f549d3e99f97b5bf81acb
[ "MIT" ]
null
null
null
json-parser002/lib/json_exception.cpp
syohex/cpp-study
598c2afbe77c6d4ba88f549d3e99f97b5bf81acb
[ "MIT" ]
null
null
null
json-parser002/lib/json_exception.cpp
syohex/cpp-study
598c2afbe77c6d4ba88f549d3e99f97b5bf81acb
[ "MIT" ]
null
null
null
#include "json_exception.h" #include <sstream> JsonException::JsonException(const std::string &message, int line, int column) { std::stringstream ss; ss << message << " at " << line << ':' << column; } const char *JsonException::what() const noexcept { return message_.c_str(); }
24.5
80
0.663265
syohex
93e2b6a988dc7c2161a3339802bf7cc56db7d1d4
1,316
cpp
C++
src/print.cpp
vivkin/jzon
49a7d1d4da166c7570679abaae8a1977f03bb0d4
[ "MIT" ]
7
2015-02-22T20:19:34.000Z
2021-03-08T14:09:02.000Z
src/print.cpp
vivkin/jzon
49a7d1d4da166c7570679abaae8a1977f03bb0d4
[ "MIT" ]
1
2017-08-05T18:49:13.000Z
2017-08-05T18:49:13.000Z
src/print.cpp
vivkin/jzon
49a7d1d4da166c7570679abaae8a1977f03bb0d4
[ "MIT" ]
1
2018-10-06T10:01:43.000Z
2018-10-06T10:01:43.000Z
#include "gason2.h" #include "gason2dump.h" #include <stdio.h> #include <stdlib.h> int main(int argc, char **argv) { if (argc < 2) { fprintf(stderr, "usage: %s [-v] [file ...]\n", argv[0]); exit(EXIT_FAILURE); } bool verbose = false; for (int i = 1; i < argc; ++i) { if (!strcmp(argv[i], "-v") || !strcmp(argv[i], "--verbose")) { verbose = true; continue; } FILE *fp = strcmp(argv[i], "-") ? fopen(argv[i], "rb") : stdin; if (!fp) { perror(argv[i]); exit(EXIT_FAILURE); } gason2::vector<char> src; while (!feof(fp)) { char buf[BUFSIZ]; src.append(buf, fread(buf, 1, sizeof(buf), fp)); } src.push_back('\0'); src.pop_back(); fclose(fp); gason2::document doc; if (doc.parse(src.data())) { gason2::vector<char> buffer; if (verbose) gason2::dump::prettify(buffer, doc); else gason2::dump::stringify(buffer, doc); buffer.push_back('\0'); buffer.pop_back(); printf("%s\n", buffer.begin()); } else { gason2::dump::print_error(argv[i], src.data(), doc); } } return 0; }
25.803922
71
0.461246
vivkin
93e4fff45d18e9041286d94ef47ed3d8ef9d7ed8
2,676
cpp
C++
src/emulator/Debugger.cpp
Wycube/Fish-8
b68b78ce348232364862b8df9737066d02ddfcd2
[ "MIT" ]
null
null
null
src/emulator/Debugger.cpp
Wycube/Fish-8
b68b78ce348232364862b8df9737066d02ddfcd2
[ "MIT" ]
null
null
null
src/emulator/Debugger.cpp
Wycube/Fish-8
b68b78ce348232364862b8df9737066d02ddfcd2
[ "MIT" ]
null
null
null
#include "Debugger.hpp" #include <fmt/printf.h> namespace fish { static std::array<const char*, 35> mnemonics = { "NOP/SYS", "CLS", "RET", "JP %03X", "CALL %03X", "SE V%X, %i", "SNE V%X, %i", "SE V%X, V%X", "LD V%X, %i", "ADD V%X, %i", "LD V%X, V%X", "OR V%X, V%X", "AND V%X, V%X", "XOR V%X, V%X", "ADD V%X, V%X", "SUB V%X, V%X", "SHR V%X", "SUBN V%X, V%X", "SHL V%X", "SNE V%X, V%X", "LD I, %03X", "JP V0, %03X", "RND V%X, %02X", "DRW V%X, V%X, %i", "SKP V%X", "SKNP V%X", "LD V%X, DT", "LD V%X, Key", "LD DT, V%X", "LD ST, V%X", "ADD I, V%X", "LD F, V%X", "LD B, V%X", "LD [I], V%X", "LD V%X, [I]" }; bool Debugger::attach(Chip8 &emu) { if(m_instance == nullptr) { m_instance = &emu; } else { return false; } return true; } bool Debugger::detach() { if(m_instance != nullptr) { m_instance = nullptr; } else { return false; } return true; } bool Debugger::hasInstance() const { return m_instance != nullptr; } uint8_t* Debugger::getMemory() { return m_instance->m_mem; } uint16_t* Debugger::getStack() { return m_instance->m_stack; } uint8_t* Debugger::getScreen() { return m_instance->m_screen; } uint8_t* Debugger::getVRegister(size_t index) { return &m_instance->m_regs.V[index]; } uint8_t* Debugger::getStackPointer() { return &m_instance->m_regs.SP; } uint16_t* Debugger::getIRegister() { return &m_instance->m_regs.I; } uint16_t* Debugger::getProgramCounter() { return &m_instance->m_regs.PC; } uint8_t* Debugger::getDelayTimer() { return &m_instance->m_regs.DT; } uint8_t* Debugger::getSoundTimer() { return &m_instance->m_regs.ST; } uint16_t Debugger::getInstructionAt(uint16_t address) { uint8_t high = m_instance->m_mem[address]; uint8_t low = m_instance->m_mem[address + 1]; return (high << 8) | low; } std::string Debugger::disassemble(uint16_t instruction) { m_interpreter.decode(instruction); uint16_t a, b, c; //Parameters a = m_interpreter.m_operands >> 8; b = m_interpreter.m_operands >> 4 & 0xf; c = m_interpreter.m_operands & 0xf; switch(m_interpreter.m_opcode) { case 3 : case 4 : a = m_interpreter.m_operands; break; case 5 : case 6 : case 8 : case 9 : case 22: b = m_interpreter.m_operands & 0xff; break; case 20: case 21: b = m_interpreter.m_operands; break; } return fmt::sprintf(mnemonics[m_interpreter.m_opcode], a, b, c); } }
23.068966
70
0.55867
Wycube
93e6aac3365d5663d9ad3b0304756150227009bc
319
hpp
C++
addons/headgear/script_component.hpp
JeffPerk/HavocTeam
6fb616c41da4baece79ebac941bac72a78c715f9
[ "MIT" ]
null
null
null
addons/headgear/script_component.hpp
JeffPerk/HavocTeam
6fb616c41da4baece79ebac941bac72a78c715f9
[ "MIT" ]
7
2021-11-22T04:36:52.000Z
2021-12-13T18:55:24.000Z
addons/headgear/script_component.hpp
JeffPerk/HavocTeam
6fb616c41da4baece79ebac941bac72a78c715f9
[ "MIT" ]
null
null
null
#define COMPONENT headgear #define COMPONENT_BEAUTIFIED Headgear #include "\z\havoc\addons\main\script_mod.hpp" #ifdef DEBUG_ENABLED_HEADGEAR #define DEBUG_MODE_FULL #endif #ifdef DEBUG_SETTINGS_HEADGEAR #define DEBUG_SETTINGS DEBUG_SETTINGS_HEADGEAR #endif #include "\z\havoc\addons\main\script_macros.hpp"
22.785714
50
0.818182
JeffPerk
93e7ae288beea19aca824c6dbce2618bf13c0008
5,360
cc
C++
src/preproc/do_prover3.cc
nerdling/SBSAT
6328c6aa105b75693d06bf0dae4a3b5ca220318b
[ "Unlicense" ]
4
2015-03-08T07:56:29.000Z
2017-10-12T04:19:27.000Z
src/preproc/do_prover3.cc
nerdling/SBSAT
6328c6aa105b75693d06bf0dae4a3b5ca220318b
[ "Unlicense" ]
null
null
null
src/preproc/do_prover3.cc
nerdling/SBSAT
6328c6aa105b75693d06bf0dae4a3b5ca220318b
[ "Unlicense" ]
null
null
null
/* =========FOR INTERNAL USE ONLY. NO DISTRIBUTION PLEASE ========== */ /********************************************************************* Copyright 1999-2007, University of Cincinnati. All rights reserved. By using this software the USER indicates that he or she has read, understood and will comply with the following: --- University of Cincinnati hereby grants USER nonexclusive permission to use, copy and/or modify this software for internal, noncommercial, research purposes only. Any distribution, including commercial sale or license, of this software, copies of the software, its associated documentation and/or modifications of either is strictly prohibited without the prior consent of University of Cincinnati. Title to copyright to this software and its associated documentation shall at all times remain with University of Cincinnati. Appropriate copyright notice shall be placed on all software copies, and a complete copy of this notice shall be included in all copies of the associated documentation. No right is granted to use in advertising, publicity or otherwise any trademark, service mark, or the name of University of Cincinnati. --- This software and any associated documentation is provided "as is" UNIVERSITY OF CINCINNATI MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED, INCLUDING THOSE OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, OR THAT USE OF THE SOFTWARE, MODIFICATIONS, OR ASSOCIATED DOCUMENTATION WILL NOT INFRINGE ANY PATENTS, COPYRIGHTS, TRADEMARKS OR OTHER INTELLECTUAL PROPERTY RIGHTS OF A THIRD PARTY. University of Cincinnati shall not be liable under any circumstances for any direct, indirect, special, incidental, or consequential damages with respect to any claim by USER or any third party on account of or arising from the use, or inability to use, this software or its associated documentation, even if University of Cincinnati has been advised of the possibility of those damages. *********************************************************************/ #include "sbsat.h" #include "sbsat_preproc.h" int size = 10; int Do_Prover3() { if(formatin != '3') return PREP_NO_CHANGE; dX_printf(3, "RECOMPUTING PROVER %d - \n", size); str_length = 0; bool OLD_DO_INFERENCES = DO_INFERENCES; DO_INFERENCES = 0; Pos_replace = Neg_replace = Setting_Pos = Setting_Neg = 0; /****** DELETING ARRAYS ********/ ite_free((void**)&original_functionType); ite_free((void**)&original_equalityVble); ite_free((void**)&original_functions); for (int x = 0; x < numinp + 1; x++) { llist *k = amount[x].head; while (k != NULL) { llist *temp = k; k = k->next; delete temp; } amount[x].head = NULL; amount[x].tail = NULL; } free(amount); ite_free((void**)&num_funcs_var_occurs); for (int x = 0; x < nmbrFunctions; x++) { if (variables[x].num != NULL) delete [] variables[x].num; } ite_free((void **)&variables); variables_size = 0; ite_free((void **)&length); length_size = 0; Delete_Repeats(); for(int x = 1; x < numinp + 1; x++) if(independantVars[x] == 2) { variablelist[x].true_false = -1; variablelist[x].equalvars = 0; } /****** DONE DELETING ARRAYS ********/ //Grabbing new prover3 BDDS nmbrFunctions = 0; prover3_max_vars = size; void p3_done(); p3_done(); //Saving Inferences. int old_numinp = numinp; delete l; numinp = getNuminp(); F = numinp+3; T = numinp+2; l = new Equiv (numinp + 1, nmbrFunctions, T, F); numinp = old_numinp; CreateInferences(); numinp = getNuminp(); ite_free((void **)&variablelist); /****** REALLOCATING ARRAYS *********/ variablelist = new varinfo[numinp + 1]; for (int x = 0; x < numinp + 1; x++) { variablelist[x].equalvars = 0; variablelist[x].replace = x; variablelist[x].true_false = -1; } ITE_NEW_CATCH(original_functions = new BDDNode *[nmbrFunctions + 1], "original functions"); original_functionType = (int *)ite_calloc(nmbrFunctions + 1, sizeof(int), 2, "original functionType"); original_equalityVble = (int *)ite_calloc(nmbrFunctions + 1, sizeof(int), 2, "original equalityVble"); for(int x = 0; x < nmbrFunctions; x++) { original_functions[x] = functions[x]; original_functionType[x] = functionType[x]; original_equalityVble[x] = equalityVble[x]; } original_numout = nmbrFunctions; length = (int *)ite_recalloc(NULL, 0, nmbrFunctions, sizeof(int), 9, "length"); length_size = nmbrFunctions; variables = (store *)ite_recalloc(NULL, 0, nmbrFunctions, sizeof(store), 9, "variables"); variables_size = nmbrFunctions; num_funcs_var_occurs = (int *)ite_calloc(numinp+1, sizeof(int), 9, "num_funcs_var_occurs"); amount = (llistStruct*)calloc(numinp+1, sizeof(llistStruct)); /****** DONE REALLOCATING ARRAYS ******/ /****** INITIALIZING ARRAYS ***********/ Init_Repeats(); for (int x = 0; x < nmbrFunctions; x++) { int r=Rebuild_BDDx(x); switch (r) { case TRIV_UNSAT: case TRIV_SAT: case PREP_ERROR: return r; default: break; } } /****** DONE INITIALIZING ARRAYS ******/ DO_INFERENCES = OLD_DO_INFERENCES; switch (int r=Do_Apply_Inferences()) { case TRIV_UNSAT: case TRIV_SAT: case PREP_ERROR: return r; default: break; } dX_printf(3, "\n"); d2e_printf1("\r "); int ret = PREP_NO_CHANGE; return ret; }
32.883436
103
0.680597
nerdling
93e9737656bf1132822675a1768fcf7337a24b42
24,512
hh
C++
src/yajlpp.hh
emilianobonassi/lnav
37f46af7a691192fba4a889e4e4da6cbfcaac8e4
[ "BSD-2-Clause" ]
null
null
null
src/yajlpp.hh
emilianobonassi/lnav
37f46af7a691192fba4a889e4e4da6cbfcaac8e4
[ "BSD-2-Clause" ]
null
null
null
src/yajlpp.hh
emilianobonassi/lnav
37f46af7a691192fba4a889e4e4da6cbfcaac8e4
[ "BSD-2-Clause" ]
null
null
null
/** * Copyright (c) 2013, Timothy Stack * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of Timothy Stack 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 REGENTS 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 REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * @file yajlpp.hh */ #ifndef _yajlpp_hh #define _yajlpp_hh #include <string.h> #include <stdarg.h> #include <limits.h> #include <map> #include <set> #include <stack> #include <vector> #include <string> #include <algorithm> #include "optional.hpp" #include "pcrepp.hh" #include "json_ptr.hh" #include "intern_string.hh" #include "yajl/api/yajl_parse.h" #include "yajl/api/yajl_gen.h" inline yajl_gen_status yajl_gen_pstring(yajl_gen hand, const char *str, size_t len) { if (len == (size_t)-1) { len = strlen(str); } return yajl_gen_string(hand, (const unsigned char *)str, len); } inline yajl_gen_status yajl_gen_string(yajl_gen hand, const std::string &str) { return yajl_gen_string(hand, (const unsigned char *)str.c_str(), str.length()); } template<typename T> inline T *nullobj() { return (T *) NULL; } struct json_path_handler; class yajlpp_gen_context; class json_schema_validator; class yajlpp_parse_context; struct yajlpp_provider_context { pcre_extractor ypc_extractor; int ypc_index; template<typename T> intern_string_t get_substr_i(T name) const { pcre_context::iterator cap = this->ypc_extractor.pe_context[name]; char path[cap->length() + 1]; size_t len = json_ptr::decode(path, this->ypc_extractor.pe_input.get_substr_start(cap), cap->length()); return intern_string::lookup(path, len); }; template<typename T> std::string get_substr(T name) const { pcre_context::iterator cap = this->ypc_extractor.pe_context[name]; char path[cap->length() + 1]; size_t len = json_ptr::decode(path, this->ypc_extractor.pe_input.get_substr_start(cap), cap->length()); return std::string(path, len); }; }; struct json_path_handler_base { typedef std::pair<const char *, int> enum_value_t; static const enum_value_t ENUM_TERMINATOR; json_path_handler_base(const char *path) : jph_path(path), jph_regex(path, PCRE_ANCHORED), jph_gen_callback(NULL), jph_obj_provider(NULL), jph_path_provider(NULL), jph_synopsis(""), jph_description(""), jph_simple_offset(NULL), jph_children(NULL), jph_kv_pair(false), jph_min_length(0), jph_max_length(INT_MAX), jph_enum_values(NULL), jph_min_value(LLONG_MIN), jph_optional_wrapper(false) { memset(&this->jph_callbacks, 0, sizeof(this->jph_callbacks)); }; virtual yajl_gen_status gen(yajlpp_gen_context &ygc, yajl_gen handle) const; virtual void possibilities(std::vector<std::string> &dst, void *root = NULL, const std::string &base = "") const; const char * jph_path; pcrepp jph_regex; yajl_callbacks jph_callbacks; yajl_gen_status (*jph_gen_callback)(yajlpp_gen_context &, const json_path_handler_base &, yajl_gen); void (*jph_validator)(yajlpp_parse_context &ypc, const json_path_handler_base &jph); void *(*jph_obj_provider)(const yajlpp_provider_context &pe, void *root); void (*jph_path_provider)(void *root, std::vector<std::string> &paths_out); const char * jph_synopsis; const char * jph_description; void * jph_simple_offset; json_path_handler_base *jph_children; bool jph_kv_pair; std::shared_ptr<pcrepp> jph_pattern; size_t jph_min_length; size_t jph_max_length; const enum_value_t *jph_enum_values; long long jph_min_value; bool jph_optional_wrapper; }; int yajlpp_static_string(yajlpp_parse_context *, const unsigned char *, size_t); int yajlpp_static_string_vector(yajlpp_parse_context *, const unsigned char *, size_t); int yajlpp_static_intern_string(yajlpp_parse_context *, const unsigned char *, size_t); int yajlpp_static_enum(yajlpp_parse_context *, const unsigned char *, size_t); yajl_gen_status yajlpp_static_gen_string(yajlpp_gen_context &ygc, const json_path_handler_base &, yajl_gen); yajl_gen_status yajlpp_static_gen_string_vector(yajlpp_gen_context &ygc, const json_path_handler_base &, yajl_gen); void yajlpp_validator_for_string(yajlpp_parse_context &ypc, const json_path_handler_base &jph); void yajlpp_validator_for_string_vector(yajlpp_parse_context &ypc, const json_path_handler_base &jph); void yajlpp_validator_for_intern_string(yajlpp_parse_context &ypc, const json_path_handler_base &jph); void yajlpp_validator_for_int(yajlpp_parse_context &ypc, const json_path_handler_base &jph); void yajlpp_validator_for_double(yajlpp_parse_context &ypc, const json_path_handler_base &jph); template<typename T> int yajlpp_static_number(yajlpp_parse_context *ypc, long long num); int yajlpp_static_decimal(yajlpp_parse_context *, double); int yajlpp_static_bool(yajlpp_parse_context *, int); yajl_gen_status yajlpp_static_gen_bool(yajlpp_gen_context &ygc, const json_path_handler_base &, yajl_gen); struct json_path_handler : public json_path_handler_base { json_path_handler(const char *path, int(*null_func)(yajlpp_parse_context *)) : json_path_handler_base(path) { this->jph_callbacks.yajl_null = (int (*)(void *))null_func; }; json_path_handler(const char *path, int(*bool_func)(yajlpp_parse_context *, int)) : json_path_handler_base(path) { this->jph_callbacks.yajl_boolean = (int (*)(void *, int))bool_func; } json_path_handler(const char *path, int(*int_func)(yajlpp_parse_context *, long long)) : json_path_handler_base(path) { this->jph_callbacks.yajl_integer = (int (*)(void *, long long))int_func; } json_path_handler(const char *path, int(*double_func)(yajlpp_parse_context *, double)) : json_path_handler_base(path) { this->jph_callbacks.yajl_double = (int (*)(void *, double))double_func; } json_path_handler(const char *path, int(*str_func)(yajlpp_parse_context *, const unsigned char *, size_t)) : json_path_handler_base(path) { this->jph_callbacks.yajl_string = (int (*)(void *, const unsigned char *, size_t))str_func; } json_path_handler(const char *path) : json_path_handler_base(path) { }; json_path_handler() : json_path_handler_base("") {}; json_path_handler &add_cb(int(*null_func)(yajlpp_parse_context *)) { this->jph_callbacks.yajl_null = (int (*)(void *))null_func; return *this; }; json_path_handler &add_cb(int(*bool_func)(yajlpp_parse_context *, int)) { this->jph_callbacks.yajl_boolean = (int (*)(void *, int))bool_func; return *this; } json_path_handler &add_cb(int(*int_func)(yajlpp_parse_context *, long long)) { this->jph_callbacks.yajl_integer = (int (*)(void *, long long))int_func; return *this; } json_path_handler &add_cb(int(*double_func)(yajlpp_parse_context *, double)) { this->jph_callbacks.yajl_double = (int (*)(void *, double))double_func; return *this; } json_path_handler &add_cb(int(*str_func)(yajlpp_parse_context *, const unsigned char *, size_t)) { this->jph_callbacks.yajl_string = (int (*)(void *, const unsigned char *, size_t))str_func; return *this; } json_path_handler &with_synopsis(const char *synopsis) { this->jph_synopsis = synopsis; return *this; } json_path_handler &with_description(const char *description) { this->jph_description = description; return *this; } json_path_handler &with_min_length(size_t len) { this->jph_min_length = len; return *this; } json_path_handler &with_max_length(size_t len) { this->jph_max_length = len; return *this; } json_path_handler &with_enum_values(const enum_value_t values[]) { this->jph_enum_values = values; return *this; } json_path_handler &with_pattern(const char *re) { this->jph_pattern.reset(new pcrepp(re)); return *this; }; json_path_handler &with_min_value(long long val) { this->jph_min_value = val; return *this; } template<typename R, typename T> json_path_handler &with_obj_provider(R *(*provider)(const yajlpp_provider_context &pc, T *root)) { this->jph_obj_provider = (void *(*)(const yajlpp_provider_context &, void *)) provider; return *this; }; template<typename T> json_path_handler &with_path_provider(void (*provider)(T *root, std::vector<std::string> &paths_out)) { this->jph_path_provider = (void (*)(void *, std::vector<std::string> &)) provider; return *this; } json_path_handler &for_field(std::string *field) { this->add_cb(yajlpp_static_string); this->jph_simple_offset = field; this->jph_gen_callback = yajlpp_static_gen_string; this->jph_validator = yajlpp_validator_for_string; return *this; }; json_path_handler &for_field(std::vector<std::string> *field) { this->add_cb(yajlpp_static_string_vector); this->jph_simple_offset = field; return *this; }; json_path_handler &for_field(intern_string_t *field) { this->add_cb(yajlpp_static_intern_string); this->jph_simple_offset = field; this->jph_gen_callback = yajlpp_static_gen_string; this->jph_validator = yajlpp_validator_for_intern_string; return *this; }; json_path_handler &for_field(std::map<std::string, std::string> *field) { this->add_cb(yajlpp_static_string); this->jph_kv_pair = true; this->jph_simple_offset = field; this->jph_gen_callback = yajlpp_static_gen_string; this->jph_validator = yajlpp_validator_for_string; return *this; }; json_path_handler &for_field(std::map<std::string, std::vector<std::string>> *field) { this->add_cb(yajlpp_static_string_vector); this->jph_kv_pair = true; this->jph_simple_offset = field; this->jph_gen_callback = yajlpp_static_gen_string_vector; this->jph_validator = yajlpp_validator_for_string_vector; return *this; }; template<typename T> json_path_handler &for_enum(T *field) { this->add_cb(yajlpp_static_enum); this->jph_simple_offset = field; this->jph_gen_callback = yajlpp_static_gen_string; return *this; }; template<typename T, typename T2 = typename std::enable_if<std::is_arithmetic<T>::value>::type> json_path_handler &for_field(T *field) { this->add_cb(yajlpp_static_number<T>); this->jph_simple_offset = field; this->jph_validator = yajlpp_validator_for_int; return *this; }; json_path_handler &for_field(double *field) { this->add_cb(yajlpp_static_decimal); this->jph_simple_offset = field; this->jph_validator = yajlpp_validator_for_double; return *this; }; json_path_handler &for_field(bool *field) { this->add_cb(yajlpp_static_bool); this->jph_simple_offset = field; this->jph_gen_callback = yajlpp_static_gen_bool; return *this; }; template<typename T> json_path_handler &for_field(nonstd::optional<T> *field) { T dummy; this->for_field(&dummy); this->jph_simple_offset = field; this->jph_optional_wrapper = true; return *this; }; json_path_handler &with_children(json_path_handler *children) { require(this->jph_path[strlen(this->jph_path) - 1] == '/'); this->jph_children = children; return *this; }; }; class yajlpp_parse_context { public: typedef void (*error_reporter_t)(const yajlpp_parse_context &ypc, const char *msg); yajlpp_parse_context(const std::string &source, struct json_path_handler *handlers = NULL) : ypc_source(source), ypc_line_number(1), ypc_handlers(handlers), ypc_userdata(NULL), ypc_handle(NULL), ypc_json_text(NULL), ypc_ignore_unused(false), ypc_sibling_handlers(nullptr), ypc_current_handler(nullptr), ypc_error_reporter(nullptr) { this->ypc_path.reserve(4096); this->ypc_path.push_back('\0'); this->ypc_callbacks = DEFAULT_CALLBACKS; memset(&this->ypc_alt_callbacks, 0, sizeof(this->ypc_alt_callbacks)); }; const char *get_path_fragment(int offset, char *frag_in, size_t &len_out) const { const char *retval; size_t start, end; if (offset < 0) { offset = this->ypc_path_index_stack.size() + offset; } start = this->ypc_path_index_stack[offset] + 1; if ((offset + 1) < (int)this->ypc_path_index_stack.size()) { end = this->ypc_path_index_stack[offset + 1]; } else { end = this->ypc_path.size() - 1; } if (this->ypc_handlers != NULL) { len_out = json_ptr::decode(frag_in, &this->ypc_path[start], end - start); retval = frag_in; } else { retval = &this->ypc_path[start]; len_out = end - start; } return retval; } const intern_string_t get_path_fragment_i(int offset) const { char fragbuf[this->ypc_path.size()]; const char *frag; size_t len; frag = this->get_path_fragment(offset, fragbuf, len); return intern_string::lookup(frag, len); }; std::string get_path_fragment(int offset) const { char fragbuf[this->ypc_path.size()]; const char *frag; size_t len; frag = this->get_path_fragment(offset, fragbuf, len); return std::string(frag, len); }; const intern_string_t get_path() const { return intern_string::lookup(&this->ypc_path[1], this->ypc_path.size() - 2); }; bool is_level(size_t level) const { return this->ypc_path_index_stack.size() == level; }; yajlpp_parse_context &set_path(const std::string &path) { this->ypc_path.resize(path.size() + 1); std::copy(path.begin(), path.end(), this->ypc_path.begin()); this->ypc_path[path.size()] = '\0'; for (size_t lpc = 0; lpc < path.size(); lpc++) { switch (path[lpc]) { case '/': this->ypc_path_index_stack.push_back(lpc); break; } } return *this; } void reset(struct json_path_handler *handlers) { this->ypc_handlers = handlers; this->ypc_path.clear(); this->ypc_path.push_back('\0'); this->ypc_path_index_stack.clear(); this->ypc_array_index.clear(); this->ypc_callbacks = DEFAULT_CALLBACKS; memset(&this->ypc_alt_callbacks, 0, sizeof(this->ypc_alt_callbacks)); this->ypc_sibling_handlers = nullptr; this->ypc_current_handler = nullptr; while (!this->ypc_obj_stack.empty()) { this->ypc_obj_stack.pop(); } } void set_static_handler(struct json_path_handler &jph) { this->ypc_path.clear(); this->ypc_path.push_back('\0'); this->ypc_path_index_stack.clear(); this->ypc_array_index.clear(); if (jph.jph_callbacks.yajl_null != NULL) this->ypc_callbacks.yajl_null = jph.jph_callbacks.yajl_null; if (jph.jph_callbacks.yajl_boolean != NULL) this->ypc_callbacks.yajl_boolean = jph.jph_callbacks.yajl_boolean; if (jph.jph_callbacks.yajl_integer != NULL) this->ypc_callbacks.yajl_integer = jph.jph_callbacks.yajl_integer; if (jph.jph_callbacks.yajl_double != NULL) this->ypc_callbacks.yajl_double = jph.jph_callbacks.yajl_double; if (jph.jph_callbacks.yajl_string != NULL) this->ypc_callbacks.yajl_string = jph.jph_callbacks.yajl_string; } template<typename T> yajlpp_parse_context &with_obj(T &obj) { this->ypc_obj_stack.push(&obj); return *this; }; yajlpp_parse_context &with_handle(yajl_handle handle) { this->ypc_handle = handle; return *this; }; yajlpp_parse_context &with_error_reporter(error_reporter_t err) { this->ypc_error_reporter = err; return *this; } yajlpp_parse_context &with_ignore_unused(bool ignore) { this->ypc_ignore_unused = ignore; return *this; } yajl_status parse(const unsigned char *jsonText, size_t jsonTextLen) { this->ypc_json_text = jsonText; yajl_status retval = yajl_parse(this->ypc_handle, jsonText, jsonTextLen); size_t consumed = yajl_get_bytes_consumed(this->ypc_handle); this->ypc_line_number += std::count(&jsonText[0], &jsonText[consumed], '\n'); this->ypc_json_text = NULL; return retval; }; int get_line_number() const { if (this->ypc_handle != NULL && this->ypc_json_text) { size_t consumed = yajl_get_bytes_consumed(this->ypc_handle); long current_count = std::count(&this->ypc_json_text[0], &this->ypc_json_text[consumed], '\n'); return this->ypc_line_number + current_count; } else { return this->ypc_line_number; } }; yajl_status complete_parse() { return yajl_complete_parse(this->ypc_handle); }; void report_error(const char *format, ...) { va_list args; va_start(args, format); if (this->ypc_error_reporter != NULL) { char buffer[1024]; vsnprintf(buffer, sizeof(buffer), format, args); this->ypc_error_reporter(*this, buffer); } va_end(args); } const std::string ypc_source; int ypc_line_number; struct json_path_handler *ypc_handlers; void * ypc_userdata; std::stack<void *> ypc_obj_stack; yajl_handle ypc_handle; const unsigned char * ypc_json_text; yajl_callbacks ypc_callbacks; yajl_callbacks ypc_alt_callbacks; std::vector<char> ypc_path; std::vector<size_t> ypc_path_index_stack; std::vector<int> ypc_array_index; pcre_context_static<30> ypc_pcre_context; bool ypc_ignore_unused; const struct json_path_handler_base *ypc_sibling_handlers; const struct json_path_handler_base *ypc_current_handler; std::set<std::string> ypc_active_paths; error_reporter_t ypc_error_reporter; void update_callbacks(const json_path_handler_base *handlers = NULL, int child_start = 0); private: static const yajl_callbacks DEFAULT_CALLBACKS; int index_for_provider() const { return this->ypc_array_index.empty() ? -1 : this->ypc_array_index.back(); }; static int map_start(void *ctx); static int map_key(void *ctx, const unsigned char *key, size_t len); static int map_end(void *ctx); static int array_start(void *ctx); static int array_end(void *ctx); static int handle_unused(void *ctx); }; class yajlpp_generator { public: yajlpp_generator(yajl_gen handle) : yg_handle(handle) { }; void operator()(const std::string &str) { yajl_gen_string(this->yg_handle, str); }; void operator()(const char *str) { yajl_gen_string(this->yg_handle, (const unsigned char *)str, strlen(str)); }; void operator()(const char *str, size_t len) { yajl_gen_string(this->yg_handle, (const unsigned char *)str, len); }; void operator()(long long value) { yajl_gen_integer(this->yg_handle, value); }; void operator()(bool value) { yajl_gen_bool(this->yg_handle, value); }; void operator()() { yajl_gen_null(this->yg_handle); }; private: yajl_gen yg_handle; }; class yajlpp_container_base { public: yajlpp_container_base(yajl_gen handle) : gen(handle), ycb_handle(handle) {}; yajlpp_generator gen; protected: yajl_gen ycb_handle; }; class yajlpp_map : public yajlpp_container_base { public: yajlpp_map(yajl_gen handle) : yajlpp_container_base(handle) { yajl_gen_map_open(handle); }; ~yajlpp_map() { yajl_gen_map_close(this->ycb_handle); }; }; class yajlpp_array : public yajlpp_container_base { public: yajlpp_array(yajl_gen handle) : yajlpp_container_base(handle) { yajl_gen_array_open(handle); }; ~yajlpp_array() { yajl_gen_array_close(this->ycb_handle); }; }; class yajlpp_gen_context { public: yajlpp_gen_context(yajl_gen handle, json_path_handler *handlers) : ygc_handle(handle), ygc_depth(0), ygc_handlers(handlers) { }; template<typename T> yajlpp_gen_context &with_default_obj(T &obj) { this->ygc_default_stack.push(&obj); return *this; }; template<typename T> yajlpp_gen_context &with_obj(T &obj) { this->ygc_obj_stack.push(&obj); return *this; }; yajlpp_gen_context &with_context(yajlpp_parse_context &ypc) { this->ygc_obj_stack = ypc.ypc_obj_stack; this->ygc_base_name = ypc.get_path_fragment(-1); return *this; } void gen() { yajlpp_map root(this->ygc_handle); for (int lpc = 0; this->ygc_handlers[lpc].jph_path[0]; lpc++) { json_path_handler &jph = this->ygc_handlers[lpc]; jph.gen(*this, this->ygc_handle); } }; yajl_gen ygc_handle; int ygc_depth; std::stack<void *> ygc_default_stack; std::stack<void *> ygc_obj_stack; std::string ygc_base_name; json_path_handler *ygc_handlers; }; #define JSON_SUBTYPE 74 /* Ascii for "J" */ struct json_string { json_string(yajl_gen_t *gen) { const unsigned char *buf; yajl_gen_get_buf(gen, &buf, &this->js_len); this->js_content = (const unsigned char *) malloc(this->js_len); memcpy((void *) this->js_content, buf, this->js_len); }; const unsigned char *js_content; size_t js_len; }; #endif
33.03504
111
0.638014
emilianobonassi
93ed52711b43e56b8f78459b4daf2c40f084e15d
279
cc
C++
ch06/ex6_9_fact_main.cc
bashell/Cpp-Primer
405c5c43edc4bc734ee2a445b7a1f135e33c7f2b
[ "Apache-2.0" ]
null
null
null
ch06/ex6_9_fact_main.cc
bashell/Cpp-Primer
405c5c43edc4bc734ee2a445b7a1f135e33c7f2b
[ "Apache-2.0" ]
null
null
null
ch06/ex6_9_fact_main.cc
bashell/Cpp-Primer
405c5c43edc4bc734ee2a445b7a1f135e33c7f2b
[ "Apache-2.0" ]
null
null
null
// factMain.cc #include <iostream> #include "ex6_8.h" using std::cin; using std::cout; using std::endl; int main() { int val; cout << "Input a integer: " << endl; cin >> val; cout << "The factorial of " << val << " is " << MyFact(val) << endl; return 0; }
15.5
72
0.55914
bashell
93f1d21d4a7702cbbda371ba6e6e69df9974ccad
647
cpp
C++
144_preorderTraversal.cpp
imxiaobo/leetcode-solutions
a59c4c9fa424787771c8faca7ba444cae4ed6a4e
[ "MIT" ]
null
null
null
144_preorderTraversal.cpp
imxiaobo/leetcode-solutions
a59c4c9fa424787771c8faca7ba444cae4ed6a4e
[ "MIT" ]
null
null
null
144_preorderTraversal.cpp
imxiaobo/leetcode-solutions
a59c4c9fa424787771c8faca7ba444cae4ed6a4e
[ "MIT" ]
null
null
null
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: vector<int> preorderTraversal(TreeNode *root) { std::stack<TreeNode *> stack; std::vector<int> preorder; if (root) { stack.push(root); while (!stack.empty()) { TreeNode *t = stack.top(); stack.pop(); if (t->right) stack.push(t->right); if (t->left) stack.push(t->left); preorder.push_back(t->val); } } return preorder; } };
21.566667
59
0.528594
imxiaobo
93f20a846ff5f1ef0cc4db5e03fa676b9a79a707
6,062
cpp
C++
tests/matrices.cpp
pdm-pcb/pdmath
6c8ac4288c68bbe547e71f5bb7d1e44d3f1e35ab
[ "MIT" ]
null
null
null
tests/matrices.cpp
pdm-pcb/pdmath
6c8ac4288c68bbe547e71f5bb7d1e44d3f1e35ab
[ "MIT" ]
null
null
null
tests/matrices.cpp
pdm-pcb/pdmath
6c8ac4288c68bbe547e71f5bb7d1e44d3f1e35ab
[ "MIT" ]
null
null
null
#include "pdmath/Matrix3.hpp" #include "pdmath/Vector3.hpp" #include "pdmath/Matrix4.hpp" #include "pdmath/Vector4.hpp" #include "catch2/catch_test_macros.hpp" #include "catch2/catch_approx.hpp" using namespace pdm; using namespace Catch; TEST_CASE("Matrices can multiply", "[matrices]") { Mat3 m( 3.0f, -5.0f, 4.0f, -2.0f, 2.0f, 3.0f, -3.0f, -4.0f, -5.0f); Mat3 n(-1.0f, -2.0f, -3.0f, -5.0f, 2.0f, 3.0f, 1.0f, 0.0f, -3.0f); Mat3 solution (26.0f, -16.0f, -36.0f, -5.0f, 8.0f, 3.0f, 18.0f, -2.0f, 12.0f); REQUIRE((m * n) == solution); REQUIRE((m *= n) == solution); m = Mat3(-2.0f, 4.0f, 4.0f, -1.0f, -4.0f, 4.0f, 2.0f, 3.0f, 0.0f); n = Mat3( 4.0f, 4.0f, 1.0f, -4.0f, -5.0f, 2.0f, -1.0f, -1.0f, -5.0f); solution = Mat3(-28.0f, -32.0f, -14.0f, 8.0f, 12.0f, -29.0f, -4.0f, -7.0f, 8.0f); REQUIRE((m * n) == solution); REQUIRE((m *= n) == solution); } TEST_CASE("Matrices can add", "[matrices]") { Mat3 m(-4.0f, -2.0f, -2.0f, -4.0f, 2.0f, -3.0f, 2.0f, -3.0f, 2.0f); Mat3 n(-1.0f, -1.0f, 1.0f, 1.0f, 3.0f, -3.0f, -3.0f, -5.0f, 2.0f); Mat3 solution(-5.0f, -3.0f, -1.0f, -3.0f, 5.0f, -6.0f, -1.0f, -8.0f, 4.0f); REQUIRE((m + n) == solution); REQUIRE((m += n) == solution); Mat4 a(-4.0f, -2.0f, -2.0f, 4.0f, -4.0f, 2.0f, -3.0f, -3.0f, 2.0f, -3.0f, 2.0f, 1.0f, 5.0f, 3.0f, 1.0f, 0.0f); Mat4 b(-1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 3.0f, 0.0f, -3.0f, -3.0f, -5.0f, 2.0f, 2.0f, 3.0f, 2.0f, 2.0f, 2.0f); Mat4 ab_solution(-5.0f, -3.0f, -1.0f, 5.0f, -3.0f, 5.0f, -3.0f, -6.0f, -1.0f, -8.0f, 4.0f, 3.0f, 8.0f, 5.0f, 3.0f, 2.0f); REQUIRE((a + b) == ab_solution); REQUIRE((a += b) == ab_solution); } TEST_CASE("Matrices can subtract", "[matrices]") { Mat3 m(-2.0f, -4.0f, 4.0f, 0.0f, 0.0f, -5.0f, -4.0f, 0.0f, -5.0f); Mat3 n(-1.0f, -3.0f, 4.0f, 4.0f, 4.0f, -2.0f, -3.0f, 3.0f, -4.0f); Mat3 solution(-1.0f, -1.0f, 0.0f, -4.0f, -4.0f, -3.0f, -1.0f, -3.0f, -1.0f); REQUIRE((m - n) == solution); REQUIRE((m -= n) == solution); Mat4 a(-2.0f, -4.0f, 4.0f, 4.0f, 0.0f, 0.0f, -5.0f, -3.0f, -4.0f, 0.0f, -5.0f, 1.0f, 5.0f, 3.0f, 1.0f, 0.0f); Mat4 b(-1.0f, -3.0f, 4.0f, 1.0f, 4.0f, 4.0f, -2.0f, -3.0f, -3.0f, 3.0f, -4.0f, 2.0f, 3.0f, 2.0f, 2.0f, 2.0f); Mat4 ab_solution(-1.0f, -1.0f, 0.0f, 3.0f, -4.0f, -4.0f, -3.0f, 0.0f, -1.0f, -3.0f, -1.0f, -1.0f, 2.0f, 1.0f, -1.0f, -2.0f); REQUIRE((a - b) == ab_solution); REQUIRE((a -= b) == ab_solution); } TEST_CASE("Matrix Vector multiplication works", "[matrices][vectors]") { Mat3 m( 3.0f, 2.0f, 0.0f, 1.0f, -1.0f, 4.0f, -4.0f, 4.0f, 4.0f); Mat3 n(-4.0f, -1.0f, -5.0f, -3.0f, 3.0f, 0.0f, 0.0f, 1.0f, 3.0f); Vec3 v(-3.0f, -1.0f, 4.0f); REQUIRE((m * v) == Vec3(-11.0f, 14.0f, 24.0f)); REQUIRE((m * n * v) == Vec3(-9.0f, 31.0f, 96.0f)); } TEST_CASE("Matrices can find their determinants", "[matrices]") { Mat3 m(-5.0f, -3.0f, 1.0f, -4.0f, 1.0f, 0.0f, 2.0f, -4.0f, -1.0f); REQUIRE(m.determinant() == 31); m = Mat3( 2.0f, 2.0f,-5.0f, 3.0f, 2.0f, 3.0f, -3.0f, -5.0f, 4.0f); REQUIRE(m.determinant() == 49); } TEST_CASE("Matrices know their minors, cofactors, and adjoints", "[matrices]") { Mat3 m(3.0f, 0.0f, 2.0f, 2.0f, 0.0f, -2.0f, 0.0f, 1.0f, 1.0f); REQUIRE(m.matrix_of_minors() == Mat3( 2.0f, 2.0f, 2.0f, -2.0f, 3.0f, 3.0f, 0.0f, -10.0f, 0.0f)); REQUIRE(m.matrix_of_cofactors() == Mat3(2.0f, -2.0f, 2.0f, 2.0f, 3.0f, -3.0f, 0.0f, 10.0f, 0.0f)); REQUIRE(m.matrix_of_cofactors().transposed() == Mat3( 2.0f, 2.0f, 0.0f, -2.0f, 3.0f, 10.0f, 2.0f, -3.0f, 0.0f)); } TEST_CASE("Matrices can find their inverses", "[matrices]") { Mat3 m(3.0f, 0.0f, 2.0f, 2.0f, 0.0f, -2.0f, 0.0f, 1.0f, 1.0f); REQUIRE(m.inverted() == Mat3( 0.2f, 0.2f, 0.0f, -0.2f, 0.3f, 1.0f, 0.2f, -0.3f, 0.0f)); } TEST_CASE("Extracting Euler angles from matrices", "[matrices]") { Mat3 r( 0.09473f, -0.0442f, -0.9945f, 0.30563f, -0.9495f, 0.07129f, -0.9474f, -0.3107f, -0.0764f); Vec3 ans1; Vec3 ans2; r.get_euler_xyz(ans1, ans2); REQUIRE(ans1 == Vec3(-2.39078f, -1.465867f, 0.436564f)); REQUIRE(ans2 == Vec3(0.750813f, -1.675726f, -2.705029f)); r = Mat3(-0.0696f, 0.7956f, -0.6018f, -0.4681f, -0.5588f, -0.6846f, -0.8809f, 0.2341f, 0.41133f); r.get_euler_xyz(ans1, ans2); REQUIRE(ans1 == Vec3(1.029765f, -0.645753f, -1.658055f)); REQUIRE(ans2 == Vec3(-2.111828f, -2.49584f, 1.483537f)); // Well... these don't work for now. // r = Mat3( 0.67016f, 0.6509f, 0.35668f, // -0.6467f, 0.2763f, 0.71092f, // 0.36419f, -0.7071f, 0.60611f); // r.get_euler_zxy(ans1, ans2); // REQUIRE(ans1 == Vec3(-3.0892f, -0.1047f, 0.4538f)); // REQUIRE(ans2 == Vec3(0.0524f, 3.0369f, 2.6878f)); }
30.009901
80
0.423458
pdm-pcb
93fb027d867d902d3c6541872be8561db2b9f0f8
2,873
cpp
C++
src/Hexxagon/HexxagonAIPlayer.cpp
ldornbusch/hexxagon_sfml
62de9412a46da98f212f4c2fa8c934786200f02a
[ "Apache-2.0" ]
null
null
null
src/Hexxagon/HexxagonAIPlayer.cpp
ldornbusch/hexxagon_sfml
62de9412a46da98f212f4c2fa8c934786200f02a
[ "Apache-2.0" ]
null
null
null
src/Hexxagon/HexxagonAIPlayer.cpp
ldornbusch/hexxagon_sfml
62de9412a46da98f212f4c2fa8c934786200f02a
[ "Apache-2.0" ]
null
null
null
// HexxagonAIPlayer.cpp: implementation of the HexxagonAIPlayer class. // ////////////////////////////////////////////////////////////////////// #include "HexxagonAIPlayer.h" ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// HexxagonAIPlayer::HexxagonAIPlayer() : bestMove() { } HexxagonAIPlayer::~HexxagonAIPlayer() { } HexxagonMove HexxagonAIPlayer::getBestMove(int iPlayer, vector<HexxagonStone*> vecStones) { // remember current player iCurrentPlayer = iPlayer; // reset best move bestMove.Color = iPlayer; bestMove.from = -1; bestMove.to = -1; bestMove.rate = -1; bestMove.moveType = -1; // loop through all stones for (unsigned int x=0;x<vecStones.size();x++) { // analyze stone if it belongs to current player if ( vecStones[x]->getColor()==iCurrentPlayer) { HexxagonMove aiMove = analyze(x,vecStones); if ( aiMove.rate > bestMove.rate ) { bestMove = aiMove; } } } //xxagonMove bestMove = new HexxagonMove(iPlayer,iIndex,-1,0); return bestMove; } /* * analyse given stone and return best possible move * @param iIndex offset of the current stone in vector * @param vecStones vector of HexxagonStone* * @return HexxagonMove with the best rating * ===================================================================== */ HexxagonMove HexxagonAIPlayer::analyze(int iIndex, vector<HexxagonStone*> vecStones) { // create new move and set to color and given index HexxagonMove ratedMove = HexxagonMove(vecStones[iIndex]->getColor(),iIndex,-1,-1,-1); // check all neighbouring stones for (int x=0; x<HEX_NUM_STONE_NEIGHBOURS+HEX_NUM_STONE_DISTANT_NEIGHBOURS;x++) { // get neighbour from current stone int iNeighbour = vecStones[iIndex]->getNeighbour(x); // if we have a neighbour and it is an empty field if (iNeighbour >= 0 && vecStones[iNeighbour]->getColor()==0) { // rate depending on move type int iRate = (x<HEX_NUM_STONE_NEIGHBOURS)?2:1; // check close neighbours of neighbours for (int y=0; y<HEX_NUM_STONE_NEIGHBOURS;y++) { // get close neighbour if it is valid int iSubNeighbour = vecStones[iNeighbour]->getNeighbour(y); // increment rate if field is sourrounded by enemy stones if ( iSubNeighbour>=0 && (vecStones[iSubNeighbour]->getColor() != iCurrentPlayer) && (vecStones[iSubNeighbour]->getColor() != 0)) iRate++; } // compare rate with rate of last best rated move if ( iRate > ratedMove.rate ) { // copy rest of move attributes ratedMove.to = iNeighbour; ratedMove.rate = iRate; ratedMove.moveType = (x<HEX_NUM_STONE_NEIGHBOURS)?2:1; } } } // pass best possible move back return ratedMove; }
31.571429
90
0.611556
ldornbusch
93fd8bcc603f7a670dbd908b046820328c44405c
155
hpp
C++
include/SplayLibrary/3D/3D.hpp
Reiex/SplayLibrary
94b68f371ea4c662c84dfe2dd0a6d1625b60fb04
[ "MIT" ]
1
2021-12-14T21:36:39.000Z
2021-12-14T21:36:39.000Z
include/SplayLibrary/3D/3D.hpp
Reiex/SplayLibrary
94b68f371ea4c662c84dfe2dd0a6d1625b60fb04
[ "MIT" ]
null
null
null
include/SplayLibrary/3D/3D.hpp
Reiex/SplayLibrary
94b68f371ea4c662c84dfe2dd0a6d1625b60fb04
[ "MIT" ]
null
null
null
#pragma once #include <SplayLibrary/3D/Transformable3D.hpp> #include <SplayLibrary/3D/PerspectiveCamera.hpp> #include <SplayLibrary/3D/Mesh.hpp>
19.375
49
0.76129
Reiex
9e00e4e64c362ff594dc35d56dd31835d2dece09
2,349
cpp
C++
src/qt/qtbase/tests/manual/cocoa/appicon/main.cpp
power-electro/phantomjs-Gohstdriver-DIY-openshift
a571d301a9658a4c1b524d07e15658b45f8a0579
[ "BSD-3-Clause" ]
1
2020-04-30T15:47:35.000Z
2020-04-30T15:47:35.000Z
src/qt/qtbase/tests/manual/cocoa/appicon/main.cpp
power-electro/phantomjs-Gohstdriver-DIY-openshift
a571d301a9658a4c1b524d07e15658b45f8a0579
[ "BSD-3-Clause" ]
null
null
null
src/qt/qtbase/tests/manual/cocoa/appicon/main.cpp
power-electro/phantomjs-Gohstdriver-DIY-openshift
a571d301a9658a4c1b524d07e15658b45f8a0579
[ "BSD-3-Clause" ]
null
null
null
/**************************************************************************** ** ** Copyright (C) 2015 The Qt Company Ltd. ** Contact: http://www.qt.io/licensing/ ** ** This file is part of the test suite of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL21$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see http://www.qt.io/terms-conditions. For further ** information use the contact form at http://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** As a special exception, The Qt Company gives you certain additional ** rights. These rights are described in The Qt Company LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <QApplication> #include <QPushButton> #include <QVBoxLayout> class TopWidget : public QWidget { Q_OBJECT public: TopWidget(QWidget *parent = 0) : QWidget(parent) { QVBoxLayout *layout = new QVBoxLayout; QPushButton *button = new QPushButton("Change app icon"); connect(button, SIGNAL(clicked()), this, SLOT(changeIcon())); layout->addWidget(button); setLayout(layout); } public slots: void changeIcon() { QPixmap pix(32, 32); pix.fill(Qt::red); QIcon i(pix); qApp->setWindowIcon(i); } }; #include "main.moc" int main(int argc, char **argv) { QApplication a(argc, argv); TopWidget w; w.show(); return a.exec(); }
34.043478
78
0.65049
power-electro
9e0334d3223ce649d87ca4a066c190672e17c82f
2,050
cpp
C++
Vishv_GE/Framework/Graphics/Src/BlendState.cpp
InFaNsO/Vishv_GameEngine
e721afa899fb8715e52cdd67c2656ba6cce7ffed
[ "MIT" ]
1
2021-12-19T02:06:12.000Z
2021-12-19T02:06:12.000Z
Vishv_GE/Framework/Graphics/Src/BlendState.cpp
InFaNsO/Vishv_GameEngine
e721afa899fb8715e52cdd67c2656ba6cce7ffed
[ "MIT" ]
null
null
null
Vishv_GE/Framework/Graphics/Src/BlendState.cpp
InFaNsO/Vishv_GameEngine
e721afa899fb8715e52cdd67c2656ba6cce7ffed
[ "MIT" ]
null
null
null
#include "Precompiled.h" #include "BlendState.h" #include "D3DUtil.h" #include "GraphicsSystem.h" using namespace Vishv; using namespace Vishv::Graphics; namespace { D3D11_BLEND GetSrcBlend(BlendState::Mode mode) { switch (mode) { case BlendState::Mode::Opaque: return D3D11_BLEND_ONE; case BlendState::Mode::AlphaBlend: return D3D11_BLEND_SRC_ALPHA; case BlendState::Mode::AlphaPremultiplied: return D3D11_BLEND_ONE; case BlendState::Mode::Additive: return D3D11_BLEND_SRC_ALPHA; } return D3D11_BLEND_ONE; } D3D11_BLEND GetDestBlend(BlendState::Mode mode) { switch (mode) { case BlendState::Mode::Opaque: return D3D11_BLEND_ZERO; case BlendState::Mode::AlphaBlend: return D3D11_BLEND_INV_SRC_ALPHA; case BlendState::Mode::AlphaPremultiplied: return D3D11_BLEND_INV_SRC_ALPHA; case BlendState::Mode::Additive: return D3D11_BLEND_ONE; } return D3D11_BLEND_ZERO; } } BlendState::~BlendState() { VISHVASSERT(mBlendState == nullptr, "[Graphics::BlendState] Blend State not Terminated"); } void BlendState::Initialize(BlendState::Mode mode) { D3D11_BLEND srcBlend = GetSrcBlend(mode); D3D11_BLEND destBlend = GetDestBlend(mode); D3D11_BLEND_DESC desc{}; desc.RenderTarget[0].BlendEnable = (srcBlend != D3D11_BLEND_ONE) || (destBlend != D3D11_BLEND_ZERO); desc.RenderTarget[0].SrcBlend = desc.RenderTarget[0].SrcBlendAlpha = srcBlend; desc.RenderTarget[0].DestBlend = desc.RenderTarget[0].DestBlendAlpha = destBlend; desc.RenderTarget[0].BlendOp = desc.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD; desc.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL; HRESULT hr = GetDevice()->CreateBlendState(&desc, &mBlendState); VISHVASSERT(SUCCEEDED(hr), "[Graphics::BlendState] Failed to create blend state"); } void BlendState::Terminate() { SafeRelease(mBlendState); } void BlendState::Set() { GetContext()->OMSetBlendState(mBlendState, nullptr, UINT_MAX); } void BlendState::Clear() { GetContext()->OMSetBlendState(nullptr, nullptr, UINT_MAX); }
24.698795
101
0.76
InFaNsO
9e0532cb756a276c21b2f7dd8d822889833e8769
906
tcc
C++
include/biggles/observation.tcc
fbi-octopus/biggles
2dac4f1748ab87242951239caf274f302be1143a
[ "Apache-2.0" ]
1
2019-11-15T14:01:59.000Z
2019-11-15T14:01:59.000Z
include/biggles/observation.tcc
fbi-octopus/biggles
2dac4f1748ab87242951239caf274f302be1143a
[ "Apache-2.0" ]
null
null
null
include/biggles/observation.tcc
fbi-octopus/biggles
2dac4f1748ab87242951239caf274f302be1143a
[ "Apache-2.0" ]
null
null
null
#ifndef WITHIN_BIGGLES_OBSERVATION_HPP__ #error "this file must only be included by observation.hpp" #endif // WITHIN_BIGGLES_OBSERVATION_HPP__ #include <cmath> namespace biggles { inline bool observations_see_each_other(const observation& o1, const observation& o2, const float& speed_of_light) { time_stamp dt(std::abs(t(o1) - t(o2))); float dx(x(o1) - x(o2)); float dy(y(o1) - y(o2)); float ds_sq(dx*dx + dy*dy); float max_ds(dt * speed_of_light); if(ds_sq > max_ds*max_ds) return false; return true; } inline float observations_see_each_other2(const observation& o1, const observation& o2, const float& speed_of_light) { float ds(dist(o1, o2)); float max_ds(std::abs(t(o1) - t(o2)) * speed_of_light); if(ds > max_ds) return -1.f; return sqrtf(square(x(o1)-x(o2)) + square(y(o1)-y(o2)) + float(square(t(o2)-t(o1)))); //return ds; } }
27.454545
116
0.674393
fbi-octopus
9e07e6eba2f995fe5d7c9947da1cbc6fb4e713d0
4,213
cpp
C++
Solutions/Word Break II/main.cpp
Crayzero/LeetCodeProgramming
b10ebe22c0de1501722f0f5c934c0c1902a26789
[ "MIT" ]
1
2015-04-13T10:58:30.000Z
2015-04-13T10:58:30.000Z
Solutions/Word Break/main.cpp
Crayzero/LeetCodeProgramming
b10ebe22c0de1501722f0f5c934c0c1902a26789
[ "MIT" ]
null
null
null
Solutions/Word Break/main.cpp
Crayzero/LeetCodeProgramming
b10ebe22c0de1501722f0f5c934c0c1902a26789
[ "MIT" ]
null
null
null
#include <iostream> #include <string> #include <unordered_set> #include <unordered_map> #include <vector> using namespace std; class Solution { public: bool wordBreak(string s, unordered_set<string> &dict) { if (s.size() == 0) { return false; } int *dp = new int[s.size()]; for(string::size_type i = 0; i < s.size(); i++) { dp[i] = 0; } if (dict.find(s.substr(0,1)) != dict.end()) { dp[0] = 1; } for (string::size_type i = 1; i < s.size(); i++) { string subs = s.substr(0, i+1); cout<<subs<<"\t"; if (dict.find(subs) != dict.end()) { dp[i] = 1; } for(string::size_type j = 0; j < i; j++) { if(dp[j] == 1) { subs = s.substr(j+1, i-j); if (dict.find(subs) != dict.end()) { dp[i] = 1; break; } } } cout<<dp[i]<<endl; } if (dp[s.size()-1]) { delete [] dp; return true; } delete [] dp; return false; } vector<string> wordBreak2(string s, unordered_set<string> &dict) { unordered_map<int, pair<int, vector<int> > > m; vector<string> res; if (s.size() == 0) { return res; } for(string::size_type i = 0; i < s.size(); i++) { m[i] = make_pair(0, vector<int>()); } if (dict.find(s.substr(0,1)) != dict.end()) { m[0].first = 1; m[0].second.push_back(0); } else { m[0].first = 0; m[0].second.push_back(-1); } for (string::size_type i = 1; i < s.size(); i++) { string subs = s.substr(0, i+1); cout<<subs<<"\t"; if (dict.find(subs) != dict.end()) { m[i].first = 1; m[i].second.push_back(-1); } for(string::size_type j = 0; j < i; j++) { if(m[j].first == 1) { subs = s.substr(j+1, i-j); if (dict.find(subs) != dict.end()) { m[i].first = 1; m[i].second.push_back(j); } } } cout<<m[i].first<<"\t"; for(auto beg = m[i].second.begin(); beg != m[i].second.end(); beg++) { cout<<*beg<<" "; } cout<<endl; } cout<<endl; if (s.size() == 1 && m[0].first == 1) { res.push_back(s); return res; } if(m[s.size()-1].first == 1) { return get_all_string(m, s.size()-1, s); } else { return res; } } vector<string> get_all_string(unordered_map<int, pair<int, vector<int> > > &m, int from, string &str) { vector<int> from_v = m[from].second; string s; vector<string > v_t; if (from == 0) { v_t.push_back(str.substr(0,1)); return v_t; } for(auto beg = from_v.begin(); beg != from_v.end(); beg++) { string subs; if (*beg >= 0) { subs = str.substr(*beg+1, from - *beg); } else { subs = str.substr(0, from + 1); } cout<<subs<<endl; vector<string > t = get_all_string(m, *beg, str); if (t.size() == 0) { v_t.push_back(subs); } for(auto beg2 = t.begin(); beg2 != t.end(); beg2++) { s = *beg2 + " " + subs; v_t.push_back(s); } } return v_t; } }; int main() { Solution solution; string s = "leeta"; unordered_set<string> dict = {"leet", "code", "a"}; //cout<<solution.wordBreak(s, dict)<<endl; vector<string > res; string s2 = "a"; unordered_set<string> dict2 = {}; res = solution.wordBreak2(s2, dict2); for(auto beg = res.begin(); beg != res.end(); beg++) { cout<<*beg<<endl; } return 0; }
29.256944
107
0.402326
Crayzero
9e0910efb0364f3a7775db8f80e66e5f1afc8c49
3,602
hpp
C++
jerome/type/algorithm.hpp
leuski-ict/jerome
6141a21c50903e98a04c79899164e7d0e82fe1c2
[ "Apache-2.0" ]
3
2018-06-11T10:48:54.000Z
2021-05-30T07:10:15.000Z
jerome/type/algorithm.hpp
leuski-ict/jerome
6141a21c50903e98a04c79899164e7d0e82fe1c2
[ "Apache-2.0" ]
null
null
null
jerome/type/algorithm.hpp
leuski-ict/jerome
6141a21c50903e98a04c79899164e7d0e82fe1c2
[ "Apache-2.0" ]
null
null
null
// // algorithm.hpp // jerome // // Created by Anton Leuski on 9/8/16. // Copyright © 2016 Anton Leuski & ICT/USC. All rights reserved. // // This file is part of Jerome. // // 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 __jerome_algorithm_h__ #define __jerome_algorithm_h__ #include <vector> #include <random> #include <boost/range/algorithm/random_shuffle.hpp> #include <boost/range/adaptor/transformed.hpp> #include <boost/iterator/transform_iterator.hpp> #include <jerome/types.hpp> namespace jerome { template <class Result, class Range, class URBG = std::default_random_engine> std::pair<Result, Result> split(Range inRange, double inProportion, URBG&& g = URBG()) { typedef typename std::remove_cv< typename std::remove_reference< Range>::type >::type::value_type value_type; std::vector<value_type> randomized(std::begin(inRange), std::end(inRange)); std::size_t maxCount = randomized.size(); std::size_t count = (inProportion < 0 || inProportion >= maxCount) ? maxCount : (std::size_t)((inProportion < 1) ? inProportion * maxCount : inProportion); if (count == maxCount) { return std::pair<Result, Result>(randomized, randomized); } std::shuffle(boost::begin(randomized), boost::end(randomized), g); auto first = boost::make_iterator_range(randomized.begin(), randomized.begin() + count); auto second = boost::make_iterator_range(randomized.begin() + count, randomized.end()); return std::pair<Result, Result>(Result(first.begin(), first.end()), Result(second.begin(), second.end())); } template <class Result, class Range, class Predicate> std::pair<Result, Result> split(Range inRange, Predicate&& p) { Result first; Result second; for(auto x : inRange) { if (p(x)) { first.push_back(x); } else { second.push_back(x); } } return std::pair<Result, Result>(first, second); } // for iterating over map keys. template <typename Iter> boost::transform_iterator<KeyGetter<Iter>, Iter, const typename Iter::value_type::first_type&> KeyIterator(Iter iterator) { return boost::transform_iterator< KeyGetter<Iter>, Iter, const typename Iter::value_type::first_type&> (iterator, KeyGetter<Iter>()); } template <typename T> std::vector<typename T::key_type> keys(const T& map) { return std::vector<typename T::key_type>(KeyIterator(map.begin()), KeyIterator(map.end())); } template <typename M> optional<typename M::mapped_type> map_value_at(const M& map, const typename M::key_type& key) { auto x = map.find(key); if (x == map.end()) { return optional<typename M::mapped_type>(); } else { return x->second; } } } #endif // __jerome_algorithm_h__
30.016667
88
0.628262
leuski-ict
9e0a7e544681068eb6bc06e2b0bbefecaa6f6fc3
6,920
cpp
C++
firmware/snake.cpp
fitzterra/bittycade
aa0918d924177557755a82498a55dc4712abcf4f
[ "MIT" ]
1
2020-10-02T04:18:27.000Z
2020-10-02T04:18:27.000Z
firmware/snake.cpp
fitzterra/bittycade
aa0918d924177557755a82498a55dc4712abcf4f
[ "MIT" ]
null
null
null
firmware/snake.cpp
fitzterra/bittycade
aa0918d924177557755a82498a55dc4712abcf4f
[ "MIT" ]
null
null
null
#include "snake.h" extern byte lost[]; /** * Generates a point at the given coordinates and returns a pointer to it. * The point is dynamically allocated and must be freed again when it is not needed anymore. **/ point* Snake::spawnSegment(int x, int y) { point *position; position = (struct point*)malloc(sizeof(struct point)); position->x = x; position->y = y; return position; } /** * Adds and displays an apple at a new random position. **/ void Snake::addApple() { point *segment; bool isClear; // Continue looking for a spot to place the apple do { // Assume it's clear to start with isClear = true; // Find a random spot apple.x = random(LEDMATRIX_X); apple.y = random(LEDMATRIX_Y); // Is it on the snake? for(int8_t i=body.size()-1; i>=0; i--) { segment = body.get(i); if(segment->x==apple.x && segment->y==apple.y) { isClear = false; break; // Jump out of for } } } while(!isClear); // Display it display->drawPixel(apple.x, apple.y); appleIsOn = true; } /** * Checks if a button is pressed and updates the steering position to left or * right if so. **/ void Snake::checkSteering() { if(controller->rightButtonPressed && !controller->leftButtonPressed) steering = STEER_RIGHT; else if(controller->leftButtonPressed && !controller->rightButtonPressed) steering = STEER_LEFT; //Serial << "steering: " << steering << endl; } /** * Checks if the snake has collided with the sides or is eating itself. * Returns true if so, false otherwise. **/ bool Snake::checkCollisions() { // Is the head outside the screen? point *head = body.get(0); if(head->x < 0 || head->y < 0 || head->x >= LEDMATRIX_X || head->y >= LEDMATRIX_Y) { //Serial << "snake in the grass...\n"; return true; } // Am I eating myself? point *seg; for(uint8_t i=body.size()-1; i>0; i--) { seg = body.get(i); if(head->x==seg->x && head->y==seg->y) { //Serial << "eat myself at " << i << endl; return true; } } return false; } /** * Moves the body by moving the head in the steering position, and moving all * other segments up one. See the SnakeSteering drawing in the docs for info on * how the new head position is determined. * If the head ends up on the apple, the body is extended by keeping the last * tail section. A new apple will also be spawned. * No checking for collisions are done.` **/ void Snake::moveBody() { // If we're not steering straight, we need to change the travel direction // point if(steering != STEER_STRAIGHT) { // See the SnakeSteering diagram in the docs for details on this // algorithm. // Get the current cardinal direction we're going in, and "turn" into // the direction the player wants to steer to so we get the new // cardinal direction we should go to. int8_t destDir = getTravelDir() + (steering==STEER_RIGHT ? 1 : -1); // Check for wrap around if(destDir>WEST) destDir = NORTH; else if(destDir<NORTH) destDir = WEST; // Temp holder for new x and y travel direction indicators int8_t x, y; // Update the direction modifier if( (steering==STEER_RIGHT && (destDir==EAST || destDir==WEST)) || (steering==STEER_LEFT && (destDir==NORTH || destDir==SOUTH)) ) { x = travelDir.y * -1; y = travelDir.x * -1; } else { x = travelDir.y; y = travelDir.x; } // Set new travel direction and steer straight travelDir.x = x; travelDir.y = y; steering = STEER_STRAIGHT; } // Spawn a new head point *head = body.get(0); point *newHead = spawnSegment(head->x+travelDir.x, head->y+travelDir.y); // Wrap out of the screen? if(newHead->x < 0) newHead->x = LEDMATRIX_X-1; else if(newHead->x >= LEDMATRIX_X) newHead->x = 0; if(newHead->y < 0) newHead->y = LEDMATRIX_Y-1; else if(newHead->y >= LEDMATRIX_Y) newHead->y = 0; // Add it at the head of the body and light the pixel body.unshift(newHead); display->drawPixel(newHead->x, newHead->y); // Has the new head now eaten the apple? if(newHead->x==apple.x && newHead->y==apple.y) { // Short animation for(uint8_t n=0; n<body.size(); n++) { head = body.get(n); display->drawPixel(head->x, head->y, false); delay(40); display->drawPixel(head->x, head->y, true); delay(50); } // Give the player some time to choose a button for direction nextMoveTime += 500; // Spawn a new apple addApple(); // Speed up moveDelay -= 50; } else { // Remove the last tail segment and switch off the pixel point *tail = body.pop(); display->drawPixel(tail->x, tail->y, false); free(tail); } } /** * Destroys the whole snake body by freeing the memory for each segment and * emptying the linked list. **/ void Snake::destroyBody() { point *seg; while(body.size()) { seg = body.pop(); free(seg); } } /** * Resets the game parameters for starting a new game. **/ void Snake::reset() { point *segment; // Re-seed the random generator randomSeed(analogRead(0)); display->clear(); moveDelay = 750; nextMoveTime = millis() + moveDelay; // Set up and draw the first 4 segments of the body for(uint8_t x=4; x<8; x++) { segment = spawnSegment(x, 4); body.add(segment); display->drawPixel(segment->x, segment->y); } // Start moving left travelDir.x = -1; travelDir.y = 0; steering = STEER_STRAIGHT; addApple(); // Give buttons a sec to settle from the press from the menu delay(1000); } void Snake::update() { uint32_t static appleDelay=0, buttonDelay=0; // We check for steering changes on every update even if it is not time to // move the snake. This allows the player to adjust the steering in advanve // before the next body move. if(millis() > buttonDelay) { checkSteering(); buttonDelay = millis() + 50; } // Time to move the snake? if(millis() >= nextMoveTime) { moveBody(); if (checkCollisions()) { display->flashSprite(lost, 4, 500); destroyBody(); gameOver = true; return; } nextMoveTime = millis() + moveDelay; } // Flash apple if(millis() > appleDelay) { appleIsOn = !appleIsOn; display->drawPixel(apple.x, apple.y, appleIsOn); appleDelay = millis() + 300; } }
28.953975
92
0.580347
fitzterra
9e0f3616ab802bf3927394c258e373b18b7b2872
550
hpp
C++
data-manager/src/server/dataManagerServer/DataManagerTCPServer.hpp
Saafke/4dm
68e235164afb1f127def35e9c15ca883ec1426d4
[ "MIT" ]
8
2021-03-16T06:48:57.000Z
2021-11-30T09:34:09.000Z
data-manager/src/server/dataManagerServer/DataManagerTCPServer.hpp
Saafke/4dm
68e235164afb1f127def35e9c15ca883ec1426d4
[ "MIT" ]
null
null
null
data-manager/src/server/dataManagerServer/DataManagerTCPServer.hpp
Saafke/4dm
68e235164afb1f127def35e9c15ca883ec1426d4
[ "MIT" ]
3
2021-05-02T15:38:17.000Z
2021-07-07T09:19:48.000Z
#pragma once #include "TCPConnection.hpp" #include "boost/asio.hpp" #include "boost/thread.hpp" #include "boost/bind.hpp" using boost::asio::ip::tcp; namespace dataManagerServer { class DataManagerTCPServer { public: DataManagerTCPServer(boost::asio::io_context& io_context, uint16_t port); void Stop(); bool Status(); private: boost::asio::io_context& io_context_; tcp::acceptor acceptor_; void startAccept(); void handleAccept(dataManagerServer::TCPConnection::pointer new_connection, const boost::system::error_code& error); }; }
18.333333
117
0.758182
Saafke
9e14075c73d7cf1511d83e703eb6e9e1e6a37cb8
260
cpp
C++
Battleship/HumanPlayer.cpp
Alimektor/battleship-cpp-clr
6c1fd7c263e087592cfee3dcd487f91c1a286554
[ "MIT" ]
null
null
null
Battleship/HumanPlayer.cpp
Alimektor/battleship-cpp-clr
6c1fd7c263e087592cfee3dcd487f91c1a286554
[ "MIT" ]
null
null
null
Battleship/HumanPlayer.cpp
Alimektor/battleship-cpp-clr
6c1fd7c263e087592cfee3dcd487f91c1a286554
[ "MIT" ]
null
null
null
#include "HumanPlayer.h" void BattleshipGame::HumanPlayer::GetTurn() { SetEnabled(); } void BattleshipGame::HumanPlayer::SetEnabled() { this->GetBoard()->SetEnabled(); } void BattleshipGame::HumanPlayer::SetDisabled() { this->GetBoard()->SetDisabled(); }
16.25
47
0.726923
Alimektor
9e16f1dbfa8ed275dabcc360763ac04036bf904d
11,236
cpp
C++
Plugins/JVM/NWScript.cpp
acaos/nwnxee-unified
0e4c318ede64028c1825319f39c012e168e0482c
[ "MIT" ]
1
2019-06-04T04:30:24.000Z
2019-06-04T04:30:24.000Z
Plugins/JVM/NWScript.cpp
presscad/nwnee
0f36b281524e0b7e9796bcf30f924792bf9b8a38
[ "MIT" ]
null
null
null
Plugins/JVM/NWScript.cpp
presscad/nwnee
0f36b281524e0b7e9796bcf30f924792bf9b8a38
[ "MIT" ]
1
2019-10-20T07:54:45.000Z
2019-10-20T07:54:45.000Z
#include "JVM.hpp" #include "Internal.hpp" #include "Util.h" #include "Services/Events/Events.hpp" #include "API/Globals.hpp" #include "API/Constants.hpp" #include "API/CScriptLocation.hpp" #include "API/Vector.hpp" #include "API/CVirtualMachine.hpp" #include "API/CVirtualMachineCmdImplementer.hpp" #include "API/CNWVirtualMachineCommands.hpp" #include <cmath> #include <jni.h> #define ENGINE_STRUCTURE_EFFECT 0 #define ENGINE_STRUCTURE_EVENT 1 #define ENGINE_STRUCTURE_LOCATION 2 #define ENGINE_STRUCTURE_TALENT 3 #define ENGINE_STRUCTURE_ITEMPROPERTY 4 namespace JVM { using namespace NWNXLib; using namespace NWNXLib::API; using namespace NWNXLib::Services; static Internal* g_internal; JNIEXPORT jint JNICALL Internal::NWScriptPopInteger(JNIEnv* env, jobject obj) { int32_t r; if (!Globals::VirtualMachine()->StackPopInteger(&r)) throw std::runtime_error("Cannot pop a int off the VM stack."); return static_cast<jint>(r); } JNIEXPORT void JNICALL Internal::NWScriptPushInteger(JNIEnv* env, jobject obj, jint value) { Globals::VirtualMachine()->StackPushInteger(value); } JNIEXPORT jfloat JNICALL Internal::NWScriptPopFloat(JNIEnv* env, jobject obj) { float r; if (!Globals::VirtualMachine()->StackPopFloat(&r)) throw std::runtime_error("Cannot pop a float off the VM stack."); return static_cast<jfloat>(r); } JNIEXPORT void JNICALL Internal::NWScriptPushFloat(JNIEnv* env, jobject obj, jfloat value) { Globals::VirtualMachine()->StackPushFloat(value); } JNIEXPORT jstring JNICALL Internal::NWScriptPopString(JNIEnv* env, jobject obj) { CExoString r; if (!Globals::VirtualMachine()->StackPopString(&r)) throw std::runtime_error("Cannot pop a string off the VM stack."); jbyteArray myByteStuff = JNICHECKED(env, NewByteArray(r.GetLength())); JNICHECKED(env, SetByteArrayRegion(myByteStuff, 0, r.GetLength(), (jbyte*) r.CStr())); auto ret = JNICHECKED(env, CallStaticObjectMethod(g_internal->m_jclassConv, g_internal->m_jmethodConvFromNative, myByteStuff)); return static_cast<jstring>(ret); } JNIEXPORT void JNICALL Internal::NWScriptPushString(JNIEnv* env, jobject obj, jstring value) { jbyteArray toNative = (jbyteArray) JNICHECKED(env, CallStaticObjectMethod(g_internal->m_jclassConv, g_internal->m_jmethodConvToNative, value)); jbyte* converted = (jbyte*) JNICHECKED(env, GetByteArrayElements(toNative, nullptr)); int32_t len = JNICHECKED(env, GetArrayLength(toNative)); ASSERT(len >= 0); CExoString toPush((char*) converted, len); Globals::VirtualMachine()->StackPushString(toPush); JNICHECKED(env, ReleaseByteArrayElements(toNative, converted, JNI_ABORT)); } JNIEXPORT void JNICALL Internal::NWScriptPushObject(JNIEnv* env, jobject obj, jobject value) { int32_t oid = Constants::OBJECT_INVALID; if (value != nullptr) oid = JNICHECKED(env, CallIntMethod(value, g_internal->m_jmethodNWObjectgetOid)); Globals::VirtualMachine()->StackPushObject(static_cast<uint32_t>(oid)); } JNIEXPORT jobject JNICALL Internal::NWScriptPopObject(JNIEnv* env, jobject obj) { uint32_t oid; if (!Globals::VirtualMachine()->StackPopObject(&oid)) throw std::runtime_error("Cannot pop a oid off the VM stack."); auto r = JNICHECKED(env, CallStaticObjectMethod(g_internal->m_jclassNWObject, g_internal->m_jmethodNWObjectCreate, oid)); return r; } jobject JNIEXPORT JNICALL Internal::NWScriptPopVector(JNIEnv* env, jobject obj) { Vector vRetVal; if (!Globals::VirtualMachine()->StackPopVector(&vRetVal)) throw std::runtime_error("Cannot pop a Vector off the VM stack."); auto r = JNICHECKED(env, CallStaticObjectMethod(g_internal->m_jclassNWVector, g_internal->m_jmethodNWVectorCreate, vRetVal.x, vRetVal.y, vRetVal.z)); return r; } void JNIEXPORT JNICALL Internal::NWScriptPushVector(JNIEnv* env, jobject obj, jobject value) { Vector vec; vec.x = JNICHECKED(env, CallFloatMethod(value, g_internal->m_jmethodNWVectorgetX)); vec.y = JNICHECKED(env, CallFloatMethod(value, g_internal->m_jmethodNWVectorgetY)); vec.z = JNICHECKED(env, CallFloatMethod(value, g_internal->m_jmethodNWVectorgetZ)); Globals::VirtualMachine()->StackPushVector(vec); } jobject JNIEXPORT JNICALL Internal::NWScriptPopLocation(JNIEnv* env, jobject obj) { CScriptLocation *pRetVal; if (!Globals::VirtualMachine()->StackPopEngineStructure(ENGINE_STRUCTURE_LOCATION, (void **) &pRetVal)) throw std::runtime_error("Cannot pop a Location off the VM stack."); jobject ret_area = JNICHECKED(env, CallStaticObjectMethod(g_internal->m_jclassNWObject, g_internal->m_jmethodNWObjectCreate, pRetVal->m_oArea)); float facing = static_cast<float>(std::atan2(pRetVal->m_vOrientation.y, pRetVal->m_vOrientation.x) * (180 / 3.1415927)); while (facing > 360.0) facing -= 360.0; while (facing < 0.0) facing += 360.0; auto r = JNICHECKED(env, CallStaticObjectMethod(g_internal->m_jclassNWLocation, g_internal->m_jmethodNWLocationCreate, ret_area, pRetVal->m_vPosition.x, pRetVal->m_vPosition.y, pRetVal->m_vPosition.z, facing)); return r; } void JNIEXPORT JNICALL Internal::NWScriptPushLocation(JNIEnv* env, jobject obj, jobject value) { jobject area = JNICHECKED(env, CallObjectMethod(value, g_internal->m_jmethodNWLocationgetArea)); float facing = JNICHECKED(env, CallFloatMethod(value, g_internal->m_jmethodNWLocationgetFacing)); Vector vv; vv.x = JNICHECKED(env, CallFloatMethod(value, g_internal->m_jmethodNWLocationgetX)); vv.y = JNICHECKED(env, CallFloatMethod(value, g_internal->m_jmethodNWLocationgetY)); vv.z = JNICHECKED(env, CallFloatMethod(value, g_internal->m_jmethodNWLocationgetZ)); // This could use some love. We're letting the VM construct the engine_structure, but // doing it on this side would be faster. Globals::VirtualMachine()->StackPushFloat(facing); Globals::VirtualMachine()->StackPushVector(vv); NWScriptPushObject(env, obj, area); NWScriptCallFunction(env, obj, 215, 3); } jobject JNIEXPORT JNICALL Internal::NWScriptPopEffect(JNIEnv* env, jobject obj) { CGameEffect *pRetVal; if (!Globals::VirtualMachine()->StackPopEngineStructure(ENGINE_STRUCTURE_EFFECT, (void **) &pRetVal)) throw std::runtime_error("Cannot pop effect off the VM stack."); g_internal->TouchEffectAddress(pRetVal); // j_touchedEffects.insert(pRetVal); auto r = JNICHECKED(env, CallStaticObjectMethod(g_internal->m_jclassNWEffect, g_internal->m_jmethodNWEffectCreate, (long) pRetVal)); return r; } void JNIEXPORT JNICALL Internal::NWScriptPushEffect(JNIEnv* env, jobject obj, jobject value) { jint jid = JNICHECKED(env, CallIntMethod(value, g_internal->m_jmethodNWEffectgetOid)); CGameEffect* ptr = reinterpret_cast<CGameEffect*>(jid); if (!g_internal->IsEffectTouched(ptr)) { JNICHECKED(env, ThrowNew(g_internal->m_jclassNWInvalidEffectException, "Do not reuse effects from past context switches.")); return; } Globals::VirtualMachine()->StackPushEngineStructure(ENGINE_STRUCTURE_EFFECT, ptr); } jobject JNIEXPORT JNICALL Internal::NWScriptPopItemProperty(JNIEnv* env, jobject obj) { CGameEffect *pRetVal; if (!Globals::VirtualMachine()->StackPopEngineStructure(ENGINE_STRUCTURE_ITEMPROPERTY, (void **) &pRetVal)) throw std::runtime_error("Cannot pop itemproperty off the VM stack."); g_internal->TouchEffectAddress(pRetVal); auto r = JNICHECKED(env, CallStaticObjectMethod(g_internal->m_jclassNWItemProperty, g_internal->m_jmethodNWItemPropertyCreate, (long) pRetVal)); return r; } void JNIEXPORT JNICALL Internal::NWScriptPushItemProperty(JNIEnv* env, jobject obj, jobject value) { jint jid = JNICHECKED(env, CallIntMethod(value, g_internal->m_jmethodNWItemPropertygetOid)); CGameEffect* ptr = reinterpret_cast<CGameEffect*>(jid); if (!g_internal->IsEffectTouched(ptr)) { JNICHECKED(env, ThrowNew(g_internal->m_jclassNWInvalidItemPropertyException, "Do not reuse itemproperties from past context switches.")); return; } Globals::VirtualMachine()->StackPushEngineStructure(ENGINE_STRUCTURE_ITEMPROPERTY, ptr); } JNIEXPORT void JNICALL Internal::NWScriptCallFunction(JNIEnv* env, jobject obj, jint functionId, jint argc) { int r = reinterpret_cast<CNWVirtualMachineCommands*>(Globals::VirtualMachine()->m_pCmdImplementer)-> ExecuteCommand(functionId, argc); if (r != 0) throw std::runtime_error("CallFunction failed: " + std::to_string(r)); } JNIEXPORT jboolean JNICALL Internal::NWScriptCanCallVM(JNIEnv* env, jobject obj) { // TODO: We are in the VM when: // - the calling thread the main thread. return true; } void Internal::BindNWScript() { g_internal = this; DoAttached([&](JavaVM* vm, JNIEnv* env) { const JNINativeMethod methods[] = { { (char*) "popInteger", (char*) "()I", (void*) Internal::NWScriptPopInteger }, { (char*) "pushInteger", (char*) "(I)V", (void*) Internal::NWScriptPushInteger }, { (char*) "popFloat", (char*) "()F", (void*) Internal::NWScriptPopFloat }, { (char*) "pushFloat", (char*) "(F)V", (void*) Internal::NWScriptPushFloat }, { (char*) "popString", (char*) "()Ljava/lang/String;", (void*) Internal::NWScriptPopString }, { (char*) "pushString", (char*) "(Ljava/lang/String;)V", (void*) Internal::NWScriptPushString }, { (char*) "popObject", (char*) "()Lorg/nwnx/nwnx2/jvm/NWObject;", (void*) Internal::NWScriptPopObject }, { (char*) "pushObject", (char*) "(Lorg/nwnx/nwnx2/jvm/NWObject;)V", (void*) Internal::NWScriptPushObject }, { (char*) "popVector", (char*) "()Lorg/nwnx/nwnx2/jvm/NWVector;", (void*) Internal::NWScriptPopVector }, { (char*) "pushVector", (char*) "(Lorg/nwnx/nwnx2/jvm/NWVector;)V", (void*) Internal::NWScriptPushVector }, { (char*) "popLocation", (char*) "()Lorg/nwnx/nwnx2/jvm/NWLocation;", (void*) Internal::NWScriptPopLocation }, { (char*) "pushLocation", (char*) "(Lorg/nwnx/nwnx2/jvm/NWLocation;)V", (void*) Internal::NWScriptPushLocation }, { (char*) "popEffect", (char*) "()Lorg/nwnx/nwnx2/jvm/NWEffect;", (void*) Internal::NWScriptPopEffect }, { (char*) "pushEffect", (char*) "(Lorg/nwnx/nwnx2/jvm/NWEffect;)V", (void*) Internal::NWScriptPushEffect }, { (char*) "popItemProperty", (char*) "()Lorg/nwnx/nwnx2/jvm/NWItemProperty;", (void*) Internal::NWScriptPopItemProperty }, { (char*) "pushItemProperty", (char*) "(Lorg/nwnx/nwnx2/jvm/NWItemProperty;)V", (void*) Internal::NWScriptPushItemProperty }, { (char*) "callFunction", (char*) "(II)V", (void*) Internal::NWScriptCallFunction }, { (char*) "canCallVM", (char*) "()Z", (void*) Internal::NWScriptCanCallVM }, }; JNICHECKED(env, RegisterNatives(m_jclassNwscript, methods, 18)); }); } void Internal::UnbindNWScript() { DoAttached([&](JavaVM* vm, JNIEnv* env) { JNICHECKED(env, UnregisterNatives(m_jclassNwscript)); }); g_internal = nullptr; } }
42.722433
145
0.711908
acaos
9e1d75722c8b7c063101f156f436a3a30dcd83c5
5,365
cpp
C++
simulation/libsimulator/test/resolver.cpp
SylemST-UtilCollection/libtorrent-build
76c22d0f0aa0e6541983fa793789f3a5774cf0ca
[ "BSL-1.0", "BSD-3-Clause" ]
null
null
null
simulation/libsimulator/test/resolver.cpp
SylemST-UtilCollection/libtorrent-build
76c22d0f0aa0e6541983fa793789f3a5774cf0ca
[ "BSL-1.0", "BSD-3-Clause" ]
null
null
null
simulation/libsimulator/test/resolver.cpp
SylemST-UtilCollection/libtorrent-build
76c22d0f0aa0e6541983fa793789f3a5774cf0ca
[ "BSL-1.0", "BSD-3-Clause" ]
null
null
null
/* Copyright (c) 2015, Arvid Norberg All rights reserved. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "simulator/simulator.hpp" #include <functional> #include "catch.hpp" #ifdef __GNUC__ // for CATCH's CHECK macro #pragma GCC diagnostic ignored "-Wparentheses" #endif using namespace std::placeholders; using namespace sim; using asio::ip::make_address_v4; using asio::ip::address_v4; using duration = chrono::high_resolution_clock::duration; using chrono::duration_cast; using chrono::milliseconds; int num_lookups = 0; void on_name_lookup(boost::system::error_code const& ec , asio::ip::tcp::resolver::results_type ips) { ++num_lookups; int millis = int(duration_cast<milliseconds>(chrono::high_resolution_clock::now() .time_since_epoch()).count()); std::vector<address_v4> expect = { make_address_v4("1.2.3.4") , make_address_v4("1.2.3.5") , make_address_v4("1.2.3.6") , make_address_v4("1.2.3.7") }; auto expect_it = expect.begin(); for (auto const ip : ips) { assert(ip.endpoint().address() == *expect_it); assert(ip.endpoint().port() == 8080); ++expect_it; } assert(expect_it == expect.end()); } void on_failed_name_lookup(boost::system::error_code const& ec , asio::ip::tcp::resolver::results_type ips) { ++num_lookups; assert(ec == boost::system::error_code(asio::error::host_not_found)); int millis = int(duration_cast<milliseconds>(chrono::high_resolution_clock::now() .time_since_epoch()).count()); } struct sim_config : sim::default_config { duration hostname_lookup( asio::ip::address const& requestor , std::string hostname , std::vector<asio::ip::address>& result , boost::system::error_code& ec) { if (hostname == "test.com") { result = { make_address_v4("1.2.3.4") , make_address_v4("1.2.3.5") , make_address_v4("1.2.3.6") , make_address_v4("1.2.3.7") }; return duration_cast<duration>(chrono::milliseconds(50)); } return default_config::hostname_lookup(requestor, hostname, result, ec); } }; TEST_CASE("resolve multiple IPv4 addresses", "[resolver]") { sim_config cfg; simulation sim(cfg); chrono::high_resolution_clock::time_point start = chrono::high_resolution_clock::now(); num_lookups = 0; asio::io_context ios(sim, make_address_v4("40.30.20.10")); asio::ip::tcp::resolver resolver(ios); resolver.async_resolve("test.com", "8080" , std::bind(&on_name_lookup, _1, _2)); sim.run(); int millis = int(duration_cast<milliseconds>(chrono::high_resolution_clock::now() - start).count()); CHECK(millis == 50); CHECK(num_lookups == 1); } TEST_CASE("resolve non-existent hostname", "[resolver]") { sim_config cfg; simulation sim(cfg); chrono::high_resolution_clock::time_point start = chrono::high_resolution_clock::now(); num_lookups = 0; asio::io_context ios(sim, make_address_v4("40.30.20.10")); asio::ip::tcp::resolver resolver(ios); resolver.async_resolve("non-existent.com", "8080" , std::bind(&on_failed_name_lookup, _1, _2)); sim.run(); int millis = int(duration_cast<milliseconds>(chrono::high_resolution_clock::now() - start).count()); CHECK(millis == 100); CHECK(num_lookups == 1); } TEST_CASE("lookups resolve serially, compounding the latency", "[resolver]") { sim_config cfg; simulation sim(cfg); chrono::high_resolution_clock::time_point start = chrono::high_resolution_clock::now(); num_lookups = 0; asio::io_context ios(sim, make_address_v4("40.30.20.10")); asio::ip::tcp::resolver resolver(ios); resolver.async_resolve("non-existent.com", "8080", std::bind(&on_failed_name_lookup, _1, _2)); resolver.async_resolve("non-existent.com", "8080", std::bind(&on_failed_name_lookup, _1, _2)); sim.run(); int millis = int(duration_cast<milliseconds>(chrono::high_resolution_clock::now() - start).count()); CHECK(millis == 200); CHECK(num_lookups == 2); } TEST_CASE("resolve an IP address", "[resolver]") { sim_config cfg; simulation sim(cfg); chrono::high_resolution_clock::time_point start = chrono::high_resolution_clock::now(); num_lookups = 0; asio::io_context ios(sim, make_address_v4("40.30.20.10")); asio::ip::tcp::resolver resolver(ios); resolver.async_resolve("10.10.10.10", "8080" , [](boost::system::error_code const& ec, asio::ip::tcp::resolver::results_type ips) { ++num_lookups; std::vector<address_v4> expect = { make_address_v4("10.10.10.10") }; auto expect_it = expect.begin(); for (auto const ip : ips) { assert(ip.endpoint().address() == *expect_it); assert(ip.endpoint().port() == 8080); ++expect_it; } assert(expect_it == expect.end()); }); sim.run(); int millis = int(duration_cast<milliseconds>(chrono::high_resolution_clock::now() - start).count()); CHECK(millis == 0); CHECK(num_lookups == 1); }
26.959799
101
0.706803
SylemST-UtilCollection
9e1f6e281c5cf2c4cbbcd9f72eb58c587a16a49f
958
cpp
C++
impl/jamtemplate/common/state_manager/state_manager_transition_fade_to_black.cpp
runvs/1hgj_352
ee7bbab20729427ce9e5f861101a75f6b3f699d3
[ "CC0-1.0" ]
6
2021-09-05T08:31:36.000Z
2021-12-09T21:14:37.000Z
impl/jamtemplate/common/state_manager/state_manager_transition_fade_to_black.cpp
runvs/1hgj_352
ee7bbab20729427ce9e5f861101a75f6b3f699d3
[ "CC0-1.0" ]
30
2021-05-19T15:33:03.000Z
2022-03-30T19:26:37.000Z
impl/jamtemplate/common/state_manager/state_manager_transition_fade_to_black.cpp
runvs/1hgj_352
ee7bbab20729427ce9e5f861101a75f6b3f699d3
[ "CC0-1.0" ]
3
2021-05-23T16:06:01.000Z
2021-10-01T01:17:08.000Z
#include "state_manager_transition_fade_to_black.hpp" #include "math_helper.hpp" #include <iostream> namespace jt { StateManagerTransitionFadeToBlack::StateManagerTransitionFadeToBlack( Vector2f const& overlaySize, TextureManagerInterface& tm, float timerMax) : StateManagerTransitionImpl(timerMax) { m_shape = std::make_shared<jt::Shape>(); m_shape->makeRect(overlaySize, tm); m_shape->setColor(jt::Color { 0, 0, 0, 0 }); m_shape->setIgnoreCamMovement(true); } void StateManagerTransitionFadeToBlack::doUpdate(float elapsed) { std::uint8_t a { static_cast<std::uint8_t>(getRatio() * 255.0f) }; jt::Color const col { 0, 0, 0, a }; m_shape->setColor(col); m_shape->update(elapsed); } void StateManagerTransitionFadeToBlack::doStart() { m_shape->setColor(jt::Color { 0, 0, 0, 0 }); } void StateManagerTransitionFadeToBlack::doDraw(std::shared_ptr<jt::RenderTarget> rt) { m_shape->draw(rt); } } // namespace jt
29.030303
98
0.72547
runvs
9e20ab1b6a0e40e6b87f721039e8f1fe29b0b9e8
798
cpp
C++
src/system/boot/platform/generic/text_console.cpp
Yn0ga/haiku
74e271b2a286c239e60f0ec261f4f197f4727eee
[ "MIT" ]
2
2018-03-28T06:53:23.000Z
2021-05-26T19:35:01.000Z
src/system/boot/platform/generic/text_console.cpp
Yn0ga/haiku
74e271b2a286c239e60f0ec261f4f197f4727eee
[ "MIT" ]
null
null
null
src/system/boot/platform/generic/text_console.cpp
Yn0ga/haiku
74e271b2a286c239e60f0ec261f4f197f4727eee
[ "MIT" ]
null
null
null
/* * Copyright 2021, Haiku, Inc. All rights reserved. * Distributed under the terms of the MIT License. */ #include <boot/platform/generic/text_console.h> #include <boot/vfs.h> // This is set by the boot platform during console_init(). ConsoleNode* gConsoleNode; void console_clear_screen() { gConsoleNode->ClearScreen(); } int32 console_width() { return gConsoleNode->Width(); } int32 console_height() { return gConsoleNode->Height(); } void console_set_cursor(int32 x, int32 y) { gConsoleNode->SetCursor(x, y); } void console_show_cursor() { gConsoleNode->SetCursorVisible(true); } void console_hide_cursor(void) { gConsoleNode->SetCursorVisible(false); } void console_set_color(int32 foreground, int32 background) { gConsoleNode->SetColors(foreground, background); }
12.870968
58
0.743108
Yn0ga
9e23e11f78e9b498e214119f29e79ad06752bb93
7,595
cpp
C++
src/Plugins/ECEditor/ECEditor.cpp
realXtend/tundra-urho3d
436d41c3e3dd1a9b629703ee76fd0ef2ee212ef8
[ "Apache-2.0" ]
13
2015-02-25T02:42:38.000Z
2018-07-31T11:40:56.000Z
src/Plugins/ECEditor/ECEditor.cpp
realXtend/tundra-urho3d
436d41c3e3dd1a9b629703ee76fd0ef2ee212ef8
[ "Apache-2.0" ]
8
2015-02-12T22:27:05.000Z
2017-01-21T15:59:17.000Z
src/Plugins/ECEditor/ECEditor.cpp
realXtend/tundra-urho3d
436d41c3e3dd1a9b629703ee76fd0ef2ee212ef8
[ "Apache-2.0" ]
12
2015-03-25T21:10:50.000Z
2019-04-10T09:03:10.000Z
// For conditions of distribution and use, see copyright notice in LICENSE #include "StableHeaders.h" #include "Win.h" #include "ECEditor.h" #include "Framework.h" #include "SceneStructureWindow.h" #include "ECEditorWindow.h" #include "FileDialog.h" #include "AssetAPI.h" #include "UI/UiAPI.h" #include "UI/MenuBar.h" #include "UI/MenuBarItem.h" #include "SceneAPI.h" #include "Scene.h" #include "LoggingFunctions.h" #include <Urho3D/UI/UI.h> #include <Urho3D/Engine/Engine.h> #include <Urho3D/UI/UIElement.h> #include <Urho3D/UI/FileSelector.h> namespace Tundra { ECEditor::ECEditor(Framework* owner) : IModule("LoginScreen", owner), entityEditor_(0), sceneEditor_(0), sceneEditorItem_(0), openSceneItem_(0), newSceneItem_(0), fileBrowser_(0), saveSceneItem_(0) { } ECEditor::~ECEditor() { entityEditor_.Reset(); sceneEditor_.Reset(); } void ECEditor::Initialize() { entityEditor_ = new ECEditorWindow(GetFramework()); entityEditor_->Hide(); sceneEditor_ = new SceneStructureWindow(GetFramework(), this); sceneEditor_->Hide(); framework->Scene()->SceneCreated.Connect(this, &ECEditor::OnSceneCreated); MenuBar *menu = framework->Ui()->GetMenuBar(); if (menu != NULL) { newSceneItem_ = menu->CreateMenuItem("File/New Scene..."); newSceneItem_->OnItemPressed.Connect(this, &ECEditor::OnBarMenuSelected); openSceneItem_ = menu->CreateMenuItem("File/Open Scene..."); openSceneItem_->OnItemPressed.Connect(this, &ECEditor::OnBarMenuSelected); saveSceneItem_ = menu->CreateMenuItem("File/Save Scene..."); saveSceneItem_->OnItemPressed.Connect(this, &ECEditor::OnBarMenuSelected); sceneEditorItem_ = menu->CreateMenuItem("Edit/Scene Editor"); sceneEditorItem_->OnItemPressed.Connect(this, &ECEditor::OnBarMenuSelected); } // Enable system clipboard so we can copy & paste entities in editor. GetSubsystem<UI>()->SetUseSystemClipboard(true); } void ECEditor::Update(float UNUSED_PARAM(frametime)) { if (sceneEditor_.Get()) sceneEditor_->Update(); } void ECEditor::OpenSceneEditor() { SceneMap scenes = GetFramework()->Scene()->Scenes(); if (scenes.Values().Size() > 0) sceneEditor_->SetShownScene(scenes.Values()[0]); } void ECEditor::OpenSceneEditor(Scene *scene) { if (sceneEditor_.Get()) sceneEditor_->SetShownScene(scene); } void ECEditor::OpenEntityEditor(Entity *entity) { if (entityEditor_.Get()) { entityEditor_->SetEntity(entity->Id()); entityEditor_->Show(); } } void ECEditor::OpenEntityEditor(Entity *entity, IComponent *component) { if (entityEditor_.Get()) { entityEditor_->SetEntity(entity->Id()); entityEditor_->ScrollToComponent(component); entityEditor_->Show(); } } void ECEditor::OpenFileDialogWindow(const String &action) { if (fileBrowser_.Get()) { fileBrowser_.Reset(); } StringVector filters; filters.Push("*.txml"); fileBrowser_ = FileDialog::Open(framework); fileBrowser_->SetFilters(filters); if (action == "OpenScene") { fileBrowser_->SetTitle("Open Scene..."); fileBrowser_->OnDialogClosed.Connect(this, &ECEditor::OnOpenSceneDialogClosed); } else if (action == "NewScene") { fileBrowser_->SetTitle("Create new Scene..."); fileBrowser_->OnDialogClosed.Connect(this, &ECEditor::OnNewSceneDialogClosed); } else if (action == "SaveScene") { fileBrowser_->SetTitle("Save Scene as..."); fileBrowser_->OnDialogClosed.Connect(this, &ECEditor::OnSaveSceneDialogClosed); } } void ECEditor::OnOpenSceneDialogClosed(FileDialog* /*dialog*/, bool confirmed, const String &directory, const String &file) { if (!confirmed) return; OpenScene(directory, file); } void ECEditor::OnNewSceneDialogClosed(FileDialog* /*dialog*/, bool confirmed, const String &directory, const String &file) { if (!confirmed) return; CreateNewScene(directory, file); } void ECEditor::OnSaveSceneDialogClosed(FileDialog* /*dialog*/, bool confirmed, const String &directory, const String &file) { if (!confirmed) return; SaveSceneAs(directory, file); } void ECEditor::CreateNewScene(const String &directory, const String &file) { /// @todo validate file path and confirm the action. ScenePtr scene = framework->Scene()->SceneByName("TundraServer"); if (scene.Get()) framework->Scene()->RemoveScene("TundraServer"); ScenePtr newScene = framework->Scene()->CreateScene("TundraServer", true, true); if (newScene == NULL) return; String fullFilePath = directory + file; AssetStoragePtr storage = framework->Asset()->DeserializeAssetStorageFromString(fullFilePath, false); if (storage == NULL) { LogError("Failed to create asset storage for file " + fullFilePath); return; } framework->Asset()->SetDefaultAssetStorage(storage); AssetStorageVector storages = framework->Asset()->AssetStorages(); for (uint i = 0; i < storages.Size(); ++i) { if (storages[i].Get() && storages[i] != storage) framework->Asset()->RemoveAssetStorage(storages[i]->Name()); } newScene->SaveSceneXML(fullFilePath, false, true); } void ECEditor::OpenScene(const String &directory, const String &file) { /// @todo validate file path and confirm the action. String fullFilePath = directory + file; ScenePtr scene = framework->Scene()->SceneByName("TundraServer"); if (!scene.Get()) { scene = framework->Scene()->CreateScene("TundraServer", true, true); if (!scene.Get()) return; } AssetStoragePtr storage = framework->Asset()->DeserializeAssetStorageFromString(fullFilePath, false); if (storage.Get()) framework->Asset()->SetDefaultAssetStorage(storage); else { LogError("Failed to create asset storage for file " + fullFilePath); return; } AssetStorageVector storages = framework->Asset()->AssetStorages(); for (uint i = 0; i < storages.Size(); ++i) { if (storages[i].Get() && storages[i] != storage) framework->Asset()->RemoveAssetStorage(storages[i]->Name()); } framework->Asset()->SetDefaultAssetStorage(storage); scene->LoadSceneXML(fullFilePath, true, false, AttributeChange::Default); } void ECEditor::SaveSceneAs(const String &directory, const String &file) { ScenePtr scene = ScenePtr(framework->Scene()->MainCameraScene()); if (!scene.Get()) { SceneMap scenes = framework->Scene()->Scenes(); if (scenes.Size()) return; // Check if any scene exists if main camera scene is null. scene = scenes.Values()[0]; if (!scene.Get()) return; } String fullFilePath = directory + file; scene->SaveSceneXML(fullFilePath, false, true); } void ECEditor::OnBarMenuSelected(MenuBarItem *item) { if (sceneEditorItem_ == item) sceneEditor_->Show(); else if (openSceneItem_ == item) OpenFileDialogWindow("OpenScene"); else if (newSceneItem_ == item) OpenFileDialogWindow("NewScene"); else if (saveSceneItem_ == item) OpenFileDialogWindow("SaveScene");; } void ECEditor::OnSceneCreated(Scene *scene, AttributeChange::Type /*type*/) { OpenSceneEditor(scene); } } extern "C" { DLLEXPORT void TundraPluginMain(Tundra::Framework *fw) { fw->RegisterModule(new Tundra::ECEditor(fw)); } }
27.618182
123
0.665043
realXtend
9e26d52e7f8445379b9e0da30207d81035832aff
15,003
cc
C++
src/Publisher.cc
amtj/ign-transport
3b386bf46efd2fc0b847aa7fd3911b1d9d27546c
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
src/Publisher.cc
amtj/ign-transport
3b386bf46efd2fc0b847aa7fd3911b1d9d27546c
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
src/Publisher.cc
amtj/ign-transport
3b386bf46efd2fc0b847aa7fd3911b1d9d27546c
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
/* * Copyright (C) 2015 Open Source Robotics Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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 <cstdint> #include <cstring> #include <iostream> #include <string> #include "ignition/transport/Publisher.hh" using namespace ignition; using namespace transport; ////////////////////////////////////////////////// Publisher::Publisher(const std::string &_topic, const std::string &_addr, const std::string &_pUuid, const std::string &_nUuid, const Scope_t &_scope) : topic(_topic), addr(_addr), pUuid(_pUuid), nUuid(_nUuid), scope(_scope) { } ////////////////////////////////////////////////// std::string Publisher::Topic() const { return this->topic; } ////////////////////////////////////////////////// std::string Publisher::Addr() const { return this->addr; } ////////////////////////////////////////////////// std::string Publisher::PUuid() const { return this->pUuid; } ////////////////////////////////////////////////// std::string Publisher::NUuid() const { return this->nUuid; } ////////////////////////////////////////////////// Scope_t Publisher::Scope() const { return this->scope; } ////////////////////////////////////////////////// void Publisher::SetTopic(const std::string &_topic) { this->topic = _topic; } ////////////////////////////////////////////////// void Publisher::SetAddr(const std::string &_addr) { this->addr = _addr; } ////////////////////////////////////////////////// void Publisher::SetPUuid(const std::string &_pUuid) { this->pUuid = _pUuid; } ////////////////////////////////////////////////// void Publisher::SetNUuid(const std::string &_nUuid) { this->nUuid = _nUuid; } ////////////////////////////////////////////////// void Publisher::SetScope(const Scope_t &_scope) { this->scope = _scope; } ////////////////////////////////////////////////// size_t Publisher::Pack(char *_buffer) const { if (this->topic.empty() || this->addr.empty() || this->pUuid.empty() || this->nUuid.empty()) { std::cerr << "Publisher::Pack() error: You're trying to pack an " << "incomplete Publisher:" << std::endl << *this; return 0; } // null buffer. if (!_buffer) { std::cerr << "Publisher::Pack() error: NULL output buffer" << std::endl; return 0; } // Pack the topic length. uint16_t topicLength = static_cast<uint16_t>(this->topic.size()); memcpy(_buffer, &topicLength, sizeof(topicLength)); _buffer += sizeof(topicLength); // Pack the topic. memcpy(_buffer, this->topic.data(), static_cast<size_t>(topicLength)); _buffer += topicLength; // Pack the zeromq address length. uint16_t addrLength = static_cast<uint16_t>(this->addr.size()); memcpy(_buffer, &addrLength, sizeof(addrLength)); _buffer += sizeof(addrLength); // Pack the zeromq address. memcpy(_buffer, this->addr.data(), static_cast<size_t>(addrLength)); _buffer += addrLength; // Pack the process UUID length. uint16_t pUuidLength = static_cast<uint16_t>(this->pUuid.size()); memcpy(_buffer, &pUuidLength, sizeof(pUuidLength)); _buffer += sizeof(pUuidLength); // Pack the process UUID. memcpy(_buffer, this->pUuid.data(), static_cast<size_t>(pUuidLength)); _buffer += pUuidLength; // Pack the node UUID length. uint16_t nUuidLength = static_cast<uint16_t>(this->nUuid.size()); memcpy(_buffer, &nUuidLength, sizeof(nUuidLength)); _buffer += sizeof(nUuidLength); // Pack the node UUID. memcpy(_buffer, this->nUuid.data(), static_cast<size_t>(nUuidLength)); _buffer += nUuidLength; // Pack the topic scope. uint8_t intscope = static_cast<uint8_t>(this->scope); memcpy(_buffer, &intscope, sizeof(intscope)); return this->MsgLength(); } ////////////////////////////////////////////////// size_t Publisher::Unpack(char *_buffer) { // null buffer. if (!_buffer) { std::cerr << "Publisher::Unpack() error: NULL input buffer" << std::endl; return 0; } // Unpack the topic length. uint16_t topicLength; memcpy(&topicLength, _buffer, sizeof(topicLength)); _buffer += sizeof(topicLength); // Unpack the topic. this->topic = std::string(_buffer, _buffer + topicLength); _buffer += topicLength; // Unpack the zeromq address length. uint16_t addrLength; memcpy(&addrLength, _buffer, sizeof(addrLength)); _buffer += sizeof(addrLength); // Unpack the zeromq address. this->addr = std::string(_buffer, _buffer + addrLength); _buffer += addrLength; // Unpack the process UUID length. uint16_t pUuidLength; memcpy(&pUuidLength, _buffer, sizeof(pUuidLength)); _buffer += sizeof(pUuidLength); // Unpack the process UUID. this->pUuid = std::string(_buffer, _buffer + pUuidLength); _buffer += pUuidLength; // Unpack the node UUID length. uint16_t nUuidLength; memcpy(&nUuidLength, _buffer, sizeof(nUuidLength)); _buffer += sizeof(nUuidLength); // Unpack the node UUID. this->nUuid = std::string(_buffer, _buffer + nUuidLength); _buffer += nUuidLength; // Unpack the topic scope. uint8_t intscope; memcpy(&intscope, _buffer, sizeof(intscope)); this->scope = static_cast<Scope_t>(intscope); return this->MsgLength(); } ////////////////////////////////////////////////// size_t Publisher::MsgLength() const { return sizeof(uint16_t) + this->topic.size() + sizeof(uint16_t) + this->addr.size() + sizeof(uint16_t) + this->pUuid.size() + sizeof(uint16_t) + this->nUuid.size() + sizeof(uint8_t); } ////////////////////////////////////////////////// bool Publisher::operator==(const Publisher &_pub) const { return this->topic == _pub.topic && this->addr == _pub.addr && this->pUuid == _pub.pUuid && this->nUuid == _pub.nUuid && this->scope == _pub.scope; } ////////////////////////////////////////////////// bool Publisher::operator!=(const Publisher &_pub) const { return !(*this == _pub); } ////////////////////////////////////////////////// MessagePublisher::MessagePublisher(const std::string &_topic, const std::string &_addr, const std::string &_ctrl, const std::string &_pUuid, const std::string &_nUuid, const Scope_t &_scope, const std::string &_msgTypeName) : Publisher(_topic, _addr, _pUuid, _nUuid, _scope), ctrl(_ctrl), msgTypeName(_msgTypeName) { } ////////////////////////////////////////////////// size_t MessagePublisher::Pack(char *_buffer) const { if (this->ctrl.empty() || this->msgTypeName.empty()) { std::cerr << "MessagePublisher::Pack() error: You're trying to pack an " << "incomplete MessagePublisher:" << std::endl << *this; return 0; } // Pack the common part of any Publisher message. size_t len = Publisher::Pack(_buffer); if (len == 0) return 0; _buffer += len; // Pack the zeromq control address length. uint16_t ctrlLength = static_cast<uint16_t>(this->ctrl.size()); memcpy(_buffer, &ctrlLength, sizeof(ctrlLength)); _buffer += sizeof(ctrlLength); // Pack the zeromq control address. memcpy(_buffer, this->ctrl.data(), static_cast<size_t>(ctrlLength)); _buffer += ctrlLength; // Pack the type name length. uint16_t typeNameLength = static_cast<uint16_t>(this->msgTypeName.size()); memcpy(_buffer, &typeNameLength, sizeof(typeNameLength)); _buffer += sizeof(typeNameLength); // Pack the type name. memcpy(_buffer, this->msgTypeName.data(), static_cast<size_t>(typeNameLength)); return this->MsgLength(); } ////////////////////////////////////////////////// size_t MessagePublisher::Unpack(char *_buffer) { // null buffer. if (!_buffer) { std::cerr << "MessagePublisher::UnpackBody() error: NULL input buffer" << std::endl; return 0; } // Unpack the common part of any Publisher message. size_t len = Publisher::Unpack(_buffer); if (len == 0) return 0; _buffer += len; // Unpack the zeromq control address length. uint16_t ctrlLength; memcpy(&ctrlLength, _buffer, sizeof(ctrlLength)); _buffer += sizeof(ctrlLength); // Unpack the zeromq control address. this->ctrl = std::string(_buffer, _buffer + ctrlLength); _buffer += ctrlLength; // Unpack the type name length. uint16_t typeNameLength; memcpy(&typeNameLength, _buffer, sizeof(typeNameLength)); _buffer += sizeof(typeNameLength); // Unpack the type name. this->msgTypeName = std::string(_buffer, _buffer + typeNameLength); return this->MsgLength(); } ////////////////////////////////////////////////// size_t MessagePublisher::MsgLength() const { return Publisher::MsgLength() + sizeof(uint16_t) + this->ctrl.size() + sizeof(uint16_t) + this->msgTypeName.size(); } ////////////////////////////////////////////////// std::string MessagePublisher::Ctrl() const { return this->ctrl; } ////////////////////////////////////////////////// void MessagePublisher::SetCtrl(const std::string &_ctrl) { this->ctrl = _ctrl; } ////////////////////////////////////////////////// std::string MessagePublisher::MsgTypeName() const { return this->msgTypeName; } ////////////////////////////////////////////////// void MessagePublisher::SetMsgTypeName(const std::string &_msgTypeName) { this->msgTypeName = _msgTypeName; } ////////////////////////////////////////////////// bool MessagePublisher::operator==(const MessagePublisher &_pub) const { return Publisher::operator==(_pub) && this->ctrl == _pub.ctrl && this->msgTypeName == _pub.msgTypeName; } ////////////////////////////////////////////////// bool MessagePublisher::operator!=(const MessagePublisher &_pub) const { return !(*this == _pub); } ////////////////////////////////////////////////// ServicePublisher::ServicePublisher(const std::string &_topic, const std::string &_addr, const std::string &_socketId, const std::string &_pUuid, const std::string &_nUuid, const Scope_t &_scope, const std::string &_reqType, const std::string &_repType) : Publisher(_topic, _addr, _pUuid, _nUuid, _scope), socketId(_socketId), reqTypeName(_reqType), repTypeName(_repType) { } ////////////////////////////////////////////////// size_t ServicePublisher::Pack(char *_buffer) const { if (this->socketId.empty() || this->reqTypeName.empty() || this->repTypeName.empty()) { std::cerr << "ServicePublisher::Pack() error: You're trying to pack an " << "incomplete ServicePublisher:" << std::endl << *this; return 0; } // Pack the common part of any Publisher message. size_t len = Publisher::Pack(_buffer); if (len == 0) return 0; _buffer += len; // Pack the socket ID length. uint16_t socketIdLength = static_cast<uint16_t>(this->socketId.size()); memcpy(_buffer, &socketIdLength, sizeof(socketIdLength)); _buffer += sizeof(socketIdLength); // Pack the socket ID. memcpy(_buffer, this->socketId.data(), static_cast<size_t>(socketIdLength)); _buffer += socketIdLength; // Pack the request type length. uint16_t reqTypeLength = static_cast<uint16_t>(this->reqTypeName.size()); memcpy(_buffer, &reqTypeLength, sizeof(reqTypeLength)); _buffer += sizeof(reqTypeLength); // Pack the request type. memcpy(_buffer, this->reqTypeName.data(), static_cast<size_t>(reqTypeLength)); _buffer += reqTypeLength; // Pack the response type length. uint16_t repTypeLength = static_cast<uint16_t>(this->repTypeName.size()); memcpy(_buffer, &repTypeLength, sizeof(repTypeLength)); _buffer += sizeof(repTypeLength); // Pack the response. memcpy(_buffer, this->repTypeName.data(), static_cast<size_t>(repTypeLength)); return this->MsgLength(); } ////////////////////////////////////////////////// size_t ServicePublisher::Unpack(char *_buffer) { // null buffer. if (!_buffer) { std::cerr << "MessagePublisher::Unpack() error: NULL input buffer" << std::endl; return 0; } // Unpack the common part of any Publisher message. size_t len = Publisher::Unpack(_buffer); if (len == 0) return 0; _buffer += len; // Unpack the socket ID length. uint16_t socketIdLength; memcpy(&socketIdLength, _buffer, sizeof(socketIdLength)); _buffer += sizeof(socketIdLength); // Unpack the socket ID. this->socketId = std::string(_buffer, _buffer + socketIdLength); _buffer += socketIdLength; // Unpack the request type length. uint16_t reqTypeLength; memcpy(&reqTypeLength, _buffer, sizeof(reqTypeLength)); _buffer += sizeof(reqTypeLength); // Unpack the request type. this->reqTypeName = std::string(_buffer, _buffer + reqTypeLength); _buffer += reqTypeLength; // Unpack the response type length. uint16_t repTypeLength; memcpy(&repTypeLength, _buffer, sizeof(repTypeLength)); _buffer += sizeof(repTypeLength); // Unpack the response type. this->repTypeName = std::string(_buffer, _buffer + repTypeLength); _buffer += repTypeLength; return this->MsgLength(); } ////////////////////////////////////////////////// size_t ServicePublisher::MsgLength() const { return Publisher::MsgLength() + sizeof(uint16_t) + this->socketId.size() + sizeof(uint16_t) + this->reqTypeName.size() + sizeof(uint16_t) + this->repTypeName.size(); } ////////////////////////////////////////////////// std::string ServicePublisher::SocketId() const { return this->socketId; } ////////////////////////////////////////////////// void ServicePublisher::SetSocketId(const std::string &_socketId) { this->socketId = _socketId; } ////////////////////////////////////////////////// std::string ServicePublisher::ReqTypeName() const { return this->reqTypeName; } ////////////////////////////////////////////////// std::string ServicePublisher::RepTypeName() const { return this->repTypeName; } ////////////////////////////////////////////////// void ServicePublisher::SetReqTypeName(const std::string &_reqTypeName) { this->reqTypeName = _reqTypeName; } ////////////////////////////////////////////////// void ServicePublisher::SetRepTypeName(const std::string &_repTypeName) { this->repTypeName = _repTypeName; } ////////////////////////////////////////////////// bool ServicePublisher::operator==(const ServicePublisher &_srv) const { return Publisher::operator==(_srv) && this->socketId == _srv.socketId && this->reqTypeName == _srv.reqTypeName && this->repTypeName == _srv.repTypeName; } ////////////////////////////////////////////////// bool ServicePublisher::operator!=(const ServicePublisher &_srv) const { return !(*this == _srv); }
27.886617
80
0.603013
amtj
9e2aaf25ccb083bc8ac3b0a9ee518f7ffb2c8297
4,120
cpp
C++
visual_studio_environment_test/src/visual_studio_environment_test_app/test_intrinsics.cpp
cpsusie/cjm-numerics
9719f4aa7ed0fa157f4705e3f20f069e28a5755f
[ "MIT" ]
2
2021-04-18T07:35:56.000Z
2021-04-23T07:37:58.000Z
visual_studio_environment_test/src/visual_studio_environment_test_app/test_intrinsics.cpp
cpsusie/Int128
9719f4aa7ed0fa157f4705e3f20f069e28a5755f
[ "MIT" ]
29
2020-12-18T00:50:36.000Z
2021-03-22T21:35:18.000Z
visual_studio_environment_test/src/visual_studio_environment_test_app/test_intrinsics.cpp
cpsusie/cjm-numerics
9719f4aa7ed0fa157f4705e3f20f069e28a5755f
[ "MIT" ]
null
null
null
// Copyright © 2020-2021 CJM Screws, LLC // 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. // // CJM Screws, LLC is a Maryland Limited Liability Company. // No copyright claimed to unmodified original work of others. // The original, unmodified work of others, to the extent included in this library, // is licensed to you under the same terms under which it was licensed to CJM Screws, LLC. // For information about copyright and licensing of the original work of others, // see Notices file in cjm/ folder. #include "test_intrinsics.hpp" #ifdef CJM_CLANG_TEST_INTRINSICS_AVAILABLE void cjm::clang::test_program::intrinsics_test::print_intrinsic_availability_info() { constexpr auto newl = '\n'; const std::uint64_t first_operand = 0xc0de'd00d'fea2'b00b; const std::uint64_t second_operand = 0xdead'beef'600d'f00d; const std::uint64_t third_operand = 0x01ff'ffff'ffff'ffff; std::cout << "Printing results of intrinsics test .... " << newl; unsigned long bsrev_out = 0; unsigned char result = CJM_TEST_BITSCAN_REV_64(&bsrev_out, first_operand); if (result) { std::cout << "Bitscan rev intrin result: [" << bsrev_out << "]." << newl; } else { std::cout << "Bitscan rev intrin result found no set bits." << newl; } unsigned long long high_result = 0; auto low_result = CJM_TEST_UMUL128(first_operand, second_operand, &high_result); std::cout << "Umul result is high: [0x" << std::hex << std::setw(16) << std::setfill('0') << high_result << "]; low result: [0x" << std::hex << std::setw(16) << std::setfill('0') << low_result << "]." << newl; auto res = CJM_TEST_LZCNT_64(third_operand); std::cout << "Lzcount test result: [" << std::dec << res << "]." << newl; //This doesn't seem to work in clang! /*res = CJM_TEST_UDIV128(first_operand, second_operand, third_operand, &high_result); std::cout << "Udiv quot: [0x" << std::hex << std::setw(16) << std::setfill('0') << res << "]; remainder: [0x" << std::hex << std::setw(16) << std::setfill('0') << high_result << "]." << newl; */ res = CJM_TEST_LSHIFT128(first_operand, second_operand, 63); std::cout << "Lshift128 res: [0x" << std::hex << std::setw(16) << std::setfill('0') << res << "]." << newl; res = CJM_TEST_RSHIFT128(first_operand, second_operand, 63); std::cout << "Rshift128 res: [0x" << std::hex << std::setw(16) << std::setfill('0') << res << "]." << newl; unsigned char carry_out = CJM_TEST_ADDCARRY64(0, first_operand, second_operand, &high_result); std::cout << "Adc res: [0x" << std::hex << std::setw(16) << std::setfill('0') << high_result << "]; carry_out: [" << std::dec << +carry_out << "]." << newl; carry_out = CJM_TEST_SUBBORROW_64(0, second_operand, first_operand, &high_result); std::cout << "Sub-borrow res: [0x" << std::hex << std::setw(16) << std::setfill('0') << high_result << "]; carry_out: [" << std::dec << +carry_out << "]." << newl; std::cout << "END results of intrinsics test." << newl; } #else void cjm::clang::test_program::intrinsics_test::print_intrinsic_availability_info() { constexpr auto newl = '\n'; std::cout << "Intrinsics not available in this environment." << newl; } #endif
58.028169
210
0.700485
cpsusie
9e2d394371ede6bdc498346aaddee016c646311d
6,001
cpp
C++
TerraForm/terraindesigner.cpp
MasterQ32/TerraForm
78db64148440b8236794078833d371d0aed3d262
[ "MIT" ]
1
2020-03-16T19:59:25.000Z
2020-03-16T19:59:25.000Z
TerraForm/terraindesigner.cpp
MasterQ32/TerraForm
78db64148440b8236794078833d371d0aed3d262
[ "MIT" ]
null
null
null
TerraForm/terraindesigner.cpp
MasterQ32/TerraForm
78db64148440b8236794078833d371d0aed3d262
[ "MIT" ]
null
null
null
#include "terraindesigner.hpp" #include "dragdrop.hpp" #include "terrainfeaturegroup.hpp" #include <QDebug> #include <QtMath> #include <QMouseEvent> #include <QMimeData> static char const * const terrain_vert = R"glsl(#version 450 layout(location = 0) in float uVertexHeight; uniform mat4 uTransform; uniform int uTerrainSizeX; out float height; void main() { int x = gl_VertexID % uTerrainSizeX; int y = gl_VertexID / uTerrainSizeX; vec3 world = vec3( float(x), float(y), 0.0 ); height = uVertexHeight; gl_Position = uTransform * vec4(world, 1.0); gl_PointSize = 1.0; } )glsl"; static char const * const terrain_frag = R"glsl(#version 450 out vec4 fragment; // in vec3 normal; in float height; void main() { fragment = vec4(vec3(0.5 + 0.01 * height), 1.0); } )glsl"; static char const * const terrain_vertex_frag = R"glsl(#version 450 out vec4 fragment; uniform float uAlpha; void main() { fragment = vec4(1, 0, 0, uAlpha); } )glsl"; TerrainDesigner::TerrainDesigner(QWidget *parent) : TerrainRenderer(parent), terrain_pan(0, 0), terrain_zoom(1.1) { } void TerrainDesigner::initializeGL() { TerrainRenderer::initializeGL(); surface_program = std::make_unique<QOpenGLShaderProgram>(); surface_program->addShaderFromSourceCode(QOpenGLShader::Vertex, terrain_vert); surface_program->addShaderFromSourceCode(QOpenGLShader::Fragment, terrain_frag); surface_program->link(); vertex_program = std::make_unique<QOpenGLShaderProgram>(); vertex_program->addShaderFromSourceCode(QOpenGLShader::Vertex, terrain_vert); vertex_program->addShaderFromSourceCode(QOpenGLShader::Fragment, terrain_vertex_frag); vertex_program->link(); } void TerrainDesigner::paintGL() { gl.glClearColor(0.5f, 0.5f, 1.0f, 1.0f); gl.glClearDepth(1.0); gl.glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); if(not this->terrain()) return; vao->bind(); auto const mat = get_transform(); gl.glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); gl.glDisable(GL_CULL_FACE); gl.glDisable(GL_DEPTH_TEST); gl.glEnable(GL_PROGRAM_POINT_SIZE); surface_program->bind(); surface_program->setUniformValue("uTransform", mat); surface_program->setUniformValue("uTerrainSizeX", int(terrain()->width)); gl.glDrawElements(GL_TRIANGLES, 6 * (terrain()->width - 1) * (terrain()->height - 1), GL_UNSIGNED_INT, nullptr); // render the terrain vertices if(terrain_zoom >= 3.5f) { gl.glEnable(GL_BLEND); gl.glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); gl.glBlendEquation(GL_ADD); vertex_program->bind(); vertex_program->setUniformValue("uTransform", mat); vertex_program->setUniformValue("uTerrainSizeX", int(terrain()->width)); vertex_program->setUniformValue("uAlpha", glm::clamp(2.0f * (terrain_zoom - 3.5f), 0.0f, 1.0f)); gl.glDrawArrays(GL_POINTS, 0, terrain()->width * terrain()->height); gl.glDisable(GL_BLEND); } } void TerrainDesigner::mousePressEvent(QMouseEvent *event) { last_mousepos = event->pos(); } QVector3D TerrainDesigner::screen_to_world(int x, int y) const { auto const mat = get_transform().inverted(); float const fx = 2.0f * float(x) / float(this->width() - 1) - 1.0f; float const fy = 1.0f - 2.0f * float(y) / float(this->height() - 1); QVector4D const screen_space { fx, fy, 0.0, 1.0 }; auto const world_space = mat * screen_space; return QVector3D { world_space.x() / world_space.w(), world_space.y() / world_space.w(), world_space.z() / world_space.w(), }; } void TerrainDesigner::mouseMoveEvent(QMouseEvent *event) { auto const _new = screen_to_world(event->x(), event->y()); auto const _last = screen_to_world( last_mousepos.x(), last_mousepos.y()); auto const delta = _new - _last; last_mousepos = event->pos(); terrain_pan.x += delta.x(); terrain_pan.y += delta.y(); update(); } void TerrainDesigner::wheelEvent(QWheelEvent *event) { terrain_zoom += event->delta() / 1200.0f; terrain_zoom = glm::clamp(terrain_zoom, 0.5f, 5.0f); update(); } void TerrainDesigner::dragEnterEvent(QDragEnterEvent *event) { if (terrain() and event->mimeData()->hasFormat(DragDrop::FeatureFormat)) { event->setDropAction(Qt::CopyAction); event->accept(); } else { event->ignore(); } } void TerrainDesigner::dropEvent(QDropEvent *event) { if (terrain() and event->mimeData()->hasFormat(DragDrop::FeatureFormat)) { auto const payload = event->mimeData()->data(DragDrop::FeatureFormat); auto const feature = reinterpret_cast<TerrainFeatureType const * const &>(*payload.data()); auto const pos = screen_to_world(event->pos().x(), event->pos().y()); terrain()->add(std::unique_ptr<TerrainFeature>(feature->factory( *terrain(), pos.x(), pos.y()) )); terrain()->recalculate(); event->setDropAction(Qt::CopyAction); event->accept(); } else { event->ignore(); } } QMatrix4x4 TerrainDesigner::get_transform() const { if(terrain() == nullptr) return QMatrix4x4(); float w = terrain()->width; float h = terrain()->height; float a1 = w / h; float a2 = float(this->width()) / float(this->height()); if(a1 > a2) { h /= a2; } else { w *= a2; } w /= 2.0f; h /= 2.0f; QMatrix4x4 mat; mat.setToIdentity(); mat.ortho(-w, w, -h, h, 0.0f, 1.0f); mat.scale(terrain_zoom, terrain_zoom, terrain_zoom); mat.translate(terrain_pan.x, terrain_pan.y, 0.0); mat.translate( -float(terrain()->width) / 2.0f, -float(terrain()->height) / 2.0f, 0.0f ); return mat; }
24.295547
116
0.633228
MasterQ32
9e3125e679fe0b5943aab85924d6d4ce7ce2da3a
638
cpp
C++
HW1_T6.cpp
MihailBeloshapkin/TASK
d851d13717366b76e165b5dab1df84951efa3cf8
[ "Apache-2.0" ]
1
2020-02-12T10:52:25.000Z
2020-02-12T10:52:25.000Z
HW1_T6.cpp
MihailBeloshapkin/TASK
d851d13717366b76e165b5dab1df84951efa3cf8
[ "Apache-2.0" ]
null
null
null
HW1_T6.cpp
MihailBeloshapkin/TASK
d851d13717366b76e165b5dab1df84951efa3cf8
[ "Apache-2.0" ]
null
null
null
#include "pch.h" #include <stdio.h> int main() { int counter = 0; int operationCounter = 0; bool isSimilar = true; const int stringSize1 = 13; const int stringSize2 = 4; char string1[stringSize1] = "bckbcdbqbckc"; char string2[stringSize2] = "bck"; for (int i = 0; i < stringSize1 - stringSize2 + 1; i++) { while (isSimilar && operationCounter < stringSize2 - 1) { if (string1[i + operationCounter] != string2[operationCounter]) { isSimilar = false; } operationCounter++; } if (isSimilar) { counter++; } operationCounter = 0; isSimilar = true; } printf("Answer:%i", counter); return 0; }
18.764706
66
0.639498
MihailBeloshapkin
9e416225132157e9504bfb0557c67938e99e68e6
71,009
cpp
C++
turkey/instructions.cpp
AndrewAPrice/Turkey
aa3fab9bc344b1550eac306471b0513daf286e8a
[ "Apache-2.0" ]
1
2021-02-14T15:04:04.000Z
2021-02-14T15:04:04.000Z
turkey/instructions.cpp
AndrewAPrice/Turkey
aa3fab9bc344b1550eac306471b0513daf286e8a
[ "Apache-2.0" ]
null
null
null
turkey/instructions.cpp
AndrewAPrice/Turkey
aa3fab9bc344b1550eac306471b0513daf286e8a
[ "Apache-2.0" ]
null
null
null
#include "hooks.h" #include "turkey.h" // do nothing void turkey_interpreter_instruction_nop(TurkeyVM *vm) { } void turkey_interpreter_instruction_add(TurkeyVM *vm) { TurkeyVariable a, b; if(!vm->variable_stack.Pop(b)) b.type = TT_Null; if(!vm->variable_stack.Pop(a)) b.type = TT_Null; TurkeyVariable ret; ret.type = a.type; /* convert to the type of the left */ switch(a.type) { case TT_Array: if(b.type != TT_Array) ret.type = TT_Null; else ret.array = turkey_array_append(vm, a.array, b.array); break; case TT_Boolean: ret.boolean_value = a.boolean_value || turkey_to_boolean(vm, b); break; case TT_Buffer: if(b.type != TT_Buffer) ret.type = TT_Null; else ret.buffer = turkey_buffer_append(vm, a.buffer, b.buffer); break; case TT_Float: ret.float_value = a.float_value + turkey_to_float(vm, b); break; default: break; case TT_Unsigned: ret.unsigned_value = a.unsigned_value + turkey_to_unsigned(vm, b); break; case TT_Object: turkey_object_call_operator(vm, a.object, vm->string_table.ss_add, b); return; case TT_Signed: ret.signed_value = a.signed_value + turkey_to_signed(vm, b); break; case TT_String: { turkey_gc_hold(vm, a.string, TT_String); ret.string = turkey_string_append(vm, a.string, turkey_to_string(vm, b)); turkey_gc_unhold(vm, a.string, TT_String); break; } } vm->variable_stack.Push(ret); } void turkey_interpreter_instruction_subtract(TurkeyVM *vm) { TurkeyVariable a, b; if(!vm->variable_stack.Pop(b)) b.type = TT_Null; if(!vm->variable_stack.Pop(a)) a.type = TT_Null; TurkeyVariable ret; ret.type = a.type; /* convert to the type of the left */ switch(a.type) { default: ret.type = TT_Null; break; case TT_Boolean: ret.boolean_value = a.boolean_value && turkey_to_boolean(vm, b); break; case TT_Float: ret.float_value = a.float_value - turkey_to_float(vm, b); break; case TT_Unsigned: ret.unsigned_value = a.unsigned_value - turkey_to_unsigned(vm, b); break; case TT_Object: turkey_object_call_operator(vm, a.object, vm->string_table.ss_subtract, b); return; case TT_Signed: ret.signed_value = a.signed_value - turkey_to_signed(vm, b); break; } vm->variable_stack.Push(ret); } void turkey_interpreter_instruction_divide(TurkeyVM *vm) { TurkeyVariable a, b; if(!vm->variable_stack.Pop(b)) b.type = TT_Null; if(!vm->variable_stack.Pop(a)) a.type = TT_Null; TurkeyVariable ret; ret.type = a.type; /* convert to the type of the left */ switch(a.type) { default: ret.type = TT_Null; break; case TT_Float: ret.float_value = a.float_value / turkey_to_float(vm, b); break; case TT_Unsigned: ret.unsigned_value = a.unsigned_value / turkey_to_unsigned(vm, b); break; case TT_Object: turkey_object_call_operator(vm, a.object, vm->string_table.ss_divide, b); return; case TT_Signed: ret.signed_value = a.signed_value / turkey_to_signed(vm, b); break; } vm->variable_stack.Push(ret); } void turkey_interpreter_instruction_multiply(TurkeyVM *vm) { TurkeyVariable a, b; if(!vm->variable_stack.Pop(b)) b.type = TT_Null; if(!vm->variable_stack.Pop(a)) a.type = TT_Null; TurkeyVariable ret; ret.type = a.type; /* convert to the type of the left */ switch(a.type) { default: ret.type = TT_Null; break; case TT_Float: ret.float_value = a.float_value * turkey_to_float(vm, b); break; case TT_Unsigned: ret.unsigned_value = a.unsigned_value * turkey_to_unsigned(vm, b); break; case TT_Object: turkey_object_call_operator(vm, a.object, vm->string_table.ss_multiply, b); return; case TT_Signed: ret.signed_value = a.signed_value * turkey_to_signed(vm, b); break; } vm->variable_stack.Push(ret); } void turkey_interpreter_instruction_modulo(TurkeyVM *vm) { TurkeyVariable a, b; if(!vm->variable_stack.Pop(b)) b.type = TT_Null; if(!vm->variable_stack.Pop(a)) a.type = TT_Null; TurkeyVariable ret; ret.type = a.type; /* convert to the type of the left */ switch(a.type) { case TT_Float: ret.float_value = turkey_float_modulo(a.float_value, turkey_to_float(vm, b)); break; default: ret.type = TT_Null; break; case TT_Unsigned: ret.unsigned_value = a.unsigned_value % turkey_to_unsigned(vm, b); break; case TT_Object: turkey_object_call_operator(vm, a.object, vm->string_table.ss_modulo, b); return; case TT_Signed: ret.signed_value = a.signed_value % turkey_to_signed(vm, b); break; } vm->variable_stack.Push(ret); } void turkey_interpreter_instruction_increment(TurkeyVM *vm) { TurkeyVariable a; if(!vm->variable_stack.Pop(a)) a.type = TT_Null; TurkeyVariable ret; ret.type = a.type; /* convert to the type of the left */ switch(a.type) { default: ret.type = TT_Null; break; case TT_Boolean: ret.boolean_value = true; break; case TT_Float: ret.float_value = a.float_value + 1.0; break; case TT_Unsigned: ret.unsigned_value = a.unsigned_value + 1; break; case TT_Object: turkey_object_call_operator(vm, a.object, vm->string_table.ss_increment); return; case TT_Signed: ret.signed_value = a.signed_value + 1; break; } vm->variable_stack.Push(ret); } void turkey_interpreter_instruction_decrement(TurkeyVM *vm) { TurkeyVariable a; if(!vm->variable_stack.Pop(a)) a.type = TT_Null; TurkeyVariable ret; ret.type = a.type; /* convert to the type of the left */ switch(a.type) { default: ret.type = TT_Null; break; case TT_Boolean: ret.boolean_value = false; break; case TT_Float: ret.float_value = a.float_value - 1.0; break; case TT_Unsigned: ret.unsigned_value = a.unsigned_value - 1; break; case TT_Object: turkey_object_call_operator(vm, a.object, vm->string_table.ss_decrement); return; case TT_Signed: ret.signed_value = a.signed_value - 1; break; } vm->variable_stack.Push(ret); } void turkey_interpreter_instruction_xor(TurkeyVM *vm) { TurkeyVariable a, b; if(!vm->variable_stack.Pop(b)) b.type = TT_Null; if(!vm->variable_stack.Pop(a)) a.type = TT_Null; TurkeyVariable ret; ret.type = a.type; /* convert to the type of the left */ switch(a.type) { default: ret.type = TT_Null; break; case TT_Float: ret.type = TT_Signed; ret.signed_value = (signed long long int)a.float_value ^ turkey_to_signed(vm, b); break; case TT_Boolean: ret.boolean_value = a.boolean_value ^ turkey_to_boolean(vm, b); break; case TT_Unsigned: ret.unsigned_value = a.unsigned_value ^ turkey_to_unsigned(vm, b); break; case TT_Object: turkey_object_call_operator(vm, a.object, vm->string_table.ss_xor, b); return; case TT_Signed: ret.signed_value = a.signed_value ^ turkey_to_signed(vm, b); break; } vm->variable_stack.Push(ret); } void turkey_interpreter_instruction_and(TurkeyVM *vm) { TurkeyVariable a, b; if(!vm->variable_stack.Pop(b)) b.type = TT_Null; if(!vm->variable_stack.Pop(a)) a.type = TT_Null; TurkeyVariable ret; ret.type = a.type; /* convert to the type of the left */ switch(a.type) { default: ret.type = TT_Null; break; case TT_Float: ret.type = TT_Signed; ret.signed_value = (signed long long int)a.float_value & turkey_to_signed(vm, b); break; case TT_Boolean: ret.boolean_value = a.boolean_value & turkey_to_boolean(vm, b); break; case TT_Unsigned: ret.unsigned_value = a.unsigned_value & turkey_to_unsigned(vm, b); break; case TT_Object: turkey_object_call_operator(vm, a.object, vm->string_table.ss_and, b); return; case TT_Signed: ret.signed_value = a.signed_value & turkey_to_signed(vm, b); break; } vm->variable_stack.Push(ret); } void turkey_interpreter_instruction_or(TurkeyVM *vm) { TurkeyVariable a, b; if(!vm->variable_stack.Pop(b)) b.type = TT_Null; if(!vm->variable_stack.Pop(a)) a.type = TT_Null; TurkeyVariable ret; ret.type = a.type; /* convert to the type of the left */ switch(a.type) { default: ret.type = TT_Null; break; case TT_Float: ret.type = TT_Signed; ret.signed_value = (signed long long int)a.float_value | turkey_to_signed(vm, b); break; case TT_Boolean: ret.boolean_value = a.boolean_value | turkey_to_boolean(vm, b); break; case TT_Unsigned: ret.unsigned_value = a.unsigned_value | turkey_to_unsigned(vm, b); break; case TT_Object: turkey_object_call_operator(vm, a.object, vm->string_table.ss_or, b); return; case TT_Signed: ret.signed_value = a.signed_value | turkey_to_signed(vm, b); break; } vm->variable_stack.Push(ret); } void turkey_interpreter_instruction_not(TurkeyVM *vm) { TurkeyVariable a; if(!vm->variable_stack.Pop(a)) a.type = TT_Null; TurkeyVariable ret; ret.type = a.type; /* convert to the type of the left */ switch(a.type) { default: ret.type = TT_Null; break; case TT_Float: ret.type = TT_Signed; ret.signed_value = ~(signed long long int)a.float_value; break; case TT_Boolean: ret.boolean_value = !a.boolean_value; break; case TT_Unsigned: ret.unsigned_value = ~a.unsigned_value; break; case TT_Object: turkey_object_call_operator(vm, a.object, vm->string_table.ss_not); return; case TT_Signed: ret.signed_value = ~a.signed_value; break; } vm->variable_stack.Push(ret); } void turkey_interpreter_instruction_shift_left(TurkeyVM *vm) { TurkeyVariable a, b; if(!vm->variable_stack.Pop(b)) b.type = TT_Null; if(!vm->variable_stack.Pop(a)) a.type = TT_Null; TurkeyVariable ret; ret.type = a.type; /* convert to the type of the left */ switch(a.type) { default: ret.type = TT_Null; break; case TT_Float: case TT_Boolean: ret.type = TT_Signed; ret.signed_value = turkey_to_signed(vm, a) << turkey_to_signed(vm, b); break; case TT_Unsigned: ret.unsigned_value = a.unsigned_value << turkey_to_unsigned(vm, b); break; case TT_Object: turkey_object_call_operator(vm, a.object, vm->string_table.ss_shift_left, b); return; case TT_Signed: ret.signed_value = a.signed_value << turkey_to_signed(vm, b); break; } vm->variable_stack.Push(ret); } void turkey_interpreter_instruction_shift_right(TurkeyVM *vm) { TurkeyVariable a, b; if(!vm->variable_stack.Pop(b)) b.type = TT_Null; if(!vm->variable_stack.Pop(a)) a.type = TT_Null; TurkeyVariable ret; ret.type = a.type; /* convert to the type of the left */ switch(a.type) { default: ret.type = TT_Null; break; case TT_Float: case TT_Boolean: ret.type = TT_Signed; ret.signed_value = turkey_to_signed(vm, a) >> turkey_to_signed(vm, b); break; case TT_Unsigned: ret.unsigned_value = a.unsigned_value >> turkey_to_unsigned(vm, b); break; case TT_Object: turkey_object_call_operator(vm, a.object, vm->string_table.ss_shift_right, b); return; case TT_Signed: ret.signed_value = a.signed_value >> turkey_to_signed(vm, b); break; } vm->variable_stack.Push(ret); } void turkey_interpreter_instruction_rotate_left(TurkeyVM *vm) { TurkeyVariable a, b; if(!vm->variable_stack.Pop(b)) b.type = TT_Null; if(!vm->variable_stack.Pop(a)) a.type = TT_Null; TurkeyVariable ret; /* convert to the type of the left */ switch(a.type) { default: ret.type = TT_Null; break; case TT_Float: case TT_Boolean: case TT_Unsigned: case TT_Signed:{ ret.type = TT_Unsigned; uint64_t _a = turkey_to_signed(vm, a); uint64_t _b = turkey_to_signed(vm, b); ret.unsigned_value = (_a << _b) | (_a >> (64 - _b)); break; } case TT_Object: turkey_object_call_operator(vm, a.object, vm->string_table.ss_rotate_left, b); return; break; } vm->variable_stack.Push(ret); } void turkey_interpreter_instruction_rotate_right(TurkeyVM *vm) { TurkeyVariable a, b; if(!vm->variable_stack.Pop(b)) b.type = TT_Null; if(!vm->variable_stack.Pop(a)) a.type = TT_Null; TurkeyVariable ret; /* convert to the type of the left */ switch(a.type) { default: ret.type = TT_Null; break; case TT_Float: case TT_Boolean: case TT_Unsigned: case TT_Signed:{ ret.type = TT_Unsigned; uint64_t _a = turkey_to_signed(vm, a); uint64_t _b = turkey_to_signed(vm, b); ret.unsigned_value = (_a >> _b) | (_a << (64 - _b)); break; } case TT_Object: turkey_object_call_operator(vm, a.object, vm->string_table.ss_rotate_right, b); return; } vm->variable_stack.Push(ret); } void turkey_interpreter_instruction_is_null(TurkeyVM *vm) { TurkeyVariable var; if(!vm->variable_stack.Pop(var)) var.type = TT_Null; var.boolean_value = var.type == TT_Null; var.type = TT_Boolean; vm->variable_stack.Push(var); } void turkey_interpreter_instruction_is_not_null(TurkeyVM *vm) { TurkeyVariable var; if(!vm->variable_stack.Pop(var)) var.type = TT_Null; var.boolean_value = var.type != TT_Null; var.type = TT_Boolean; vm->variable_stack.Push(var); } void turkey_interpreter_instruction_equals(TurkeyVM *vm) { TurkeyVariable var1, var2, out; if(!vm->variable_stack.Pop(var1)) var1.type = TT_Null; if(!vm->variable_stack.Pop(var2)) var2.type = TT_Null; if(var1.type != var2.type) { if(TURKEY_IS_TYPE_NUMBER(var1.type) && TURKEY_IS_TYPE_NUMBER(var2.type)) { if(var1.type == TT_Float || var2.type == TT_Float) out.boolean_value = turkey_to_float(vm, var1) == turkey_to_float(vm, var2); else if(var1.type == TT_Signed || var2.type == TT_Signed) out.boolean_value = turkey_to_signed(vm, var1) == turkey_to_signed(vm, var2); else if(var1.type == TT_Unsigned || var2.type == TT_Unsigned) out.boolean_value = turkey_to_unsigned(vm, var1) == turkey_to_unsigned(vm, var2); else out.boolean_value = turkey_to_boolean(vm, var1) == turkey_to_boolean(vm, var2); } else out.boolean_value = false; } else { if(var1.type != TT_Null) // all null = null out.boolean_value = true; else out.boolean_value = var1.unsigned_value == var2.unsigned_value; } out.type = TT_Boolean; vm->variable_stack.Push(out); } void turkey_interpreter_instruction_not_equals(TurkeyVM *vm) { TurkeyVariable var1, var2, out; if(!vm->variable_stack.Pop(var1)) var1.type = TT_Null; if(!vm->variable_stack.Pop(var2)) var2.type = TT_Null; if(var1.type != var2.type) { if(TURKEY_IS_TYPE_NUMBER(var1.type) && TURKEY_IS_TYPE_NUMBER(var2.type)) { if(var1.type == TT_Float || var2.type == TT_Float) out.boolean_value = turkey_to_float(vm, var1) != turkey_to_float(vm, var2); else if(var1.type == TT_Signed || var2.type == TT_Signed) out.boolean_value = turkey_to_signed(vm, var1) != turkey_to_signed(vm, var2); else if(var1.type == TT_Unsigned || var2.type == TT_Unsigned) out.boolean_value = turkey_to_unsigned(vm, var1) != turkey_to_unsigned(vm, var2); else out.boolean_value = turkey_to_boolean(vm, var1) != turkey_to_boolean(vm, var2); } else out.boolean_value = true; } else { if(var1.type != TT_Null) // all null = null out.boolean_value = false; else out.boolean_value = var1.unsigned_value != var2.unsigned_value; } out.type = TT_Boolean; vm->variable_stack.Push(out); } void turkey_interpreter_instruction_less_than(TurkeyVM *vm) { TurkeyVariable a, b; if(!vm->variable_stack.Pop(b)) b.type = TT_Null; if(!vm->variable_stack.Pop(a)) a.type = TT_Null; TurkeyVariable ret; ret.type = TT_Boolean; switch(a.type) { default: ret.type = TT_Null; break; case TT_Boolean: ret.boolean_value = a.boolean_value && !(turkey_to_boolean(vm, b)); break; case TT_Float: ret.boolean_value = a.float_value < turkey_to_float(vm, b); break; case TT_Unsigned: ret.boolean_value = a.unsigned_value < turkey_to_unsigned(vm, b); break; case TT_Object: turkey_object_call_operator(vm, a.object, vm->string_table.ss_less_than, b); return; case TT_Signed: ret.boolean_value = a.signed_value < turkey_to_signed(vm, b); break; } vm->variable_stack.Push(ret); } void turkey_interpreter_instruction_greater_than(TurkeyVM *vm) { TurkeyVariable a, b; if(!vm->variable_stack.Pop(b)) b.type = TT_Null; if(!vm->variable_stack.Pop(a)) a.type = TT_Null; TurkeyVariable ret; ret.type = TT_Boolean; switch(a.type) { default: ret.type = TT_Null; break; case TT_Boolean: ret.boolean_value = !a.boolean_value && (turkey_to_boolean(vm, b)); break; case TT_Float: ret.boolean_value = a.float_value > turkey_to_float(vm, b); break; case TT_Unsigned: ret.boolean_value = a.unsigned_value > turkey_to_unsigned(vm, b); break; case TT_Object: turkey_object_call_operator(vm, a.object, vm->string_table.ss_greater_than, b); return; case TT_Signed: ret.boolean_value = a.signed_value > turkey_to_signed(vm, b); break; } vm->variable_stack.Push(ret); } void turkey_interpreter_instruction_less_than_or_equals(TurkeyVM *vm) { TurkeyVariable a, b; if(!vm->variable_stack.Pop(b)) b.type = TT_Null; if(!vm->variable_stack.Pop(a)) a.type = TT_Null; TurkeyVariable ret; ret.type = TT_Boolean; switch(a.type) { default: ret.type = TT_Null; break; case TT_Boolean: ret.boolean_value = !a.boolean_value; break; case TT_Float: ret.boolean_value = a.float_value <= turkey_to_float(vm, b); break; case TT_Unsigned: ret.boolean_value = a.unsigned_value <= turkey_to_unsigned(vm, b); break; case TT_Object: turkey_object_call_operator(vm, a.object, vm->string_table.ss_less_than_or_equals, b); return; case TT_Signed: ret.boolean_value = a.signed_value <= turkey_to_signed(vm, b); break; } vm->variable_stack.Push(ret); } void turkey_interpreter_instruction_greater_than_or_equals(TurkeyVM *vm) { TurkeyVariable a, b; if(!vm->variable_stack.Pop(b)) b.type = TT_Null; if(!vm->variable_stack.Pop(a)) a.type = TT_Null; TurkeyVariable ret; ret.type = TT_Boolean; switch(a.type) { default: ret.type = TT_Null; break; case TT_Boolean: ret.boolean_value = !turkey_to_boolean(vm, b); break; case TT_Float: ret.boolean_value = a.float_value >= turkey_to_float(vm, b); break; case TT_Unsigned: ret.boolean_value = a.unsigned_value >= turkey_to_unsigned(vm, b); break; case TT_Object: turkey_object_call_operator(vm, a.object, vm->string_table.ss_greater_than_or_equals, b); return; case TT_Signed: ret.boolean_value = a.signed_value >= turkey_to_signed(vm, b); break; } vm->variable_stack.Push(ret); } void turkey_interpreter_instruction_is_true(TurkeyVM *vm) { TurkeyVariable a; if(!vm->variable_stack.Pop(a)) a.type = TT_Null; bool _a = turkey_to_boolean(vm, a); TurkeyVariable ret; ret.type = TT_Boolean; ret.boolean_value = _a; vm->variable_stack.Push(ret); } void turkey_interpreter_instruction_is_false(TurkeyVM *vm) { TurkeyVariable a; if(!vm->variable_stack.Pop(a)) a.type = TT_Null; bool _a = turkey_to_boolean(vm, a); TurkeyVariable ret; ret.type = TT_Boolean; ret.boolean_value = !_a; vm->variable_stack.Push(ret); } void turkey_interpreter_instruction_pop(TurkeyVM *vm) { vm->variable_stack.PopNoReturn(); } void turkey_interpreter_instruction_pop_many(TurkeyVM *vm) { if(vm->interpreter_state->code_ptr >= vm->interpreter_state->code_end) return; size_t count = (size_t)*(unsigned char *)vm->interpreter_state->code_ptr; vm->interpreter_state->code_ptr++; while(count > 0) { vm->variable_stack.PopNoReturn(); count--; } } void turkey_interpreter_instruction_grab_8(TurkeyVM *vm) { if(vm->interpreter_state->code_ptr >= vm->interpreter_state->code_end) return; unsigned int grab = (unsigned int)*(unsigned char *)vm->interpreter_state->code_ptr; vm->interpreter_state->code_ptr++; turkey_grab(vm, grab); } void turkey_interpreter_instruction_grab_16(TurkeyVM *vm) { if(vm->interpreter_state->code_ptr + 1 >= vm->interpreter_state->code_end) return; unsigned int grab = (unsigned int)*(unsigned short *)vm->interpreter_state->code_ptr; vm->interpreter_state->code_ptr += 2; turkey_grab(vm, grab); } void turkey_interpreter_instruction_grab_32(TurkeyVM *vm) { if(vm->interpreter_state->code_ptr + 3 >= vm->interpreter_state->code_end) return; unsigned int grab = *(unsigned int *)vm->interpreter_state->code_ptr; vm->interpreter_state->code_ptr += 4; turkey_grab(vm, grab); } void turkey_interpreter_instruction_push_many_nulls(TurkeyVM *vm) { if(vm->interpreter_state->code_ptr >= vm->interpreter_state->code_end) return; size_t nulls = (size_t)*(unsigned char *)vm->interpreter_state->code_ptr; vm->interpreter_state->code_ptr++; for(;nulls > 0; nulls--) turkey_push_null(vm); } /* void turkey_interpreter_instruction_load_8(TurkeyVM *vm) { if(vm->interpreter_state->code_ptr >= vm->interpreter_state->code_end) return; unsigned int a = (unsigned int)*(char *)vm->interpreter_state->code_ptr; vm->interpreter_state->code_ptr++; TurkeyVariable var; turkey_stack_get(vm->local_stack, a, var); vm->variable_stack.Push(var); } void turkey_interpreter_instruction_load_16(TurkeyVM *vm) { if(vm->interpreter_state->code_ptr + 1 >= vm->interpreter_state->code_end) return; unsigned int a = (unsigned int)*(unsigned short *)vm->interpreter_state->code_ptr; vm->interpreter_state->code_ptr += 2; TurkeyVariable var; turkey_stack_get(vm->local_stack, a, var); vm->variable_stack.Push(var); } void turkey_interpreter_instruction_load_32(TurkeyVM *vm) { if(vm->interpreter_state->code_ptr + 3 >= vm->interpreter_state->code_end) return; unsigned int a = *(unsigned int *)vm->interpreter_state->code_ptr; vm->interpreter_state->code_ptr += 4; TurkeyVariable var; turkey_stack_get(vm->local_stack, a, var); vm->variable_stack.Push(var); }*/ void turkey_interpreter_instruction_store_8(TurkeyVM *vm) { if(vm->interpreter_state->code_ptr >= vm->interpreter_state->code_end) return; unsigned int a = (unsigned int)*(unsigned char *)vm->interpreter_state->code_ptr; vm->interpreter_state->code_ptr++; TurkeyVariable var; if(!vm->variable_stack.Pop(var)) var.type = TT_Null; vm->variable_stack.Set(a, var); } void turkey_interpreter_instruction_store_16(TurkeyVM *vm) { if(vm->interpreter_state->code_ptr + 1 >= vm->interpreter_state->code_end) return; unsigned int a = (unsigned int)*(unsigned short *)vm->interpreter_state->code_ptr; vm->interpreter_state->code_ptr += 2; TurkeyVariable var; if(!vm->variable_stack.Pop(var)) var.type = TT_Null; vm->variable_stack.Set( a, var); } void turkey_interpreter_instruction_store_32(TurkeyVM *vm) { if(vm->interpreter_state->code_ptr + 3 >= vm->interpreter_state->code_end) return; unsigned int a = *(unsigned int *)vm->interpreter_state->code_ptr; vm->interpreter_state->code_ptr += 4; TurkeyVariable var; if(!vm->variable_stack.Pop(var)) var.type = TT_Null; vm->variable_stack.Set( a, var); } void turkey_interpreter_instruction_swap_8(TurkeyVM *vm) { if(vm->interpreter_state->code_ptr + 1 >= vm->interpreter_state->code_end) return; unsigned int a = (unsigned int)*(unsigned char *)vm->interpreter_state->code_ptr; vm->interpreter_state->code_ptr++; unsigned int b = (unsigned int)*(unsigned char *)vm->interpreter_state->code_ptr; vm->interpreter_state->code_ptr++; turkey_swap(vm, a, b); } void turkey_interpreter_instruction_swap_16(TurkeyVM *vm) { if(vm->interpreter_state->code_ptr + 3 >= vm->interpreter_state->code_end) return; unsigned int a = (unsigned int)*(unsigned short *)vm->interpreter_state->code_ptr; vm->interpreter_state->code_ptr += 2; unsigned int b = (unsigned int)*(unsigned short *)vm->interpreter_state->code_ptr; vm->interpreter_state->code_ptr += 2; turkey_swap(vm, a, b); } void turkey_interpreter_instruction_swap_32(TurkeyVM *vm) { if(vm->interpreter_state->code_ptr + 7 >= vm->interpreter_state->code_end) return; unsigned int a = (unsigned int)*(unsigned int *)vm->interpreter_state->code_ptr; vm->interpreter_state->code_ptr += 4; unsigned int b = (unsigned int)*(unsigned int *)vm->interpreter_state->code_ptr; vm->interpreter_state->code_ptr += 4; turkey_swap(vm, a, b); } void turkey_interpreter_instruction_load_closure_8(TurkeyVM *vm) { if(vm->interpreter_state->code_ptr >= vm->interpreter_state->code_end) return; unsigned int a = (unsigned int)*(unsigned char *)vm->interpreter_state->code_ptr; vm->interpreter_state->code_ptr++; TurkeyVariable var; turkey_closure_get(vm, a, var); vm->variable_stack.Push(var); } void turkey_interpreter_instruction_load_closure_16(TurkeyVM *vm) { if(vm->interpreter_state->code_ptr + 1 >= vm->interpreter_state->code_end) return; unsigned int a = (unsigned int)*(unsigned short *)vm->interpreter_state->code_ptr; vm->interpreter_state->code_ptr += 2; TurkeyVariable var; turkey_closure_get(vm, a, var); vm->variable_stack.Push(var); } void turkey_interpreter_instruction_load_closure_32(TurkeyVM *vm) { if(vm->interpreter_state->code_ptr + 3 >= vm->interpreter_state->code_end) return; unsigned int a = *(unsigned int *)vm->interpreter_state->code_ptr; vm->interpreter_state->code_ptr += 4; TurkeyVariable var; turkey_closure_get(vm, a, var); vm->variable_stack.Push(var); } void turkey_interpreter_instruction_store_closure_8(TurkeyVM *vm) { if(vm->interpreter_state->code_ptr >= vm->interpreter_state->code_end) return; unsigned int a = (unsigned int)*(unsigned char *)vm->interpreter_state->code_ptr; vm->interpreter_state->code_ptr++; TurkeyVariable var; if(!vm->variable_stack.Pop(var)) var.type = TT_Null; turkey_closure_set(vm, a, var); } void turkey_interpreter_instruction_store_closure_16(TurkeyVM *vm) { if(vm->interpreter_state->code_ptr + 1 >= vm->interpreter_state->code_end) return; unsigned int a = (unsigned int)*(unsigned short *)vm->interpreter_state->code_ptr; vm->interpreter_state->code_ptr += 2; TurkeyVariable var; if(!vm->variable_stack.Pop(var)) var.type = TT_Null; turkey_closure_set(vm, a, var); } void turkey_interpreter_instruction_store_closure_32(TurkeyVM *vm) { if(vm->interpreter_state->code_ptr + 3 >= vm->interpreter_state->code_end) return; unsigned int a = *(unsigned int *)vm->interpreter_state->code_ptr; vm->interpreter_state->code_ptr += 4; TurkeyVariable var; if(!vm->variable_stack.Pop(var)) var.type = TT_Null; turkey_closure_set(vm, a, var); } void turkey_interpreter_instruction_new_array(TurkeyVM *vm) { TurkeyVariable a; if(!vm->variable_stack.Pop(a)) a.type = TT_Null; TurkeyVariable ret; ret.type = TT_Array; ret.array = turkey_array_new(vm, (unsigned int)turkey_to_unsigned(vm, a)); vm->variable_stack.Push(ret); } void turkey_interpreter_instruction_load_element(TurkeyVM *vm) { TurkeyVariable key, b; if(!vm->variable_stack.Pop(b)) b.type = TT_Null; if(!vm->variable_stack.Pop(key)) key.type = TT_Null; TurkeyVariable element; switch(b.type) { default: element.type = TT_Null; break; case TT_Array: element = turkey_array_get_element(vm, b.array, (unsigned int)turkey_to_unsigned(vm, key)); break; case TT_Object: { turkey_gc_hold(vm, b.object, TT_Object); element = turkey_object_get_property(vm, b.object, turkey_to_string(vm, key)); turkey_gc_unhold(vm, b.object, TT_Object); } break; case TT_String: { uint64_t pos = turkey_to_unsigned(vm, key); if(pos >= b.string->length) element.type = TT_Null; else { element.type = TT_Unsigned; element.unsigned_value = (uint64_t)key.string->string[pos]; } break; } } vm->variable_stack.Push(element); } void turkey_interpreter_instruction_save_element(TurkeyVM *vm) { TurkeyVariable key, b, element; if(!vm->variable_stack.Pop(element)) element.type = TT_Null; if(!vm->variable_stack.Pop(b)) b.type = TT_Null; if(!vm->variable_stack.Pop(key)) key.type = TT_Null; switch(b.type) { default: break; case TT_Array: turkey_array_set_element(vm, b.array, (unsigned int)turkey_to_unsigned(vm, key), element); break; case TT_Object: { turkey_gc_hold(vm, b.object, TT_Object); turkey_gc_hold(vm, element); turkey_object_set_property(vm, b.object, turkey_to_string(vm, key), element); turkey_gc_unhold(vm, b.object, TT_Object); turkey_gc_unhold(vm, element); } } } void turkey_interpreter_instruction_new_object(TurkeyVM *vm) { TurkeyVariable ret; ret.type = TT_Object; ret.object = turkey_object_new(vm); vm->variable_stack.Push(ret); } void turkey_interpreter_instruction_delete_element(TurkeyVM *vm) { TurkeyVariable key, b; if(!vm->variable_stack.Pop(b)) b.type = TT_Null; if(!vm->variable_stack.Pop(key)) key.type = TT_Null; if(b.type != TT_Object) return; turkey_gc_hold(vm, b.object, TT_Object); turkey_object_delete_property(vm, b.object, turkey_to_string(vm, key)); turkey_gc_unhold(vm, b.object, TT_Object); } void turkey_interpreter_instruction_new_buffer(TurkeyVM *vm) { TurkeyVariable a; if(!vm->variable_stack.Pop(a)) a.type = TT_Null; TurkeyVariable ret; ret.type = TT_Buffer; ret.buffer = turkey_buffer_new(vm, (unsigned int)turkey_to_unsigned(vm, a)); vm->variable_stack.Push(a); } void turkey_interpreter_instruction_load_buffer_unsigned_8(TurkeyVM *vm) { TurkeyVariable address, buffer; if(!vm->variable_stack.Pop(buffer)) buffer.type = TT_Null; if(!vm->variable_stack.Pop(address)) address.type = TT_Null; TurkeyVariable ret; if(buffer.type == TT_Buffer) { ret.type = TT_Unsigned; ret.unsigned_value = turkey_buffer_read_unsigned_8(vm, buffer.buffer, turkey_to_unsigned(vm, address)); } else ret.type = TT_Null; vm->variable_stack.Push(ret); } void turkey_interpreter_instruction_load_buffer_unsigned_16(TurkeyVM *vm) { TurkeyVariable address, buffer; if(!vm->variable_stack.Pop(buffer)) buffer.type = TT_Null; if(!vm->variable_stack.Pop(address)) address.type = TT_Null; TurkeyVariable ret; if(buffer.type == TT_Buffer) { ret.type = TT_Unsigned; ret.unsigned_value = turkey_buffer_read_unsigned_16(vm, buffer.buffer, turkey_to_unsigned(vm, address)); } else ret.type = TT_Null; vm->variable_stack.Push(ret); } void turkey_interpreter_instruction_load_buffer_unsigned_32(TurkeyVM *vm) { TurkeyVariable address, buffer; if(!vm->variable_stack.Pop(buffer)) buffer.type = TT_Null; if(!vm->variable_stack.Pop(address)) address.type = TT_Null; TurkeyVariable ret; if(buffer.type == TT_Buffer) { ret.type = TT_Unsigned; ret.unsigned_value = turkey_buffer_read_unsigned_32(vm, buffer.buffer, turkey_to_unsigned(vm, address)); } else ret.type = TT_Null; vm->variable_stack.Push(ret); } void turkey_interpreter_instruction_load_buffer_unsigned_64(TurkeyVM *vm) { TurkeyVariable address, buffer; if(!vm->variable_stack.Pop(buffer)) buffer.type = TT_Null; if(!vm->variable_stack.Pop(address)) address.type = TT_Null; TurkeyVariable ret; if(buffer.type == TT_Buffer) { ret.type = TT_Unsigned; ret.unsigned_value = turkey_buffer_read_unsigned_64(vm, buffer.buffer, turkey_to_unsigned(vm, address)); } else ret.type = TT_Null; vm->variable_stack.Push(ret); } void turkey_interpreter_instruction_store_buffer_unsigned_8(TurkeyVM *vm) { TurkeyVariable value, address, buffer; if(!vm->variable_stack.Pop(buffer)) buffer.type = TT_Null; if(!vm->variable_stack.Pop(address)) address.type = TT_Null; if(!vm->variable_stack.Pop(value)) value.type = TT_Null; if(buffer.type == TT_Buffer) turkey_buffer_write_unsigned_8(vm, buffer.buffer, turkey_to_unsigned(vm, address), turkey_to_unsigned(vm, value)); } void turkey_interpreter_instruction_store_buffer_unsigned_16(TurkeyVM *vm) { TurkeyVariable value, address, buffer; if(!vm->variable_stack.Pop(buffer)) buffer.type = TT_Null; if(!vm->variable_stack.Pop(address)) address.type = TT_Null; if(!vm->variable_stack.Pop(value)) value.type = TT_Null; if(buffer.type == TT_Buffer) turkey_buffer_write_unsigned_16(vm, buffer.buffer, turkey_to_unsigned(vm, address), turkey_to_unsigned(vm, value)); } void turkey_interpreter_instruction_store_buffer_unsigned_32(TurkeyVM *vm) { TurkeyVariable value, address, buffer; if(!vm->variable_stack.Pop(buffer)) buffer.type = TT_Null; if(!vm->variable_stack.Pop(address)) address.type = TT_Null; if(!vm->variable_stack.Pop(value)) value.type = TT_Null; if(buffer.type == TT_Buffer) turkey_buffer_write_unsigned_32(vm, buffer.buffer, turkey_to_unsigned(vm, address), turkey_to_unsigned(vm, value)); } void turkey_interpreter_instruction_store_buffer_unsigned_64(TurkeyVM *vm) { TurkeyVariable value, address, buffer; if(!vm->variable_stack.Pop(buffer)) buffer.type = TT_Null; if(!vm->variable_stack.Pop(address)) address.type = TT_Null; if(!vm->variable_stack.Pop(value)) value.type = TT_Null; if(buffer.type == TT_Buffer) turkey_buffer_write_unsigned_64(vm, buffer.buffer, turkey_to_unsigned(vm, address), turkey_to_unsigned(vm, value)); } void turkey_interpreter_instruction_load_buffer_signed_8(TurkeyVM *vm) { TurkeyVariable address, buffer; if(!vm->variable_stack.Pop(buffer)) buffer.type = TT_Null; if(!vm->variable_stack.Pop(address)) address.type = TT_Null; TurkeyVariable ret; if(buffer.type == TT_Buffer) { ret.type = TT_Signed; ret.signed_value = turkey_buffer_read_signed_8(vm, buffer.buffer, turkey_to_unsigned(vm, address)); } else ret.type = TT_Null; vm->variable_stack.Push(ret); } void turkey_interpreter_instruction_load_buffer_signed_16(TurkeyVM *vm) { TurkeyVariable address, buffer; if(!vm->variable_stack.Pop(buffer)) buffer.type = TT_Null; if(!vm->variable_stack.Pop(address)) address.type = TT_Null; TurkeyVariable ret; if(buffer.type == TT_Buffer) { ret.type = TT_Signed; ret.signed_value = turkey_buffer_read_signed_16(vm, buffer.buffer, turkey_to_unsigned(vm, address)); } else ret.type = TT_Null; vm->variable_stack.Push(ret); } void turkey_interpreter_instruction_load_buffer_signed_32(TurkeyVM *vm) { TurkeyVariable address, buffer; if(!vm->variable_stack.Pop(buffer)) buffer.type = TT_Null; if(!vm->variable_stack.Pop(address)) address.type = TT_Null; TurkeyVariable ret; if(buffer.type == TT_Buffer) { ret.type = TT_Signed; ret.signed_value = turkey_buffer_read_signed_32(vm, buffer.buffer, turkey_to_unsigned(vm, address)); } else ret.type = TT_Null; vm->variable_stack.Push(ret); } void turkey_interpreter_instruction_load_buffer_signed_64(TurkeyVM *vm) { TurkeyVariable address, buffer; if(!vm->variable_stack.Pop(buffer)) buffer.type = TT_Null; if(!vm->variable_stack.Pop(address)) address.type = TT_Null; TurkeyVariable ret; if(buffer.type == TT_Buffer) { ret.type = TT_Signed; ret.signed_value = turkey_buffer_read_signed_64(vm, buffer.buffer, turkey_to_unsigned(vm, address)); } else ret.type = TT_Null; vm->variable_stack.Push(ret); } void turkey_interpreter_instruction_store_buffer_signed_8(TurkeyVM *vm) { TurkeyVariable value, address, buffer; if(!vm->variable_stack.Pop(buffer)) buffer.type = TT_Null; if(!vm->variable_stack.Pop(address)) address.type = TT_Null; if(!vm->variable_stack.Pop(value)) value.type = TT_Null; if(buffer.type == TT_Buffer) turkey_buffer_write_signed_8(vm, buffer.buffer, turkey_to_unsigned(vm, address), turkey_to_signed(vm, value)); } void turkey_interpreter_instruction_store_buffer_signed_16(TurkeyVM *vm) { TurkeyVariable value, address, buffer; if(!vm->variable_stack.Pop(buffer)) buffer.type = TT_Null; if(!vm->variable_stack.Pop(address)) address.type = TT_Null; if(!vm->variable_stack.Pop(value)) value.type = TT_Null; if(buffer.type == TT_Buffer) turkey_buffer_write_signed_16(vm, buffer.buffer, turkey_to_unsigned(vm, address), turkey_to_signed(vm, value)); } void turkey_interpreter_instruction_store_buffer_signed_32(TurkeyVM *vm) { TurkeyVariable value, address, buffer; if(!vm->variable_stack.Pop(buffer)) buffer.type = TT_Null; if(!vm->variable_stack.Pop(address)) address.type = TT_Null; if(!vm->variable_stack.Pop(value)) value.type = TT_Null; if(buffer.type == TT_Buffer) turkey_buffer_write_signed_32(vm, buffer.buffer, turkey_to_unsigned(vm, address), turkey_to_signed(vm, value)); } void turkey_interpreter_instruction_store_buffer_signed_64(TurkeyVM *vm) { TurkeyVariable value, address, buffer; if(!vm->variable_stack.Pop(buffer)) buffer.type = TT_Null; if(!vm->variable_stack.Pop(address)) address.type = TT_Null; if(!vm->variable_stack.Pop(value)) value.type = TT_Null; if(buffer.type == TT_Buffer) turkey_buffer_write_signed_64(vm, buffer.buffer, turkey_to_unsigned(vm, address), turkey_to_signed(vm, value)); } void turkey_interpreter_instruction_load_buffer_float_32(TurkeyVM *vm) { TurkeyVariable address, buffer; if(!vm->variable_stack.Pop(buffer)) buffer.type = TT_Null; if(!vm->variable_stack.Pop(address)) address.type = TT_Null; TurkeyVariable ret; if(buffer.type == TT_Buffer) { ret.type = TT_Float; ret.float_value = turkey_buffer_read_float_32(vm, buffer.buffer, turkey_to_unsigned(vm, address)); } else ret.type = TT_Null; vm->variable_stack.Push(ret); } void turkey_interpreter_instruction_load_buffer_float_64(TurkeyVM *vm) { TurkeyVariable address, buffer; if(!vm->variable_stack.Pop(buffer)) buffer.type = TT_Null; if(!vm->variable_stack.Pop(address)) address.type = TT_Null; TurkeyVariable ret; if(buffer.type == TT_Buffer) { ret.type = TT_Float; ret.float_value = turkey_buffer_read_float_64(vm, buffer.buffer, turkey_to_unsigned(vm, address)); } else ret.type = TT_Null; vm->variable_stack.Push(ret); } void turkey_interpreter_instruction_store_buffer_float_32(TurkeyVM *vm) { TurkeyVariable value, address, buffer; if(!vm->variable_stack.Pop(buffer)) buffer.type = TT_Null; if(!vm->variable_stack.Pop(address)) address.type = TT_Null; if(!vm->variable_stack.Pop(value)) value.type = TT_Null; if(buffer.type == TT_Buffer) turkey_buffer_write_float_32(vm, buffer.buffer, turkey_to_unsigned(vm, address), turkey_to_float(vm, value)); } void turkey_interpreter_instruction_store_buffer_float_64(TurkeyVM *vm) { TurkeyVariable value, address, buffer; if(!vm->variable_stack.Pop(buffer)) buffer.type = TT_Null; if(!vm->variable_stack.Pop(address)) address.type = TT_Null; if(!vm->variable_stack.Pop(value)) value.type = TT_Null; if(buffer.type == TT_Buffer) turkey_buffer_write_float_64(vm, buffer.buffer, turkey_to_unsigned(vm, address), turkey_to_float(vm, value)); } void turkey_interpreter_instruction_push_integer_8(TurkeyVM *vm) { if(vm->interpreter_state->code_ptr >= vm->interpreter_state->code_end) return; long long int val = (long long int)*(signed char *)vm->interpreter_state->code_ptr; vm->interpreter_state->code_ptr++; TurkeyVariable var; var.type = TT_Signed; var.signed_value = val; vm->variable_stack.Push(var); } void turkey_interpreter_instruction_push_integer_16(TurkeyVM *vm) { if(vm->interpreter_state->code_ptr + 1 >= vm->interpreter_state->code_end) return; long long int val = (long long int)*(signed short *)vm->interpreter_state->code_ptr; vm->interpreter_state->code_ptr += 2; TurkeyVariable var; var.type = TT_Signed; var.signed_value = val; vm->variable_stack.Push(var); } void turkey_interpreter_instruction_push_integer_32(TurkeyVM *vm) { if(vm->interpreter_state->code_ptr + 3 >= vm->interpreter_state->code_end) return; long long int val = (long long int)*(int *)vm->interpreter_state->code_ptr; vm->interpreter_state->code_ptr += 4; TurkeyVariable var; var.type = TT_Signed; var.signed_value = val; vm->variable_stack.Push(var); } void turkey_interpreter_instruction_push_integer_64(TurkeyVM *vm) { if(vm->interpreter_state->code_ptr + 7 >= vm->interpreter_state->code_end) return; long long int val = *(long long int *)vm->interpreter_state->code_ptr; vm->interpreter_state->code_ptr += 8; TurkeyVariable var; var.type = TT_Signed; var.signed_value = val; vm->variable_stack.Push(var); } void turkey_interpreter_instruction_to_integer(TurkeyVM *vm) { TurkeyVariable var; if(!vm->variable_stack.Pop(var)) var.type = TT_Null; var.signed_value = turkey_to_signed(vm, var); var.type = TT_Signed; vm->variable_stack.Push(var); } void turkey_interpreter_instruction_push_unsigned_integer_8(TurkeyVM *vm) { if(vm->interpreter_state->code_ptr >= vm->interpreter_state->code_end) return; uint64_t val = (uint64_t)*(unsigned char *)vm->interpreter_state->code_ptr; vm->interpreter_state->code_ptr++; TurkeyVariable var; var.type = TT_Unsigned; var.unsigned_value = val; vm->variable_stack.Push(var); } void turkey_interpreter_instruction_push_unsigned_integer_16(TurkeyVM *vm) { if(vm->interpreter_state->code_ptr + 1 >= vm->interpreter_state->code_end) return; uint64_t val = (uint64_t)*(unsigned short *)vm->interpreter_state->code_ptr; vm->interpreter_state->code_ptr += 2; TurkeyVariable var; var.type = TT_Unsigned; var.unsigned_value = val; vm->variable_stack.Push(var); } void turkey_interpreter_instruction_push_unsigned_integer_32(TurkeyVM *vm) { if(vm->interpreter_state->code_ptr + 3 >= vm->interpreter_state->code_end) return; uint64_t val = (uint64_t)*(unsigned int *)vm->interpreter_state->code_ptr; vm->interpreter_state->code_ptr += 4; TurkeyVariable var; var.type = TT_Unsigned; var.unsigned_value = val; vm->variable_stack.Push(var); } void turkey_interpreter_instruction_push_unsigned_integer_64(TurkeyVM *vm) { if(vm->interpreter_state->code_ptr + 7 >= vm->interpreter_state->code_end) return; uint64_t val = *(uint64_t *)vm->interpreter_state->code_ptr; vm->interpreter_state->code_ptr += 8; TurkeyVariable var; var.type = TT_Unsigned; var.unsigned_value = val; vm->variable_stack.Push(var); } void turkey_interpreter_instruction_to_unsigned_integer(TurkeyVM *vm) { TurkeyVariable var; if(!vm->variable_stack.Pop(var)) var.type = TT_Null; var.unsigned_value = turkey_to_unsigned(vm, var); var.type = TT_Unsigned; vm->variable_stack.Push(var); } void turkey_interpreter_instruction_push_float(TurkeyVM *vm) { if(vm->interpreter_state->code_ptr + 7 >= vm->interpreter_state->code_end) return; double val = *(double *)vm->interpreter_state->code_ptr; vm->interpreter_state->code_ptr += 8; TurkeyVariable var; var.type = TT_Float; var.float_value = val; vm->variable_stack.Push(var); } void turkey_interpreter_instruction_to_float(TurkeyVM *vm) { TurkeyVariable var; if(!vm->variable_stack.Pop(var)) var.type = TT_Null; var.float_value = turkey_to_float(vm, var); var.type = TT_Float; vm->variable_stack.Push(var); } void turkey_interpreter_instruction_push_true(TurkeyVM *vm) { turkey_push_boolean(vm, true); } void turkey_interpreter_instruction_push_false(TurkeyVM *vm) { turkey_push_boolean(vm, false); } void turkey_interpreter_instruction_push_null(TurkeyVM *vm) { turkey_push_null(vm); } void turkey_interpreter_instruction_push_string_8(TurkeyVM *vm) { if(vm->interpreter_state->code_ptr >= vm->interpreter_state->code_end) return; size_t a = (uint64_t)*(unsigned char *)vm->interpreter_state->code_ptr; vm->interpreter_state->code_ptr++; TurkeyModule *module = vm->interpreter_state->function->module; TurkeyVariable var; if(a >= module->string_count) var.type = TT_Null; else { var.type = TT_String; var.string = module->strings[a]; } vm->variable_stack.Push(var); } void turkey_interpreter_instruction_push_string_16(TurkeyVM *vm) { if(vm->interpreter_state->code_ptr + 1 >= vm->interpreter_state->code_end) return; size_t a = (uint64_t)*(unsigned short *)vm->interpreter_state->code_ptr; vm->interpreter_state->code_ptr += 2; TurkeyModule *module = vm->interpreter_state->function->module; TurkeyVariable var; if(a >= module->string_count) var.type = TT_Null; else { var.type = TT_String; var.string = module->strings[a]; } vm->variable_stack.Push(var); } void turkey_interpreter_instruction_push_string_32(TurkeyVM *vm) { if(vm->interpreter_state->code_ptr + 3 >= vm->interpreter_state->code_end) return; size_t a = (uint64_t)*(unsigned short *)vm->interpreter_state->code_ptr; vm->interpreter_state->code_ptr += 4; TurkeyModule *module = vm->interpreter_state->function->module; TurkeyVariable var; if(a >= module->string_count) var.type = TT_Null; else { var.type = TT_String; var.string = module->strings[a]; } vm->variable_stack.Push(var); } void turkey_interpreter_instruction_push_function(TurkeyVM *vm) { if(vm->interpreter_state->code_ptr + 3 >= vm->interpreter_state->code_end) return; unsigned int func_ind = *(unsigned int *)vm->interpreter_state->code_ptr; vm->interpreter_state->code_ptr += 4; TurkeyModule *module = vm->interpreter_state->function->module; TurkeyVariable ret; if(func_ind >= module->function_count) ret.type = TT_Null; else { ret.type = TT_FunctionPointer; ret.function = turkey_functionpointer_new(vm, module->functions[func_ind], vm->interpreter_state->closure); } vm->variable_stack.Push(ret); } void turkey_interpreter_instruction_call_function_8(TurkeyVM *vm) { if(vm->interpreter_state->code_ptr >= vm->interpreter_state->code_end) return; unsigned int argc = (unsigned int)*(unsigned char *)vm->interpreter_state->code_ptr; vm->interpreter_state->code_ptr++; TurkeyVariable func; if(!vm->variable_stack.Pop(func)) func.type = TT_Null; TurkeyVariable returnVar; if(func.type == TT_FunctionPointer) returnVar = turkey_call_function(vm, func.function, argc); else { while(argc > 0) { vm->variable_stack.PopNoReturn(); argc--; } returnVar.type = TT_Null; } vm->variable_stack.Push(returnVar); } void turkey_interpreter_instruction_call_function_16(TurkeyVM *vm) { if(vm->interpreter_state->code_ptr + 1>= vm->interpreter_state->code_end) return; unsigned int argc = (unsigned int)*(unsigned short *)vm->interpreter_state->code_ptr; vm->interpreter_state->code_ptr += 2; TurkeyVariable func; if(!vm->variable_stack.Pop(func)) func.type = TT_Null; TurkeyVariable returnVar; if(func.type == TT_FunctionPointer) returnVar = turkey_call_function(vm, func.function, argc); else { while(argc > 0) { vm->variable_stack.PopNoReturn(); argc--; } returnVar.type = TT_Null; } vm->variable_stack.Push(returnVar); } void turkey_interpreter_instruction_call_function_no_return_8(TurkeyVM *vm) { if(vm->interpreter_state->code_ptr >= vm->interpreter_state->code_end) return; unsigned int argc = (unsigned int)*(unsigned char *)vm->interpreter_state->code_ptr; vm->interpreter_state->code_ptr++; TurkeyVariable func; if(!vm->variable_stack.Pop(func)) func.type = TT_Null; if(func.type == TT_FunctionPointer) turkey_call_function_no_return(vm, func.function, argc); else { while(argc > 0) { vm->variable_stack.PopNoReturn(); argc--; } } } void turkey_interpreter_instruction_call_function_no_return_16(TurkeyVM *vm) { if(vm->interpreter_state->code_ptr + 1>= vm->interpreter_state->code_end) return; unsigned int argc = (unsigned int)*(unsigned short *)vm->interpreter_state->code_ptr; vm->interpreter_state->code_ptr += 2; TurkeyVariable func; if(!vm->variable_stack.Pop(func)) func.type = TT_Null; if(func.type == TT_FunctionPointer) turkey_call_function(vm, func.function, argc); else { while(argc > 0) { vm->variable_stack.PopNoReturn(); argc--; } } } void turkey_interpreter_instruction_return_null(TurkeyVM *vm) { TurkeyVariable var; var.type = TT_Null; vm->variable_stack.Push(var); vm->interpreter_state->executing = false; } void turkey_interpreter_instruction_return(TurkeyVM *vm) { vm->interpreter_state->executing = false; } void turkey_interpreter_instruction_get_type(TurkeyVM *vm) { TurkeyVariable var_in; if(!vm->variable_stack.Pop(var_in)) var_in.type = TT_Null; TurkeyString *str; switch(var_in.type) { case TT_Array: str = vm->string_table.s_array; break; case TT_Boolean: str = vm->string_table.s_boolean; break; case TT_Buffer: str = vm->string_table.s_buffer; break; case TT_Float: str = vm->string_table.s_float; break; case TT_Null: default: str = vm->string_table.s_null; break; case TT_FunctionPointer: str = vm->string_table.s_function; break; case TT_Unsigned: str = vm->string_table.s_unsigned; break; case TT_Object: str = vm->string_table.s_object; break; case TT_Signed: str = vm->string_table.s_signed; break; case TT_String: str = vm->string_table.s_string; break; } TurkeyVariable var; var.type = TT_String; var.string = str; vm->variable_stack.Push(var); } void turkey_interpreter_instruction_jump_8(TurkeyVM *vm) { if(vm->interpreter_state->code_ptr >= vm->interpreter_state->code_end) return; size_t ptr = (size_t)*(unsigned char *)vm->interpreter_state->code_ptr; vm->interpreter_state->code_ptr = vm->interpreter_state->code_start + ptr; } void turkey_interpreter_instruction_jump_16(TurkeyVM *vm) { if(vm->interpreter_state->code_ptr + 1 >= vm->interpreter_state->code_end) return; size_t ptr = (size_t)*(unsigned short *)vm->interpreter_state->code_ptr; vm->interpreter_state->code_ptr = vm->interpreter_state->code_start + ptr; } void turkey_interpreter_instruction_jump_32(TurkeyVM *vm) { if(vm->interpreter_state->code_ptr + 3 >= vm->interpreter_state->code_end) return; size_t ptr = (size_t)*(unsigned int *)vm->interpreter_state->code_ptr; vm->interpreter_state->code_ptr = vm->interpreter_state->code_start + ptr; } void turkey_interpreter_instruction_jump_if_true_8(TurkeyVM *vm) { if(vm->interpreter_state->code_ptr >= vm->interpreter_state->code_end) return; TurkeyVariable a; if(!vm->variable_stack.Pop(a)) a.type = TT_Null; if(turkey_to_boolean(vm, a)) { size_t ptr = (size_t)*(unsigned char *)vm->interpreter_state->code_ptr; vm->interpreter_state->code_ptr = vm->interpreter_state->code_start + ptr; } else vm->interpreter_state->code_ptr++; } void turkey_interpreter_instruction_jump_if_true_16(TurkeyVM *vm) { if(vm->interpreter_state->code_ptr + 1 >= vm->interpreter_state->code_end) return; TurkeyVariable a; if(!vm->variable_stack.Pop(a)) a.type = TT_Null; if(turkey_to_boolean(vm, a)) { size_t ptr = (size_t)*(unsigned short *)vm->interpreter_state->code_ptr; vm->interpreter_state->code_ptr = vm->interpreter_state->code_start + ptr; } else vm->interpreter_state->code_ptr += 2; } void turkey_interpreter_instruction_jump_if_true_32(TurkeyVM *vm) { if(vm->interpreter_state->code_ptr + 3 >= vm->interpreter_state->code_end) return; TurkeyVariable a; if(!vm->variable_stack.Pop(a)) a.type = TT_Null; if(turkey_to_boolean(vm, a)) { size_t ptr = (size_t)*(unsigned int *)vm->interpreter_state->code_ptr; vm->interpreter_state->code_ptr = vm->interpreter_state->code_start + ptr; } else vm->interpreter_state->code_ptr += 4; } void turkey_interpreter_instruction_jump_if_false_8(TurkeyVM *vm) { if(vm->interpreter_state->code_ptr >= vm->interpreter_state->code_end) return; TurkeyVariable a; if(!vm->variable_stack.Pop(a)) a.type = TT_Null; if(!turkey_to_boolean(vm, a)) { size_t ptr = (size_t)*(unsigned char *)vm->interpreter_state->code_ptr; vm->interpreter_state->code_ptr = vm->interpreter_state->code_start + ptr; } else vm->interpreter_state->code_ptr++; } void turkey_interpreter_instruction_jump_if_false_16(TurkeyVM *vm) { if(vm->interpreter_state->code_ptr + 1 >= vm->interpreter_state->code_end) return; TurkeyVariable a; if(!vm->variable_stack.Pop(a)) a.type = TT_Null; if(!turkey_to_boolean(vm, a)) { size_t ptr = (size_t)*(unsigned short *)vm->interpreter_state->code_ptr; vm->interpreter_state->code_ptr = vm->interpreter_state->code_start + ptr; } else vm->interpreter_state->code_ptr += 2; } void turkey_interpreter_instruction_jump_if_false_32(TurkeyVM *vm) { if(vm->interpreter_state->code_ptr + 3 >= vm->interpreter_state->code_end) return; TurkeyVariable a; if(!vm->variable_stack.Pop(a)) a.type = TT_Null; if(!turkey_to_boolean(vm, a)) { size_t ptr = (size_t)*(unsigned int *)vm->interpreter_state->code_ptr; vm->interpreter_state->code_ptr = vm->interpreter_state->code_start + ptr; } else vm->interpreter_state->code_ptr += 4; } void turkey_interpreter_instruction_jump_if_null_8(TurkeyVM *vm) { if(vm->interpreter_state->code_ptr >= vm->interpreter_state->code_end) return; TurkeyVariable a; if(!vm->variable_stack.Pop(a)) a.type = TT_Null; if(a.type == TT_Null) { size_t ptr = (size_t)*(unsigned char *)vm->interpreter_state->code_ptr; vm->interpreter_state->code_ptr = vm->interpreter_state->code_start + ptr; } else vm->interpreter_state->code_ptr++; } void turkey_interpreter_instruction_jump_if_null_16(TurkeyVM *vm) { if(vm->interpreter_state->code_ptr + 1 >= vm->interpreter_state->code_end) return; TurkeyVariable a; if(!vm->variable_stack.Pop(a)) a.type = TT_Null; if(a.type == TT_Null) { size_t ptr = (size_t)*(unsigned short *)vm->interpreter_state->code_ptr; vm->interpreter_state->code_ptr = vm->interpreter_state->code_start + ptr; } else vm->interpreter_state->code_ptr += 2; } void turkey_interpreter_instruction_jump_if_null_32(TurkeyVM *vm) { if(vm->interpreter_state->code_ptr + 3 >= vm->interpreter_state->code_end) return; TurkeyVariable a; if(!vm->variable_stack.Pop(a)) a.type = TT_Null; if(a.type == TT_Null) { size_t ptr = (size_t)*(unsigned int *)vm->interpreter_state->code_ptr; vm->interpreter_state->code_ptr = vm->interpreter_state->code_start + ptr; } else vm->interpreter_state->code_ptr += 4; } void turkey_interpreter_instruction_jump_if_not_null_8(TurkeyVM *vm) { if(vm->interpreter_state->code_ptr >= vm->interpreter_state->code_end) return; TurkeyVariable a; if(!vm->variable_stack.Pop(a)) a.type = TT_Null; if(a.type != TT_Null) { size_t ptr = (size_t)*(unsigned char *)vm->interpreter_state->code_ptr; vm->interpreter_state->code_ptr = vm->interpreter_state->code_start + ptr; } else vm->interpreter_state->code_ptr++; } void turkey_interpreter_instruction_jump_if_not_null_16(TurkeyVM *vm) { if(vm->interpreter_state->code_ptr + 1 >= vm->interpreter_state->code_end) return; TurkeyVariable a; if(!vm->variable_stack.Pop(a)) a.type = TT_Null; if(a.type != TT_Null) { size_t ptr = (size_t)*(unsigned short *)vm->interpreter_state->code_ptr; vm->interpreter_state->code_ptr = vm->interpreter_state->code_start + ptr; } else vm->interpreter_state->code_ptr += 2; } void turkey_interpreter_instruction_jump_if_not_null_32(TurkeyVM *vm) { if(vm->interpreter_state->code_ptr + 3 >= vm->interpreter_state->code_end) return; TurkeyVariable a; if(!vm->variable_stack.Pop(a)) a.type = TT_Null; if(a.type != TT_Null) { size_t ptr = (size_t)*(unsigned int *)vm->interpreter_state->code_ptr; vm->interpreter_state->code_ptr = vm->interpreter_state->code_start + ptr; } else vm->interpreter_state->code_ptr += 4; } void turkey_interpreter_instruction_require(TurkeyVM *vm) { TurkeyVariable a; if(!vm->variable_stack.Pop(a)) a.type = TT_Null; TurkeyString *strName = turkey_to_string(vm, a); TurkeyVariable ret = turkey_require(vm, strName); vm->variable_stack.Push(ret); } /* void turkey_interpreter_instruction_load_parameter_8(TurkeyVM *vm) { if(vm->interpreter_state->code_ptr >= vm->interpreter_state->code_end) return; unsigned int a = (unsigned int)*(unsigned char *)vm->interpreter_state->code_ptr; vm->interpreter_state->code_ptr++; TurkeyVariable var; turkey_stack_get(vm->parameter_stack, a, var); vm->variable_stack.Push(var); } void turkey_interpreter_instruction_load_parameter_16(TurkeyVM *vm) { if(vm->interpreter_state->code_ptr + 1 >= vm->interpreter_state->code_end) return; unsigned int a = (unsigned int)*(unsigned short *)vm->interpreter_state->code_ptr; vm->interpreter_state->code_ptr += 2; TurkeyVariable var; turkey_stack_get(vm->parameter_stack, a, var); vm->variable_stack.Push(var); } void turkey_interpreter_instruction_load_parameter_32(TurkeyVM *vm) { if(vm->interpreter_state->code_ptr + 3 >= vm->interpreter_state->code_end) return; unsigned int a = *(unsigned int *)vm->interpreter_state->code_ptr; vm->interpreter_state->code_ptr += 4; TurkeyVariable var; turkey_stack_get(vm->parameter_stack, a, var); vm->variable_stack.Push(var); } void turkey_interpreter_instruction_store_parameter_8(TurkeyVM *vm) { if(vm->interpreter_state->code_ptr >= vm->interpreter_state->code_end) return; unsigned int a = (unsigned int)*(unsigned char *)vm->interpreter_state->code_ptr; vm->interpreter_state->code_ptr++; TurkeyVariable var; if(!vm->variable_stack.Pop(var)) var.type = TT_Null; turkey_stack_set(vm->parameter_stack, a, var); } void turkey_interpreter_instruction_store_parameter_16(TurkeyVM *vm) { if(vm->interpreter_state->code_ptr + 1 >= vm->interpreter_state->code_end) return; unsigned int a = (unsigned int)*(unsigned short *)vm->interpreter_state->code_ptr; vm->interpreter_state->code_ptr += 2; TurkeyVariable var; if(!vm->variable_stack.Pop(var)) var.type = TT_Null; turkey_stack_set(vm->parameter_stack, a, var); } void turkey_interpreter_instruction_store_parameter_32(TurkeyVM *vm) { if(vm->interpreter_state->code_ptr + 3 >= vm->interpreter_state->code_end) return; unsigned int a = *(unsigned int *)vm->interpreter_state->code_ptr; vm->interpreter_state->code_ptr += 4; TurkeyVariable var; if(!vm->variable_stack.Pop(var)) var.type = TT_Null; turkey_stack_set(vm->parameter_stack, a, var); }*/ void turkey_interpreter_instruction_to_string(TurkeyVM *vm) { TurkeyVariable var; if(!vm->variable_stack.Pop(var)) var.type = TT_Null; switch(var.type) { case TT_String: vm->variable_stack.Push(var); return; // do nothing case TT_Buffer: case TT_Object: case TT_Array: assert(0); // Not implemented! break; default: TurkeyString *str = turkey_to_string(vm, var); var.string = str; break; } var.type = TT_String; vm->variable_stack.Push(var); } void turkey_interpreter_instruction_invert(TurkeyVM *vm) { TurkeyVariable a; if(!vm->variable_stack.Pop(a)) a.type = TT_Null; TurkeyVariable ret; ret.type = a.type; /* convert to the type of the left */ switch(a.type) { default: ret.type = TT_Null; break; case TT_Boolean: ret.boolean_value = !a.boolean_value; break; case TT_Float: ret.float_value = a.float_value * -1; break; case TT_Unsigned: ret.type = TT_Signed; ret.signed_value = (long long int)a.unsigned_value * -1; break; case TT_Object: { TurkeyVariable v; v.type = TT_Signed; v.signed_value = -1; turkey_object_call_operator(vm, a.object, vm->string_table.ss_multiply, v); return; } case TT_Signed: ret.signed_value = a.signed_value * -1; break; } vm->variable_stack.Push(ret); } TurkeyInstructionHandler turkey_interpreter_operations[256] = { turkey_interpreter_instruction_add, // 0 turkey_interpreter_instruction_subtract, // 1 turkey_interpreter_instruction_divide, // 2 turkey_interpreter_instruction_multiply, // 3 turkey_interpreter_instruction_modulo, // 4 turkey_interpreter_instruction_increment, // 5 turkey_interpreter_instruction_decrement, // 6 turkey_interpreter_instruction_xor, // 7 turkey_interpreter_instruction_and, // 8 turkey_interpreter_instruction_or, // 9 turkey_interpreter_instruction_not, // 10 turkey_interpreter_instruction_shift_left, // 11 turkey_interpreter_instruction_shift_right, // 12 turkey_interpreter_instruction_rotate_left, // 13 turkey_interpreter_instruction_rotate_right, // 14 turkey_interpreter_instruction_is_null, // 15 turkey_interpreter_instruction_is_not_null, // 16 turkey_interpreter_instruction_equals, // 17 turkey_interpreter_instruction_not_equals, // 18 turkey_interpreter_instruction_less_than, // 19 turkey_interpreter_instruction_greater_than, // 20 turkey_interpreter_instruction_less_than_or_equals, // 21 turkey_interpreter_instruction_greater_than_or_equals, // 22 turkey_interpreter_instruction_is_true, // 23 turkey_interpreter_instruction_is_false, // 24 turkey_interpreter_instruction_pop, // 25 turkey_interpreter_instruction_pop_many, // 26 turkey_interpreter_instruction_grab_8, // 27 turkey_interpreter_instruction_grab_16, // 28 turkey_interpreter_instruction_grab_32, // 29 turkey_interpreter_instruction_push_many_nulls, //turkey_interpreter_instruction_load_8, // 30 turkey_interpreter_instruction_nop, //turkey_interpreter_instruction_load_16, // 31 turkey_interpreter_instruction_nop, //turkey_interpreter_instruction_load_32, // 32 turkey_interpreter_instruction_store_8, // 33 turkey_interpreter_instruction_store_16, // 34 turkey_interpreter_instruction_store_32, // 35 turkey_interpreter_instruction_swap_8, // 36 turkey_interpreter_instruction_swap_16, // 37 turkey_interpreter_instruction_swap_32, // 38 turkey_interpreter_instruction_load_closure_8, // 39 turkey_interpreter_instruction_load_closure_16, // 40 turkey_interpreter_instruction_load_closure_32, // 41 turkey_interpreter_instruction_store_closure_8, // 42 turkey_interpreter_instruction_store_closure_16, // 43 turkey_interpreter_instruction_store_closure_32, // 44 turkey_interpreter_instruction_new_array, // 45 turkey_interpreter_instruction_load_element, // 46 turkey_interpreter_instruction_save_element, // 47 turkey_interpreter_instruction_new_object, // 48 turkey_interpreter_instruction_delete_element, // 49 turkey_interpreter_instruction_new_buffer, // 50 turkey_interpreter_instruction_load_buffer_unsigned_8, // 51 turkey_interpreter_instruction_load_buffer_unsigned_16, // 52 turkey_interpreter_instruction_load_buffer_unsigned_32, // 53 turkey_interpreter_instruction_load_buffer_unsigned_64, // 54 turkey_interpreter_instruction_store_buffer_unsigned_8, // 55 turkey_interpreter_instruction_store_buffer_unsigned_16, // 56 turkey_interpreter_instruction_store_buffer_unsigned_32, // 57 turkey_interpreter_instruction_store_buffer_unsigned_64, // 58 turkey_interpreter_instruction_load_buffer_signed_8, // 59 turkey_interpreter_instruction_load_buffer_signed_16, // 60 turkey_interpreter_instruction_load_buffer_signed_32, // 61 turkey_interpreter_instruction_load_buffer_signed_64, // 62 turkey_interpreter_instruction_store_buffer_signed_8, // 63 turkey_interpreter_instruction_store_buffer_signed_16, // 64 turkey_interpreter_instruction_store_buffer_signed_32, // 65 turkey_interpreter_instruction_store_buffer_signed_64, // 66 turkey_interpreter_instruction_nop, // 67 turkey_interpreter_instruction_load_buffer_float_32, // 68 turkey_interpreter_instruction_load_buffer_float_64, // 69 turkey_interpreter_instruction_nop, // 70 turkey_interpreter_instruction_store_buffer_float_32, // 71 turkey_interpreter_instruction_store_buffer_float_64, // 72 turkey_interpreter_instruction_push_integer_8, // 73 turkey_interpreter_instruction_push_integer_16, // 74 turkey_interpreter_instruction_push_integer_32, // 75 turkey_interpreter_instruction_push_integer_64, // 76 turkey_interpreter_instruction_to_integer, // 77 turkey_interpreter_instruction_push_unsigned_integer_8, // 78 turkey_interpreter_instruction_push_unsigned_integer_16, // 79 turkey_interpreter_instruction_push_unsigned_integer_32, // 80 turkey_interpreter_instruction_push_unsigned_integer_64, // 81 turkey_interpreter_instruction_to_unsigned_integer, // 82 turkey_interpreter_instruction_push_float, // 83 turkey_interpreter_instruction_to_float, // 84 turkey_interpreter_instruction_push_true, // 85 turkey_interpreter_instruction_push_false, // 86 turkey_interpreter_instruction_push_null, // 87 turkey_interpreter_instruction_push_string_8, // 88 turkey_interpreter_instruction_push_string_16, // 89 turkey_interpreter_instruction_push_string_32, // 90 turkey_interpreter_instruction_push_function, // 91 turkey_interpreter_instruction_call_function_8, // 92 turkey_interpreter_instruction_call_function_16, // 93 turkey_interpreter_instruction_call_function_no_return_8, // 94 turkey_interpreter_instruction_call_function_no_return_16, // 95 turkey_interpreter_instruction_return_null, // 96 turkey_interpreter_instruction_return, // 97 turkey_interpreter_instruction_get_type, // 98 turkey_interpreter_instruction_jump_8, // 99 turkey_interpreter_instruction_jump_16, // 100 turkey_interpreter_instruction_jump_32, // 101 turkey_interpreter_instruction_jump_if_true_8, // 102 turkey_interpreter_instruction_jump_if_true_16, // 103 turkey_interpreter_instruction_jump_if_true_32, // 104 turkey_interpreter_instruction_jump_if_false_8, // 105 turkey_interpreter_instruction_jump_if_false_16, // 106 turkey_interpreter_instruction_jump_if_false_32, // 107 turkey_interpreter_instruction_jump_if_null_8, // 108 turkey_interpreter_instruction_jump_if_null_16, // 109 turkey_interpreter_instruction_jump_if_null_32, // 110 turkey_interpreter_instruction_jump_if_not_null_8, // 111 turkey_interpreter_instruction_jump_if_not_null_16, // 112 turkey_interpreter_instruction_jump_if_not_null_32, // 113 turkey_interpreter_instruction_require, // 114 turkey_interpreter_instruction_nop, // turkey_interpreter_instruction_load_parameter_8, // 115 turkey_interpreter_instruction_nop, // turkey_interpreter_instruction_load_parameter_16, // 116 turkey_interpreter_instruction_nop, // turkey_interpreter_instruction_load_parameter_32, // 117 turkey_interpreter_instruction_nop, // turkey_interpreter_instruction_store_parameter_8, // 118 turkey_interpreter_instruction_nop, // turkey_interpreter_instruction_store_parameter_16, // 119 turkey_interpreter_instruction_nop, // turkey_interpreter_instruction_store_parameter_32, // 120 turkey_interpreter_instruction_to_string, // 121 turkey_interpreter_instruction_invert, // 122 turkey_interpreter_instruction_call_function_8, // 123 - actually procedure not function, but they do the same thing in the interpreter turkey_interpreter_instruction_call_function_16, // 124 - ditto turkey_interpreter_instruction_nop, // 125 turkey_interpreter_instruction_nop, // 126 turkey_interpreter_instruction_nop, // 127 turkey_interpreter_instruction_nop, // 128 turkey_interpreter_instruction_nop, // 129 turkey_interpreter_instruction_nop, // 130 turkey_interpreter_instruction_nop, // 131 turkey_interpreter_instruction_nop, // 132 turkey_interpreter_instruction_nop, // 133 turkey_interpreter_instruction_nop, // 134 turkey_interpreter_instruction_nop, // 135 turkey_interpreter_instruction_nop, // 136 turkey_interpreter_instruction_nop, // 137 turkey_interpreter_instruction_nop, // 138 turkey_interpreter_instruction_nop, // 139 turkey_interpreter_instruction_nop, // 140 turkey_interpreter_instruction_nop, // 141 turkey_interpreter_instruction_nop, // 142 turkey_interpreter_instruction_nop, // 143 turkey_interpreter_instruction_nop, // 144 turkey_interpreter_instruction_nop, // 145 turkey_interpreter_instruction_nop, // 146 turkey_interpreter_instruction_nop, // 147 turkey_interpreter_instruction_nop, // 148 turkey_interpreter_instruction_nop, // 149 turkey_interpreter_instruction_nop, // 150 turkey_interpreter_instruction_nop, // 151 turkey_interpreter_instruction_nop, // 152 turkey_interpreter_instruction_nop, // 153 turkey_interpreter_instruction_nop, // 154 turkey_interpreter_instruction_nop, // 155 turkey_interpreter_instruction_nop, // 156 turkey_interpreter_instruction_nop, // 157 turkey_interpreter_instruction_nop, // 158 turkey_interpreter_instruction_nop, // 159 turkey_interpreter_instruction_nop, // 160 turkey_interpreter_instruction_nop, // 161 turkey_interpreter_instruction_nop, // 162 turkey_interpreter_instruction_nop, // 163 turkey_interpreter_instruction_nop, // 164 turkey_interpreter_instruction_nop, // 165 turkey_interpreter_instruction_nop, // 166 turkey_interpreter_instruction_nop, // 167 turkey_interpreter_instruction_nop, // 168 turkey_interpreter_instruction_nop, // 169 turkey_interpreter_instruction_nop, // 170 turkey_interpreter_instruction_nop, // 171 turkey_interpreter_instruction_nop, // 172 turkey_interpreter_instruction_nop, // 173 turkey_interpreter_instruction_nop, // 174 turkey_interpreter_instruction_nop, // 175 turkey_interpreter_instruction_nop, // 176 turkey_interpreter_instruction_nop, // 177 turkey_interpreter_instruction_nop, // 178 turkey_interpreter_instruction_nop, // 179 turkey_interpreter_instruction_nop, // 180 turkey_interpreter_instruction_nop, // 181 turkey_interpreter_instruction_nop, // 182 turkey_interpreter_instruction_nop, // 183 turkey_interpreter_instruction_nop, // 184 turkey_interpreter_instruction_nop, // 185 turkey_interpreter_instruction_nop, // 186 turkey_interpreter_instruction_nop, // 187 turkey_interpreter_instruction_nop, // 188 turkey_interpreter_instruction_nop, // 189 turkey_interpreter_instruction_nop, // 190 turkey_interpreter_instruction_nop, // 191 turkey_interpreter_instruction_nop, // 192 turkey_interpreter_instruction_nop, // 193 turkey_interpreter_instruction_nop, // 194 turkey_interpreter_instruction_nop, // 195 turkey_interpreter_instruction_nop, // 196 turkey_interpreter_instruction_nop, // 197 turkey_interpreter_instruction_nop, // 198 turkey_interpreter_instruction_nop, // 199 turkey_interpreter_instruction_nop, // 200 turkey_interpreter_instruction_nop, // 201 turkey_interpreter_instruction_nop, // 202 turkey_interpreter_instruction_nop, // 203 turkey_interpreter_instruction_nop, // 204 turkey_interpreter_instruction_nop, // 205 turkey_interpreter_instruction_nop, // 206 turkey_interpreter_instruction_nop, // 207 turkey_interpreter_instruction_nop, // 208 turkey_interpreter_instruction_nop, // 209 turkey_interpreter_instruction_nop, // 210 turkey_interpreter_instruction_nop, // 211 turkey_interpreter_instruction_nop, // 212 turkey_interpreter_instruction_nop, // 213 turkey_interpreter_instruction_nop, // 214 turkey_interpreter_instruction_nop, // 215 turkey_interpreter_instruction_nop, // 216 turkey_interpreter_instruction_nop, // 217 turkey_interpreter_instruction_nop, // 218 turkey_interpreter_instruction_nop, // 219 turkey_interpreter_instruction_nop, // 220 turkey_interpreter_instruction_nop, // 221 turkey_interpreter_instruction_nop, // 222 turkey_interpreter_instruction_nop, // 223 turkey_interpreter_instruction_nop, // 224 turkey_interpreter_instruction_nop, // 225 turkey_interpreter_instruction_nop, // 226 turkey_interpreter_instruction_nop, // 227 turkey_interpreter_instruction_nop, // 228 turkey_interpreter_instruction_nop, // 229 turkey_interpreter_instruction_nop, // 230 turkey_interpreter_instruction_nop, // 231 turkey_interpreter_instruction_nop, // 232 turkey_interpreter_instruction_nop, // 233 turkey_interpreter_instruction_nop, // 234 turkey_interpreter_instruction_nop, // 235 turkey_interpreter_instruction_nop, // 236 turkey_interpreter_instruction_nop, // 237 turkey_interpreter_instruction_nop, // 238 turkey_interpreter_instruction_nop, // 239 turkey_interpreter_instruction_nop, // 240 turkey_interpreter_instruction_nop, // 241 turkey_interpreter_instruction_nop, // 242 turkey_interpreter_instruction_nop, // 243 turkey_interpreter_instruction_nop, // 244 turkey_interpreter_instruction_nop, // 245 turkey_interpreter_instruction_nop, // 246 turkey_interpreter_instruction_nop, // 247 turkey_interpreter_instruction_nop, // 248 turkey_interpreter_instruction_nop, // 249 turkey_interpreter_instruction_nop, // 250 turkey_interpreter_instruction_nop, // 251 turkey_interpreter_instruction_nop, // 252 turkey_interpreter_instruction_nop, // 253 turkey_interpreter_instruction_nop, // 254 turkey_interpreter_instruction_nop // 255 };
31.629844
136
0.762523
AndrewAPrice
9e45d4a8c77de0d29808520d9b8f184b21f27967
9,969
hpp
C++
src/analysis/include/mpi/SendRecvRule.hpp
rdietric/casita
02453e1467af10710dd87065c26bccd5d2026c67
[ "BSD-3-Clause" ]
5
2017-04-10T18:23:35.000Z
2022-02-21T00:27:23.000Z
src/analysis/include/mpi/SendRecvRule.hpp
rdietric/casita
02453e1467af10710dd87065c26bccd5d2026c67
[ "BSD-3-Clause" ]
1
2020-07-09T14:25:49.000Z
2020-07-13T19:30:18.000Z
src/analysis/include/mpi/SendRecvRule.hpp
rdietric/casita
02453e1467af10710dd87065c26bccd5d2026c67
[ "BSD-3-Clause" ]
1
2022-02-21T00:27:26.000Z
2022-02-21T00:27:26.000Z
/* * This file is part of the CASITA software * * Copyright (c) 2013-2018, * Technische Universitaet Dresden, Germany * * This software may be modified and distributed under the terms of * a BSD-style license. See the COPYING file in the package base * directory for details. * */ #pragma once #include "IMPIRule.hpp" #include "AnalysisParadigmMPI.hpp" namespace casita { namespace mpi { class SendRecvRule : public IMPIRule { public: SendRecvRule( int priority ) : IMPIRule( "SendRecvRule", priority ) { } private: /**\todo: simplify this rule. To a send and a receive operation? */ bool apply( AnalysisParadigmMPI* analysis, GraphNode* sendRecvLeave ) { // applied at MPI_SendRecv leave if ( !sendRecvLeave->isMPISendRecv() || !sendRecvLeave->isLeave() ) { return false; } AnalysisEngine* commonAnalysis = analysis->getAnalysisEngine(); // count occurrence commonAnalysis->getStatistics().countActivity( STAT_MPI_P2P ); commonAnalysis->getStatistics().countActivity( STAT_MPI_P2P ); MPIAnalysis& mpiAnalysis = commonAnalysis->getMPIAnalysis(); GraphNode* sendRecvEnter = sendRecvLeave->getGraphPair().first; uint32_t* data = (uint32_t*)( sendRecvLeave->getData() ); UTILS_ASSERT( data, "No data found for %s", sendRecvLeave->getUniqueName().c_str() ); int sendRank = (int) data[ 0 ]; uint32_t sendTag = data[ 1 ]; int recvRank = (int) data[ 2 ]; uint32_t recvTag = data[ 3 ]; delete[] data; const uint32_t comRef = (uint32_t) sendRecvLeave->getReferencedStreamId(); MPI_Comm communicator = mpiAnalysis.getMPICommGroup( comRef ).comm; uint64_t sendBuffer[ CASITA_MPI_P2P_BUF_SIZE ]; uint64_t recvBuffer[ CASITA_MPI_P2P_BUF_SIZE ]; const uint64_t myStartTime = sendRecvEnter->getTime(); const uint64_t myEndTime = sendRecvLeave->getTime(); // prepare send buffer sendBuffer[0] = myStartTime; sendBuffer[1] = myEndTime; sendBuffer[2] = sendRecvEnter->getId(); sendBuffer[3] = sendRecvLeave->getId(); sendBuffer[CASITA_MPI_P2P_BUF_LAST] = MPI_SEND | MPI_RECV; // replay: get information from receive rank MPI_CHECK( MPI_Sendrecv( sendBuffer, CASITA_MPI_P2P_BUF_SIZE, MPI_UINT64_T, sendRank, sendTag, //CASITA_MPI_REPLAY_TAG, recvBuffer, CASITA_MPI_P2P_BUF_SIZE, MPI_UINT64_T, recvRank, recvTag, //CASITA_MPI_REPLAY_TAG, communicator, MPI_STATUS_IGNORE ) ); // evaluate receive buffer const uint64_t recvRankStartTime = recvBuffer[0]; const uint64_t recvRankEndTime = recvBuffer[1]; const uint64_t recvRankEnterId = recvBuffer[2]; //uint64_t otherLeaveId = recvBuffer[3]; // if send and receive rank are the same we do not need the revers replay // as there is only one remote partner which also has sendRank == recvRank if( sendRank == recvRank ) { // handle similar to MPI_Recv // if this operation is early, it is blocking and not on the CP if ( myStartTime < recvRankStartTime ) { Edge* myEdge = commonAnalysis->getEdge( sendRecvEnter, sendRecvLeave ); if ( myEdge ) { myEdge->makeBlocking(); uint64_t partnerStreamId = mpiAnalysis.getStreamId( recvRank, comRef ); // point to potential continuation (node ID, stream ID) commonAnalysis->getMPIAnalysis().addRemoteMPIEdge( sendRecvLeave, recvRankEnterId, partnerStreamId ); } else { UTILS_OUT( "[%" PRIu64 "] SendRecvRule: Edge not found. " "Critical path analysis might fail!", sendRecvLeave->getStreamId() ); } // add waiting time to statistics commonAnalysis->getStatistics().addStatWithCount( MPI_STAT_SENDRECV, recvRankStartTime - myStartTime ); sendRecvLeave->incCounter( WAITING_TIME, recvRankStartTime - myStartTime ); } // if this operation starts after the other AND they are overlapping, else if ( myStartTime != recvRankStartTime && myStartTime < recvRankEndTime ) { distributeBlame( commonAnalysis, sendRecvEnter, myStartTime - recvRankStartTime, mpiStreamWalkCallback, REASON_MPI_LATE_SENDRECV ); } return true; } // send and receive rank are distinct // reverse replay: get information from send rank MPI_CHECK( MPI_Sendrecv( sendBuffer, CASITA_MPI_P2P_BUF_SIZE, MPI_UINT64_T, recvRank, recvTag + CASITA_MPI_REVERS_REPLAY_TAG, recvBuffer, CASITA_MPI_P2P_BUF_SIZE, MPI_UINT64_T, sendRank, sendTag + CASITA_MPI_REVERS_REPLAY_TAG, communicator, MPI_STATUS_IGNORE ) ); const uint64_t sendRankStartTime = recvBuffer[0]; const uint64_t sendRankEnterId = recvBuffer[2]; // set myself as last entering stream uint64_t lastStreamId = sendRecvLeave->getStreamId(); uint64_t lastNodeId = sendRecvLeave->getId(); uint64_t lastTime = myStartTime; // set my operation edge to NULL // (if it gets set, this operation is not the last) Edge* myEdge = NULL; // handle similar to MPI_Recv, as this operation cannot end before the // sender started (no overlap check needed) if ( myStartTime < recvRankStartTime ) { // this operation started early, hence it is blocking myEdge = commonAnalysis->getEdge( sendRecvEnter, sendRecvLeave ); if ( myEdge ) { myEdge->makeBlocking(); } else { UTILS_WARNING( "[%" PRIu64 "] SendrecvRule: Activity edge not found.", sendRecvLeave->getStreamId() ); } lastStreamId = mpiAnalysis.getStreamId( recvRank, comRef ); lastNodeId = recvRankEnterId; lastTime = recvRankStartTime; } // handle similar to MPI_Send (which is often buffered) // early sender/late receiver AND operations are overlapping if ( myStartTime < sendRankStartTime && myEndTime > sendRankStartTime ) { // this operation started before the receive rank operation // blocking edge is already set if( myEdge ) { // get the latest starter if( sendRankStartTime < recvRankStartTime ) { // receive rank is the latest lastStreamId = mpiAnalysis.getStreamId( recvRank, comRef ); lastNodeId = recvRankEnterId; lastTime = recvRankStartTime; } else { // send rank is the latest lastStreamId = mpiAnalysis.getStreamId( sendRank, comRef ); lastNodeId = sendRankEnterId; lastTime = sendRankStartTime; } } else// create blocking edge due to send rank operation { myEdge = commonAnalysis->getEdge( sendRecvEnter, sendRecvLeave ); if ( myEdge ) { myEdge->makeBlocking(); } else { UTILS_WARNING( "[%" PRIu64 "] SendrecvRule: Activity edge not found.", sendRecvLeave->getStreamId() ); } lastStreamId = mpiAnalysis.getStreamId( sendRank, comRef ); lastNodeId = sendRankEnterId; lastTime = sendRankStartTime; } } // if this operation is blocking, we need a continuation edge for CPA if( myEdge ) { uint64_t waitEnd = std::min( lastTime, myEndTime ); if( myStartTime < waitEnd ) { commonAnalysis->getStatistics().addStatWithCount( MPI_STAT_SENDRECV, waitEnd - myStartTime ); sendRecvLeave->incCounter( WAITING_TIME, waitEnd - myStartTime ); } else { UTILS_WARNING( "[%" PRIu64 "] SendrecvRule: Error in determining " "waiting time." ); } // point to potential continuation (node ID, stream ID) commonAnalysis->getMPIAnalysis().addRemoteMPIEdge( sendRecvLeave, lastNodeId, lastStreamId ); } else // this operation was last (all other enter times are smaller) { // distribute blame from both uint64_t blame = 0; if ( myStartTime != recvRankStartTime && myStartTime < recvRankEndTime ) { blame = myStartTime - recvRankStartTime; } // late sender if( myStartTime > sendRankStartTime ) { blame += myStartTime - sendRankStartTime; } if( blame > 0 ) { distributeBlame( commonAnalysis, sendRecvEnter, blame, mpiStreamWalkCallback, REASON_MPI_LATE_SENDRECV ); } } return true; } }; } }
35.476868
87
0.556726
rdietric
9e48476d47d9c1b22447aa0818b1fb40b07603ad
1,749
cpp
C++
plugin_vc/game_vc/CCopPed.cpp
gta-chaos-mod/plugin-sdk
e3bf176337774a2afc797a47825f81adde78e899
[ "Zlib" ]
368
2015-01-01T21:42:00.000Z
2022-03-29T06:22:22.000Z
plugin_vc/game_vc/CCopPed.cpp
SteepCheat/plugin-sdk
a17c5d933cb8b06e4959b370092828a6a7aa00ef
[ "Zlib" ]
89
2016-05-08T06:42:36.000Z
2022-03-29T06:49:09.000Z
plugin_vc/game_vc/CCopPed.cpp
SteepCheat/plugin-sdk
a17c5d933cb8b06e4959b370092828a6a7aa00ef
[ "Zlib" ]
179
2015-02-03T23:41:17.000Z
2022-03-26T08:27:16.000Z
/* Plugin-SDK (Grand Theft Auto Vice City) header file Authors: GTA Community. See more here https://github.com/DK22Pac/plugin-sdk Do not delete this comment block. Respect others' work! */ #include "CCopPed.h" // Converted from thiscall void CCopPed::ArrestPlayer(void) 0x4EB470 void CCopPed::ArrestPlayer() { plugin::CallMethod<0x4EB470, CCopPed *>(this); } // Converted from thiscall void CCopPed::CCopPed(eCopType copType, int) 0x4ED720 CCopPed::CCopPed(eCopType copType, int arg1) : CPed(plugin::dummy) { plugin::CallMethod<0x4ED720, CCopPed *, eCopType, int>(this, copType, arg1); } // Converted from thiscall void CCopPed::ClearPursuit(void) 0x4EB770 void CCopPed::ClearPursuit() { plugin::CallMethod<0x4EB770, CCopPed *>(this); } // Converted from thiscall void CCopPed::CopAI(void) 0x4EBC10 void CCopPed::CopAI() { plugin::CallMethod<0x4EBC10, CCopPed *>(this); } // Converted from thiscall void CCopPed::ProcessHeliSwat(void) 0x4EB280 void CCopPed::ProcessHeliSwat() { plugin::CallMethod<0x4EB280, CCopPed *>(this); } // Converted from thiscall void CCopPed::ProcessStingerCop(void) 0x4EB010 void CCopPed::ProcessStingerCop() { plugin::CallMethod<0x4EB010, CCopPed *>(this); } // Converted from thiscall int CCopPed::ScanForCrimes(void) 0x4EBAD0 int CCopPed::ScanForCrimes() { return plugin::CallMethodAndReturn<int, 0x4EBAD0, CCopPed *>(this); } // Converted from thiscall void CCopPed::SetArrestPlayer(CPed * ped) 0x4EB5F0 void CCopPed::SetArrestPlayer(CPed* ped) { plugin::CallMethod<0x4EB5F0, CCopPed *, CPed*>(this, ped); } // Converted from thiscall void CCopPed::SetPursuit(bool) 0x4EB9C0 void CCopPed::SetPursuit(bool arg0) { plugin::CallMethod<0x4EB9C0, CCopPed *, bool>(this, arg0); }
33.634615
80
0.743282
gta-chaos-mod
eaff88e76a76a81e34f6ad6e09b35eead91d7d23
5,814
cpp
C++
src/obj_loader.cpp
hadalhw17/meshloader
411babf21a6bddf61c6ea8fc8b8ffce325ae5e52
[ "MIT" ]
null
null
null
src/obj_loader.cpp
hadalhw17/meshloader
411babf21a6bddf61c6ea8fc8b8ffce325ae5e52
[ "MIT" ]
null
null
null
src/obj_loader.cpp
hadalhw17/meshloader
411babf21a6bddf61c6ea8fc8b8ffce325ae5e52
[ "MIT" ]
null
null
null
#include "obj_loader.hpp" #include <algorithm> #include <array> #include <fmt/format.h> #include <functional> #include <string> #include <cassert> #include <thread> namespace loader { template <class ArgumentType, class ResultType> struct unary_function { using argument_type = ArgumentType; using result_type = ResultType; }; /// Tokenize a InString into a list by splitting at 'InDelim' std::vector<std::string> tokenize(const std::string &InString, const std::string &InDelim, bool InIncludeEmpty) { std::string::size_type lastPos = 0; std::string::size_type pos = InString.find_first_of(InDelim, lastPos); std::vector<std::string> tokens; while (lastPos != std::string::npos) { if (pos != lastPos || InIncludeEmpty) { auto str = InString.substr(lastPos, pos - lastPos); tokens.push_back(str); } lastPos = pos; if (lastPos != std::string::npos) { lastPos += 1; pos = InString.find_first_of(InDelim, lastPos); } } return tokens; } /// Convert a string into an unsigned integer value auto toInt(const std::string &InStr) { size_t end_ptr{ }; const auto result = std::stoi(InStr, &end_ptr); if (end_ptr == 0) { std::puts( fmt::format("Could not parse integer value: {} \n", InStr).c_str( )); assert(end_ptr == 0); } return result; } CObjModel::SObjVertex::SObjVertex(const std::string &InString) { std::vector<std::string> tokens = tokenize(InString, "/", true); if (tokens.empty( ) || tokens.size( ) > 3) { std::puts(fmt::format("Invalid vertex data: {} \n", InString).c_str( )); } p = toInt(tokens[0]); if (tokens.size( ) >= 2 && !tokens[1].empty( )) { uv = toInt(tokens[1]); } if (tokens.size( ) >= 3 && !tokens[2].empty( )) { n = toInt(tokens[2]); } } std::optional<Model> CObjModel::LoadObjFromFile(const char *InFileName) { auto model = Model( ); model.meshes.resize(1, { }); Mesh &mesh = model.meshes[0]; using VertexMap = std::unordered_map<SObjVertex, uint32_t, SObjVertexHash>; std::ifstream is(InFileName); if (!is) { return std::nullopt; } std::cout << "Loading \"" << InFileName << "\" .. " << std::endl; std::vector<float3> positions; std::vector<float2> texcoords; std::vector<float3> normals; std::vector<SObjVertex> vertices; VertexMap vertexMap; AABB &meshBox = mesh.boundingBox; std::string lineStr; while (std::getline(is, lineStr)) { std::istringstream line(lineStr); std::string prefix; line >> prefix; if (prefix == "v") { float3 p{ }; line >> p.x >> p.y >> p.z; meshBox.extend(p); positions.push_back(p); } else if (prefix == "vt") { float2 tc{ }; line >> tc.x >> tc.y; texcoords.push_back(tc); } else if (prefix == "vn") { float3 n{ }; line >> n.x >> n.y >> n.z; normals.push_back((n)); } else if (prefix == "f") { std::array<std::string, 4> v; line >> v[0] >> v[1] >> v[2] >> v[3]; std::array<SObjVertex, 6> verts; std::size_t nVertices = 3; verts[0] = SObjVertex(v[0]); verts[1] = SObjVertex(v[1]); verts[2] = SObjVertex(v[2]); if (!v[3].empty( )) { /* This is a quad, split into two triangles */ verts[3] = SObjVertex(v[3]); verts[4] = verts[0]; verts[5] = verts[2]; nVertices = verts.size( ); } /* Convert to an indexed vertex list */ for (size_t i = 0; i < nVertices; ++i) { const SObjVertex &vertex = verts.at(i); const auto it = vertexMap.find(vertex); if (it == vertexMap.end( )) { vertexMap[vertex] = static_cast<std::uint32_t>(vertices.size( )); mesh.indices.push_back(static_cast<std::uint32_t>(vertices.size( ))); vertices.push_back(vertex); } else { mesh.indices.push_back(it->second); } } } } mesh.positions.resize(vertices.size( )); if (!texcoords.empty( )) { mesh.texCords.resize(vertices.size( )); } if (!normals.empty( )) { mesh.normals.resize(vertices.size( )); } auto copyPositions = [&positions, &vertices](std::vector<float3> &InDist) { for (size_t i = 0; i < InDist.size( ); ++i) { const auto p = vertices[i].p > 0 ? vertices[i].p - 1 : positions.size( ) + vertices[i].p; InDist[i] = positions[p]; } }; auto copyNorms = [&normals, &vertices](std::vector<float3> &InDist) { for (size_t i = 0; i < InDist.size( ); ++i) { const auto p = vertices[i].n > 0 ? vertices[i].n - 1 : normals.size( ) + vertices[i].n; InDist[i] = normals[p]; } }; auto copyTexCords = [&texcoords, &vertices](std::vector<float2> &InDist) { for (size_t i = 0; i < InDist.size( ); ++i) { const auto p = vertices[i].uv > 0 ? vertices[i].uv - 1 : texcoords.size( ) + vertices[i].uv; InDist[i] = texcoords[p]; } }; #ifdef NO_MT copyPositions(std::ref(mesh.positions)); copyNorms(std::ref(mesh.normals)); copyTexCords(std::ref(mesh.texCords)); #else std::thread posLoader(copyPositions, std::ref(mesh.positions)); std::thread normLoader(copyNorms, std::ref(mesh.normals)); std::thread uvLoader(copyTexCords, std::ref(mesh.texCords)); posLoader.join( ); normLoader.join( ); uvLoader.join( ); #endif // Since I am currently loading everything as a single mesh, then I need this // default primitive for all indices. Primitive prim{ 0, mesh.indices.size( ), -1 }; mesh.primitives.push_back(prim); return model; } }// namespace loader
25.5
79
0.573443
hadalhw17
eaff8d6675c4e7af73288e00a06a6523cb9d2418
12,260
hpp
C++
include/fluidity/container/array_view.hpp
robclu/fluidity
22069dc3b0280f843494913a2371f940531d1744
[ "MIT" ]
1
2018-04-21T09:24:36.000Z
2018-04-21T09:24:36.000Z
include/fluidity/container/array_view.hpp
robclu/fluidity
22069dc3b0280f843494913a2371f940531d1744
[ "MIT" ]
4
2018-08-05T12:14:41.000Z
2021-09-20T14:38:50.000Z
include/fluidity/container/array_view.hpp
robclu/fluidity
22069dc3b0280f843494913a2371f940531d1744
[ "MIT" ]
null
null
null
//==--- fluidity/container/array_view.hpp ------------------ -*- C++ -*- ---==// // // Fluidity // // Copyright (c) 2018 Rob Clucas. // // This file is distributed under the MIT License. See LICENSE for details. // //==------------------------------------------------------------------------==// // /// \file array_view.hpp /// \brief This file defines the implementation of an array class which does not /// own the underlying data, but rather just views it. // //==------------------------------------------------------------------------==// #ifndef FLUIDITY_CONTAINER_ARRAY_VIEW_HPP #define FLUIDITY_CONTAINER_ARRAY_VIEW_HPP #include <fluidity/algorithm/unrolled_for.hpp> #include <fluidity/iterator/range.hpp> namespace fluid { /// The ArrayView class allows portions of data to be viewed as an array. This /// can view portions of the data in row major or column major (in >= 2 dims) /// by modifying the stride of the view to match the number of elements in a /// given direction of the container which is being viewed. /// \tparam T The type of the data to store in the tensor. /// \tparam Elements The number of elements in the array. template <typename T, std::size_t Elements> class ArrayView; namespace detail { /// Struct which can be used to check if the type T is an ArrayView type. /// \tparam T The type to check. template <typename T> struct IsArrayView { /// Defines that this type is not an array view. static constexpr auto value = false; }; /// Specialization for types which are ArrayView types. /// \tparam T The type held by the ArrayView. /// \tparam S The size of the ArrayView. template <typename T, std::size_t S> struct IsArrayView<ArrayView<T, S>> { /// Defines that this type is an array view. static constexpr auto value = true; }; } // namespace detail /// Returns true if the type T is an ArrayView. /// \tparam T The type to check if is an ArrayView. template <typename T> static constexpr auto is_array_view_v = detail::IsArrayView<T>::value; /// Implementation of the ArrayView class. /// \tparam T The type of the data to store in the tensor. /// \tparam Elements The number of elements in the array. template <typename T, std::size_t Elements> class ArrayView { /// Defines the type of the tensor. using self_t = ArrayView; /// Defines the type of the elements in the tensor. using value_t = std::decay_t<T>; /// Defines the type of the pointer to the data type. using pointer_t = value_t*; /// Defines the type of a reference to the data type. using reference_t = value_t&; /// Defines the type of a const reference to the data type. using const_reference_t = const value_t&; /// Defines the type of a non const iterator. using iterator_t = StridedIterator<value_t, false>; /// Defines the type of a const iterator. using const_iterator_t = StridedIterator<value_t, true>; /// Defines a tag class which can be used to define unrolled and non-unrolled /// implementations of the array functionality. template <bool> struct UnrollTag {}; /// Defines the type of tag for unrolled implementations. using unroll_true_tag_t = UnrollTag<true>; /// Defines the type of a tage for non-unrolled implementations. using unroll_false_tag_t = UnrollTag<false>; /// Defines an instance of the unroll tag for this class based on the number /// of elements in the array. static constexpr auto unroll_tag = UnrollTag<(Elements < max_unroll_depth)>{}; public: /// Initializes pointer to the first element and the step size. /// \param[in] ptr The pointer to the first element. /// \param[in] step The step size between elements that are being referenced. fluidity_host_device ArrayView(pointer_t ptr, std::size_t step) : _ptr(ptr), _step(step) {} /// Creates a new array view by setting the pointer and the step size to that /// of the other array view. /// \param[in] other The other ArrayRef to copy. fluidity_host_device ArrayView(const self_t& other) : _ptr(other._ptr), _step(other._step) {} /// Creates a new array view by setting the pointer and the step size to that /// of the other array view. This moves the pointer from \p other to this /// array view, invalidating \p other. /// \param[in] other The other ArrayView to copy. fluidity_host_device ArrayView(self_t&& other) : _ptr(std::move(other._ptr)), _step(other._step) { other._ptr = nullptr; other._step = 0; } /// Overload of access operator to return a reference to the \p ith element /// in the array. /// \param[in] i The index of the element to get a referemce to. fluidity_host_device reference_t operator[](std::size_t i) { return _ptr[i * _step]; } /// Overload of access operator to return a constant reference to the /// \p ith element in the array. /// \param[in] i The index of the element to get a referemce to. /// \return A constant reference to the element at position \p i. fluidity_host_device const_reference_t operator[](std::size_t i) const { return _ptr[i * _step]; } /// Overload of operator- to subtract each element of a container from each /// element in the array view, returning a new array. /// \param[in] container The container to elementwise subtract from the array. /// \tparam Container The type of the container. template <typename Container> fluidity_host_device constexpr auto operator-(Container&& container) const { auto result = Array<value_t, Elements>(); unrolled_for_bounded<Elements>([&] (auto i) { result[i] = this->operator[](i) - container[i]; }); return result; } /// Overload of operator+ to add each element of a container to each element /// in the array. /// \param[in] container The container to elementwise add with the array. /// \tparam Container The type of the container. template <typename Container> fluidity_host_device constexpr auto operator+(Container&& container) const { auto result = Array<value_t, Elements>(); unrolled_for_bounded<Elements>([&] (auto i) { result[i] = this->operator[](i) + container[i]; }); return result; } /// Overload of operator-= to subtract each element of a container from each /// element in the array view, returning the modified array view. /// \param[in] container The container to elementwise subtract from the array. /// \tparam Container The type of the container. template <typename Container> fluidity_host_device constexpr self_t& operator-=(Container&& container) { unrolled_for_bounded<Elements>([&] (auto i) { this->operator[](i) -= container[i]; }); return *this; } /// Overload of operator+= to add each element of a container to each element /// in the array view, returning the modified array view. /// \param[in] container The container to elementwise add with the array. /// \tparam Container The type of the container. template <typename Container> fluidity_host_device constexpr self_t& operator+=(Container&& container) { unrolled_for_bounded<Elements>([&] (auto i) { this->operator[](i) += container[i]; }); return *this; } /// Returns an iterator to the first element in the array. fluidity_host_device constexpr iterator_t begin() { return iterator_t{_ptr, _step}; } /// Returns an iterator to the last element in the array. fluidity_host_device constexpr iterator_t end() { return iterator_t{_ptr + _step * Elements, _step}; } /// Returns a constant iterator to the first element in the array. fluidity_host_device constexpr const_iterator_t begin() const { return const_iterator_t{_ptr, _step}; } /// Returns a constant iterator to the last element in the array. fluidity_host_device constexpr const_iterator_t end() const { return const_iterator_t{_ptr + _step * Elements, _step}; } /// Returns the number of elements in the array. fluidity_host_device constexpr std::size_t size() const { return Elements; } /// Returns the number of elements in the array. fluidity_host_device std::size_t step() const { return _step; } private: pointer_t _ptr; //!< Pointer to the data to view. std::size_t _step; //!< Step size when moving between elements. /// Copies the contents of a container into the contents which are viewed by /// this class. /// \param[in] container The container to copy the data from. /// \tparam Container The type of the container. template <typename Container> void copy_from_container(Container&& container); }; //==--- Implementation -----------------------------------------------------==// //===== Operator --------------------------------------------------------=====// /// Overload of multiplication operator to perform elementwise multiplication of /// a scalar constant to an array view. This returns am array, to modify the /// contents of the array view, use *=. /// \param[in] s The scalar to multiply to each element of the array view. /// \param[in] a The array view to multiply with the scalar. /// \tparam T The type of the scalar data. /// \tparam U The type of the data in the array view. /// \tparam S The size of the array view. template <typename T, typename U, std::size_t S, conv_enable_t<T, U> = 0> fluidity_host_device constexpr auto operator*(T s, const ArrayView<U, S>& a) { auto result = Array<U, S>(); unrolled_for_bounded<S>([&] (auto i) { result[i] = s * a[i]; }); return result; } /// Overload of division operator to perform elementwise division of /// a scalar constant to an array view. This returns an array, to modify the /// contents of the array view, use /=. /// \param[in] s The scalar to devide by each element. /// \param[in] a The array view divide with the scalar. /// \tparam T The type of the scalar data. /// \tparam U The type of the data in the array view. /// \tparam S The size of the array view. template <typename T, typename U, std::size_t S, conv_enable_t<T, U> = 0> fluidity_host_device constexpr auto operator/(T s, const ArrayView<U, S>& a) { auto result = Array<U, S>(); unrolled_for_bounded<S>([&] (auto i) { result[i] = s / a[i]; }); return result; } /// Overload of addition operator to perform elementwise addition of /// a scalar constant to an array view. This returns an array, to modify the /// contents of the array view, use +=. /// \param[in] s The scalar to add to each element of the array view. /// \param[in] a The array view to add with the scalar. /// \tparam T The type of the scalar data. /// \tparam U The type of the data in the array view. /// \tparam S The size of the array view. template <typename T, typename U, std::size_t S, conv_enable_t<T, U> = 0> fluidity_host_device constexpr auto operator+(T s, const ArrayView<U, S>& a) { auto result = Array<U, S>(); unrolled_for_bounded<S>([&] (auto i) { result[i] = s + a[i]; }); return result; } /// Overload of subtraction operator to perform elementwise subtraction of /// a scalar constant to an array view. This returns an array, to modify the /// contents of the array view, use -=. /// \param[in] s The scalar to add to each element of the array view. /// \param[in] a The array view to add with the scalar. /// \tparam T The type of the scalar data. /// \tparam U The type of the data in the array view. /// \tparam S The size of the array view. template <typename T, typename U, std::size_t S, conv_enable_t<T, U> = 0> fluidity_host_device constexpr auto operator-(T s, const ArrayView<U, S>& a) { auto result = Array<U, S>(s); unrolled_for_bounded<S>([&] (auto i) { result[i] = s - a[i]; }); return result; } //===== Private ---------------------------------------------------------=====// template <typename T, std::size_t Elements> template <typename Container> void ArrayView<T, Elements>::copy_from_container(Container&& container) { unrolled_for_bounded<Elements>([&] (auto i) { _ptr[i * _step] = container[i]; }); } } // namespace fluid #endif // FLUIDITY_CONTAINER_ARRAY_VIEW_HPP
36.816817
80
0.668108
robclu
d80788d45ddaabb723daa5df302b1f59f7bf3172
1,355
hpp
C++
src/morda/widgets/base/fraction_band_widget.hpp
igagis/morda
dd7b58f7cb2689d56b7796cc9b6b9302aad1a529
[ "MIT" ]
69
2016-12-07T05:56:53.000Z
2020-11-27T20:59:05.000Z
src/morda/widgets/base/fraction_band_widget.hpp
igagis/morda
dd7b58f7cb2689d56b7796cc9b6b9302aad1a529
[ "MIT" ]
103
2015-07-10T14:42:21.000Z
2020-09-09T16:16:21.000Z
src/morda/widgets/base/fraction_band_widget.hpp
igagis/morda
dd7b58f7cb2689d56b7796cc9b6b9302aad1a529
[ "MIT" ]
18
2016-11-22T14:41:37.000Z
2020-04-22T18:16:10.000Z
/* morda - GUI framework Copyright (C) 2012-2021 Ivan Gagis <igagis@gmail.com> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* ================ LICENSE END ================ */ #pragma once #include "../base/fraction_widget.hpp" namespace morda{ class fraction_band_widget : public fraction_widget{ float curBandSizeFraction = 0; // Current bar size factor from 0 to 1 protected: fraction_band_widget(std::shared_ptr<morda::context> c, const treeml::forest& desc) : widget(std::move(c), desc), fraction_widget(this->context, desc) {} virtual void on_band_change(); public: std::function<void(fraction_band_widget& s)> band_change_handler; void set_band_fraction(real fraction); real get_band_fraction()const noexcept{ return this->curBandSizeFraction; } }; }
27.653061
86
0.746863
igagis
d81d303a6c4bc521cdf5cb60c0d76c699efe3470
976
cpp
C++
74.cpp
adelacvg/PE
0345335a3f959342625be03ae36a21bbad45f273
[ "MIT" ]
3
2018-11-12T07:32:42.000Z
2021-07-27T04:40:41.000Z
74.cpp
adelacvg/PE
0345335a3f959342625be03ae36a21bbad45f273
[ "MIT" ]
null
null
null
74.cpp
adelacvg/PE
0345335a3f959342625be03ae36a21bbad45f273
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> using namespace std; int M = 1000000; int fac[20]={1,1,2,6,24,120,720,5040,40320,362880}; int cash[1000001]; int f(int n) { int sum=0; while(n) { sum+=fac[n%10]; n/=10; } return sum; } int main() { cash[169]=3; cash[363601]=3; cash[1454]=3; cash[871]=2; cash[45361]=2; cash[872]=2; cash[45362]=3; int ans = 0; for(int i=69;i<M;i++) { int n=i; int count = 0; vector<int> seq; seq.push_back(0); while(n!=seq[seq.size()-1]) { seq.push_back(n); n = f(n); count++; if(n<M&&cash[n]) { count+=cash[n]; break; } } if(count==60) { ans++; } for(int j=1;j<seq.size();j++) { if(seq[j]<M)cash[seq[j]] = count; count--; } } cout<<ans; }
17.428571
51
0.396516
adelacvg
d825a7564b9ef54397cc86c7336fc7ea33d3555b
1,528
cpp
C++
src/example_ceres_helloworld.cpp
dringakn/ROSExamples
f4f19d21fab3630c112148e198f117f0466032c4
[ "MIT" ]
2
2020-07-14T19:37:43.000Z
2020-07-15T04:38:09.000Z
src/example_ceres_helloworld.cpp
dringakn/ROSExamples
f4f19d21fab3630c112148e198f117f0466032c4
[ "MIT" ]
null
null
null
src/example_ceres_helloworld.cpp
dringakn/ROSExamples
f4f19d21fab3630c112148e198f117f0466032c4
[ "MIT" ]
null
null
null
/* A simple example of using the Ceres minimizer. Minimize 0.5 (10 - x)^2 using jacobian matrix computed using automatic differentiation. */ #include <ceres/ceres.h> #include <glog/log_severity.h> using ceres::AutoDiffCostFunction; using ceres::CostFunction; using ceres::Problem; using ceres::Solve; using ceres::Solver; // A templated cost functor that implements the residual r = 10 - // x. The method operator() is templated so that we can then use an // automatic differentiation wrapper around it to generate its // derivatives. struct CostFunctor { template <typename T> bool operator()(const T* const x, T* residual) const { residual[0] = 10.0 - x[0]; return true; } }; int main(int argc, char** argv) { google::InitGoogleLogging(argv[0]); // The variable to solve for with its initial value. It will be // mutated in place by the solver. double x = 0.5; const double initial_x = x; // Build the problem. Problem problem; // Set up the only cost function (also known as residual). This uses // auto-differentiation to obtain the derivative (jacobian). CostFunction* cost_function = new AutoDiffCostFunction<CostFunctor, 1, 1>(new CostFunctor); problem.AddResidualBlock(cost_function, nullptr, &x); // Run the solver! Solver::Options options; options.minimizer_progress_to_stdout = true; Solver::Summary summary; Solve(options, &problem, &summary); std::cout << summary.BriefReport() << "\n"; std::cout << "x : " << initial_x << " -> " << x << "\n"; return 0; }
31.833333
93
0.704188
dringakn
d82ba3919471c00c10094e9a854645d6f1c568aa
461
cpp
C++
Tests/bug18.cpp
klassen-software-solutions/ksstest
c90efdbc40613230f42a84d31e9b8172bde57453
[ "MIT" ]
2
2018-10-14T03:12:45.000Z
2018-10-14T03:12:54.000Z
Tests/bug18.cpp
klassen-software-solutions/ksstest
c90efdbc40613230f42a84d31e9b8172bde57453
[ "MIT" ]
29
2018-04-03T01:02:56.000Z
2020-01-10T21:42:42.000Z
Tests/bug18.cpp
klassen-software-solutions/ksstest
c90efdbc40613230f42a84d31e9b8172bde57453
[ "MIT" ]
null
null
null
// // bug18.cpp // unittest // // Created by Steven W. Klassen on 2019-01-17. // Copyright © 2019 Klassen Software Solutions. All rights reserved. // #include <kss/test/all.h> using namespace std; using namespace kss::test; static TestSuite ts("bug18", { // The bug is that this will not compile. make_pair("string", [] { KSS_ASSERT(isEqualTo<string>("hello world", [] { return string("hello world"); })); }) });
20.043478
69
0.613883
klassen-software-solutions
d83fafa0bfa6493f1b49c2bb74d1ab57adad6261
3,290
cpp
C++
src/core/p_render/scene/mesh/Mesh.cpp
jabronicus/P-Engine
7786c2f97d19bd2913b706f6afe5087a392b1a3c
[ "MIT" ]
null
null
null
src/core/p_render/scene/mesh/Mesh.cpp
jabronicus/P-Engine
7786c2f97d19bd2913b706f6afe5087a392b1a3c
[ "MIT" ]
null
null
null
src/core/p_render/scene/mesh/Mesh.cpp
jabronicus/P-Engine
7786c2f97d19bd2913b706f6afe5087a392b1a3c
[ "MIT" ]
1
2021-08-24T05:43:01.000Z
2021-08-24T05:43:01.000Z
#include "../../../../../include/core/p_render/scene/mesh/Mesh.hpp" using namespace scene; /* SUBMESH */ SubMesh::SubMesh(const SubMeshCreateInfo &info) : Renderable() { name_ = info.name; // set up submesh data (these submesh objects should contain the actual geometry data) numVertices_ = info.vertexCount; vertexData_ = info.vertexData; // we just copy the pointer; data won't be copied til bake() // compute vertex size based on enabled attributes const auto &computeVertexSize = [&](const VertexAttributeFlags &enabledVertexAttributes) { unsigned int vertexSize = 0; if (info.enabledVertexAttributes & VertexAttributeFlagBits::PositionBit) { vertexSize += sizeof(VertexAttributeTypes::PositionType); } if (info.enabledVertexAttributes & VertexAttributeFlagBits::NormalBit) { vertexSize += sizeof(VertexAttributeTypes::NormalType); } if (info.enabledVertexAttributes & VertexAttributeFlagBits::ColorBit) { vertexSize += sizeof(VertexAttributeTypes::ColorType); } if (info.enabledVertexAttributes & VertexAttributeFlagBits::UVBit) { vertexSize += sizeof(VertexAttributeTypes::UVType); } if (info.enabledVertexAttributes & VertexAttributeFlagBits::TangentBit) { vertexSize += sizeof(VertexAttributeTypes::TangentType); } if (info.enabledVertexAttributes & VertexAttributeFlagBits::BitangentBit) { vertexSize += sizeof(VertexAttributeTypes::BitangentType); } if (info.enabledVertexAttributes & VertexAttributeFlagBits::BoneIndexBit) { //todo } if (info.enabledVertexAttributes & VertexAttributeFlagBits::BoneWeightsBit) { //todo } return vertexSize; }; vertexSize_ = computeVertexSize(info.enabledVertexAttributes); indices_ = info.indices; } SubMesh::~SubMesh() { } bool SubMesh::update() { if (update_) return update_(*this); return false; // otherwise return false; no update function registered -> no change automatically } /* MESH */ Mesh::Mesh(const MeshCreateInfo &info) : Renderable() { // here we prepare the vertex data + index data initially, so that it can be // copied into the scene buffer for rendering unsigned long long meshSizeInBytes = 0; for (int i = 0; i < info.submeshCreateInfos.size(); i++) { const auto &submeshCreateInfo = info.submeshCreateInfos[i]; submeshes_.push_back(std::make_shared<SubMesh>(submeshCreateInfo)); const auto &submesh = submeshes_.back(); meshSizeInBytes += submesh->getIndexDataSizeInBytes() + submesh->getVertexDataSizeInBytes(); } meshSizeInBytes_ = meshSizeInBytes; // any other mesh preperation! enableSubMeshUpdateCallbacksOnly_ = info.enableSubMeshUpdateCallbacks; } Mesh::~Mesh() { // not sure i need an explicit dtor but w/e } bool Mesh::isMesh() { // obviously meshes should return true here return true; } bool Mesh::update() { // idea here i think: activate update callback // not sure what to do here if (!enableSubMeshUpdateCallbacksOnly_) { return updateCallback_(*this); } return false; }
33.917526
101
0.672948
jabronicus
d8470c10963e74c4c0e7f281ca1bfd5c914038a8
1,496
cpp
C++
ural/1085.cpp
jffifa/algo-solution
af2400d6071ee8f777f9473d6a34698ceef08355
[ "MIT" ]
5
2015-07-14T10:29:25.000Z
2016-10-11T12:45:18.000Z
ural/1085.cpp
jffifa/algo-solution
af2400d6071ee8f777f9473d6a34698ceef08355
[ "MIT" ]
null
null
null
ural/1085.cpp
jffifa/algo-solution
af2400d6071ee8f777f9473d6a34698ceef08355
[ "MIT" ]
3
2016-08-23T01:05:26.000Z
2017-05-28T02:04:20.000Z
/* Problem: Ural1085 Algorithm: Floyd-Warshall Time: O() Memory: O() Detail: Simple Coded by [BUPT]AkemiHomura */ #include <cstdio> #include <cstring> #include <algorithm> using namespace std; const int MaxN = 105; const int INF = 0x1fffffff; int N, M, K, L; int Stop[MaxN], Money[MaxN], S[MaxN], Ans, AnsV, Cnt; int G[MaxN][MaxN], MonTic[MaxN]; void CheckMin(int v) { int Cnt = 0; for (int i = 0; i < K; ++i) { if (G[S[i]][v] >= INF) return; if (!MonTic[i]) if (G[S[i]][v]*4 > Money[i]) return; else Cnt += G[S[i]][v]*4; } if (Cnt < Ans) { Ans = Cnt; AnsV = v; } } int main() { scanf("%d%d", &N, &M); for (int i = 1; i <= N; ++i) for (int j = 1; j <= N; ++j) if (i == j) G[i][j] = 0; else G[i][j] = INF; for (int i = 0; i < M; ++i) { scanf("%d", &L); for (int j = 0; j < L; ++j) scanf("%d", &Stop[j]); for (int j = 0; j < L; ++j) for (int k = j+1; k < L; ++k) { G[Stop[j]][Stop[k]] = min(G[Stop[j]][Stop[k]], 1); G[Stop[k]][Stop[j]] = min(G[Stop[k]][Stop[j]], 1); } } scanf("%d", &K); for (int i = 0; i < K; ++i) scanf("%d%d%d", &Money[i], &S[i], &MonTic[i]); for (int k = 1; k <= N; ++k) for (int i = 1; i <= N; ++i) for (int j = 1; j <= N; ++j) G[i][j] = min(G[i][j], G[i][k]+G[k][j]); Ans = INF; AnsV = 0; for (int i = 1; i <= N; ++i) CheckMin(i); if (AnsV) printf("%d %d\n", AnsV, Ans); else printf("0\n"); return 0; }
19.946667
55
0.456551
jffifa
d8474c18e8a284c93eadb433d8226d080be9b940
1,363
hxx
C++
c++/src/laolx/parser/Words.hxx
kpfalzer/laolx
66e5571a63c289294af69949b9ec56f752efc51b
[ "MIT" ]
null
null
null
c++/src/laolx/parser/Words.hxx
kpfalzer/laolx
66e5571a63c289294af69949b9ec56f752efc51b
[ "MIT" ]
null
null
null
c++/src/laolx/parser/Words.hxx
kpfalzer/laolx
66e5571a63c289294af69949b9ec56f752efc51b
[ "MIT" ]
null
null
null
// // Words.hxx // // // Created by Karl W Pfalzer. // #ifndef laolx_parser_Words_hxx #define laolx_parser_Words_hxx #include "laolx/parser/laolx.hxx" namespace laolx { namespace parser { class Words : public _Acceptor { public: explicit Words() {} virtual ~Words() {} class Node : public NodeVector { public: virtual ~Node() {} virtual ostream& operator<<(ostream& os) const; NODE_TYPE_DECLARE; private: friend class Words; explicit Node(const TPNode& node); }; static const Words& THE_ONE; protected: TPNode _accept(Consumer& consumer) const; }; typedef PTRcObjPtr<Words::Node> TPWordsNode; DEF_TO_XXXNODE(Words) class Symbols : public _Acceptor { public: explicit Symbols() {} virtual ~Symbols() {} class Node : public NodeVector { public: virtual ~Node() {} virtual ostream& operator<<(ostream& os) const; NODE_TYPE_DECLARE; private: friend class Symbols; explicit Node(const TPNode& node); }; static const Symbols& THE_ONE; protected: TPNode _accept(Consumer& consumer) const; }; typedef PTRcObjPtr<Symbols::Node> TPSymbolsNode; DEF_TO_XXXNODE(Symbols) } } #endif /* laolx_parser_Words_hxx */
16.22619
55
0.608217
kpfalzer
d8491f1f1fd13e489d8a2f4083ce992df573b6c9
5,811
cpp
C++
src/partition/Partitioning.cpp
dlasalle/poros
a87e2dc1b64c47f94e0ce05adadbd7e35a63d166
[ "MIT" ]
1
2022-01-15T21:58:08.000Z
2022-01-15T21:58:08.000Z
src/partition/Partitioning.cpp
dlasalle/poros
a87e2dc1b64c47f94e0ce05adadbd7e35a63d166
[ "MIT" ]
15
2018-12-15T04:09:58.000Z
2019-09-29T18:51:06.000Z
src/partition/Partitioning.cpp
dlasalle/poros
a87e2dc1b64c47f94e0ce05adadbd7e35a63d166
[ "MIT" ]
null
null
null
/** * @file Partitioning.cpp * @brief Implementation of the partitioning class. * @author Dominique LaSalle <dominique@solidlake.com> * Copyright 2017-2018 * @version 1 * @date 2017-10-04 * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ #include "Partitioning.hpp" namespace poros { /****************************************************************************** * HELPER FUNCTIONS ************************************************************ ******************************************************************************/ namespace { template<bool HAS_VERTEX_WEIGHT> void sumPartitionWeight( Graph const * const graph, pid_type const * const assignment, wgt_type * const partWeight) { for (Vertex const & vertex : graph->vertices()) { vtx_type const v = vertex.index; pid_type const part = assignment[v]; wgt_type const wgt = graph->weightOf<HAS_VERTEX_WEIGHT>(vertex); partWeight[part] += wgt; } } template<bool HAS_EDGE_WEIGHT> wgt_type sumCutEdgeWeight( Graph const * const graph, pid_type const * const assignment) { wgt_type twoWayCutEdgeWeight = 0; for (Vertex const vertex : graph->vertices()) { vtx_type const v = vertex.index; pid_type const home = assignment[v]; for (Edge const edge : graph->edgesOf(vertex)) { Vertex const u = graph->destinationOf(edge); pid_type const other = assignment[u.index]; if (other != home) { twoWayCutEdgeWeight += graph->weightOf<HAS_EDGE_WEIGHT>(edge); } } } return twoWayCutEdgeWeight / 2; } } /****************************************************************************** * CONSTRUCTORS / DESTRUCTOR *************************************************** ******************************************************************************/ Partitioning::Partitioning( pid_type const numParts, Graph const * const graph) : m_cutEdgeWeight(0), m_partitionWeight(numParts, 0), m_assignment(graph->numVertices(), NULL_PID), m_graph(graph) { ASSERT_GREATER(numParts, 0); } Partitioning::Partitioning( pid_type const numParts, Graph const * const graph, sl::Array<pid_type> partitionLabels) : m_cutEdgeWeight(0), m_partitionWeight(numParts, 0), m_assignment(std::move(partitionLabels)), m_graph(graph) { ASSERT_GREATER(numParts, 0); // calculate partition weights if (graph->hasUnitVertexWeight()) { sumPartitionWeight<false>(m_graph, m_assignment.data(), m_partitionWeight.data()); } else { sumPartitionWeight<true>(m_graph, m_assignment.data(), m_partitionWeight.data()); } if (m_graph->hasUnitEdgeWeight()) { m_cutEdgeWeight = sumCutEdgeWeight<false>(m_graph, m_assignment.data()); } else { m_cutEdgeWeight = sumCutEdgeWeight<true>(m_graph, m_assignment.data()); } } // use default generated -- must be done explicitly since we disabled copying Partitioning::Partitioning( Partitioning && lhs) noexcept = default; // use default generated -- must be done explicitly since we disabled copying Partitioning& Partitioning::operator=( Partitioning && lhs) = default; /****************************************************************************** * PUBLIC FUNCTIONS ************************************************************ ******************************************************************************/ std::vector<vtx_type> Partitioning::calcVertexCounts() const { std::vector<vtx_type> vertexCounts(numPartitions(), 0); for (pid_type const & part : m_assignment) { ++vertexCounts[part]; } return vertexCounts; } void Partitioning::recalcCutEdgeWeight() { if (m_graph->hasUnitEdgeWeight()) { m_cutEdgeWeight = sumCutEdgeWeight<false>(m_graph, m_assignment.data()); } else { m_cutEdgeWeight = sumCutEdgeWeight<true>(m_graph, m_assignment.data()); } } void Partitioning::assignAll( pid_type const partition) { ASSERT_LESS(partition, numPartitions()); m_cutEdgeWeight = 0; // move all vertices for (pid_type & where : m_assignment) { where = partition; } // set weights to zero for (wgt_type & partWeight : m_partitionWeight) { partWeight = 0; } // fix the one odd partition m_partitionWeight[partition] = m_graph->getTotalVertexWeight(); } void Partitioning::unassignAll() { for (pid_type & where : m_assignment) { where = NULL_PID; } // set weights to zero for (wgt_type & partWeight : m_partitionWeight) { partWeight = 0; } } void Partitioning::output( wgt_type * const totalCutEdgeWeight, pid_type * const partitionAssignment) const noexcept { *totalCutEdgeWeight = m_cutEdgeWeight; vtx_type const numVertices = static_cast<vtx_type>(m_assignment.size()); for (vtx_type v = 0; v < numVertices; ++v) { partitionAssignment[v] = m_assignment[v]; } } }
27.9375
86
0.637928
dlasalle
d849a646f5c5f17071e8dc8783da51d6c3fb796d
679
inl
C++
ecs/inc/inline/component.inl
RyeToastyO/Ecs
ed748693d28d581abd7912acb992a912768cb62d
[ "MIT" ]
1
2019-10-31T19:18:45.000Z
2019-10-31T19:18:45.000Z
ecs/inc/inline/component.inl
RyeToastyO/Ecs
ed748693d28d581abd7912acb992a912768cb62d
[ "MIT" ]
null
null
null
ecs/inc/inline/component.inl
RyeToastyO/Ecs
ed748693d28d581abd7912acb992a912768cb62d
[ "MIT" ]
null
null
null
// ---------------------------------------------------------------------------- // Copyright (c) 2020 Riley Diederich // License (MIT): https://github.com/RyeToastyO/Ecs/blob/master/LICENSE // ---------------------------------------------------------------------------- namespace ecs { namespace impl { template<typename T> inline ComponentId GetComponentId () { // If you get a compile error on this function, // it means you forgot ECS_COMPONENT(name) macro in your component struct return T::GetEcsComponentId(); } template<typename T> inline size_t GetComponentSize () { return std::is_empty<T>() ? 0 : sizeof(T); } } // namespace impl } // namespace ecs
29.521739
79
0.543446
RyeToastyO
d84a36b1b19978e5fd2c8aa0eb0af247f54c7cd5
148
cpp
C++
src/app/src/main.cpp
Mahmuttalemdar/TicTacToe.AI
ccd7f51c5bdfdd86996790db287d2f3d1628809b
[ "MIT" ]
1
2021-04-19T12:36:02.000Z
2021-04-19T12:36:02.000Z
src/app/src/main.cpp
Mahmuttalemdar/TicTacToe.AI
ccd7f51c5bdfdd86996790db287d2f3d1628809b
[ "MIT" ]
null
null
null
src/app/src/main.cpp
Mahmuttalemdar/TicTacToe.AI
ccd7f51c5bdfdd86996790db287d2f3d1628809b
[ "MIT" ]
null
null
null
#include <glue/src/entrance.h> int main(int argc, char* argv[]) { // Show time for TicTacToeAI Entrance::getInstance()->run(argc, argv); }
18.5
45
0.655405
Mahmuttalemdar
d84fb18dcfcbfb1d61a326e28bfa47bc75096e01
348
hpp
C++
src/manager.hpp
handtruth/mcshub
00f23171a868b80469020b6f1830c290570b0187
[ "MIT" ]
6
2019-08-08T04:28:27.000Z
2022-03-19T14:27:44.000Z
src/manager.hpp
handtruth/mcshub
00f23171a868b80469020b6f1830c290570b0187
[ "MIT" ]
1
2021-07-25T19:58:15.000Z
2021-07-26T19:40:00.000Z
src/manager.hpp
handtruth/mcshub
00f23171a868b80469020b6f1830c290570b0187
[ "MIT" ]
null
null
null
#ifndef _MANAGER_HEAD #define _MANAGER_HEAD #include <ekutils/cli.hpp> #include <ekutils/stdin_d.hpp> #include <ekutils/reader.hpp> namespace mcshub { class manager { ekutils::choice_cli_node root; ekutils::reader input = ekutils::reader(ekutils::input); public: manager(); void on_line(); }; } // namespace mcshub #endif // _MANAGER_HEAD
16.571429
57
0.741379
handtruth
d85a86e411fdee4052b2371049ac362d3ad5d2db
526
cpp
C++
src/AnimationWaitingThread.cpp
mbychawski/traffic-simulator
ef576cb9b2083e9e1cb8671356032d90dcfa42aa
[ "BSD-3-Clause" ]
null
null
null
src/AnimationWaitingThread.cpp
mbychawski/traffic-simulator
ef576cb9b2083e9e1cb8671356032d90dcfa42aa
[ "BSD-3-Clause" ]
null
null
null
src/AnimationWaitingThread.cpp
mbychawski/traffic-simulator
ef576cb9b2083e9e1cb8671356032d90dcfa42aa
[ "BSD-3-Clause" ]
null
null
null
#include "AnimationWaitingThread.h" #include <QWaitCondition> #include <QMutex> #include <QMutexLocker> #include <QTime> AnimationWaitingThread::AnimationWaitingThread(functionPtr f_, QWaitCondition * waitCondition_, QMutex * mutex_) : f(f_), waitCondition(waitCondition_), mutex(mutex_) { go = true; } void AnimationWaitingThread::run() { QMutexLocker locker(mutex); while(go){ f(); waitCondition->wait(mutex); } } void AnimationWaitingThread::stopThread() { go = false; }
21.916667
112
0.692015
mbychawski
d866ae42b1198b97b85397a18ec8209b90893034
3,155
hpp
C++
nheqminer/3rdparty/boost/metaparse/v1/impl/concat.hpp
EuroLine/nheqminer
81c7ef889bb502d16f7d1e7ef020d0592f8af945
[ "MIT" ]
886
2016-10-20T20:59:59.000Z
2022-03-12T07:47:52.000Z
ios/Pods/boost-for-react-native/boost/metaparse/v1/impl/concat.hpp
c7yrus/alyson-v3
5ad95a8f782f5f5d2fd543d44ca6a8b093395965
[ "Apache-2.0" ]
369
2016-10-21T07:42:54.000Z
2020-11-19T10:49:29.000Z
ios/Pods/boost-for-react-native/boost/metaparse/v1/impl/concat.hpp
c7yrus/alyson-v3
5ad95a8f782f5f5d2fd543d44ca6a8b093395965
[ "Apache-2.0" ]
534
2016-10-20T21:00:00.000Z
2022-03-29T10:02:27.000Z
#ifndef BOOST_METAPARSE_V1_IMPL_CONCAT_HPP #define BOOST_METAPARSE_V1_IMPL_CONCAT_HPP // Copyright Abel Sinkovics (abel@sinkovics.hu) 2013. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #include <boost/metaparse/config.hpp> #include <boost/metaparse/v1/fwd/string.hpp> #include <boost/preprocessor/arithmetic/dec.hpp> #include <boost/preprocessor/arithmetic/inc.hpp> #include <boost/preprocessor/arithmetic/mul.hpp> #include <boost/preprocessor/arithmetic/sub.hpp> #include <boost/preprocessor/cat.hpp> #include <boost/preprocessor/punctuation/comma_if.hpp> #include <boost/preprocessor/repetition/enum.hpp> #include <boost/preprocessor/repetition/enum_params.hpp> namespace boost { namespace metaparse { namespace v1 { namespace impl { template <class A, class B> struct concat; #ifdef BOOST_METAPARSE_VARIADIC_STRING template <char... As, char... Bs> struct concat<string<As...>, string<Bs...>> : string<As..., Bs...> {}; #else template <class A, class B> struct concat_impl; #ifdef BOOST_METAPARSE_ARG # error BOOST_METAPARSE_ARG already defined #endif #define BOOST_METAPARSE_ARG(z, n, unused) \ BOOST_PP_CAT(B, BOOST_PP_INC(n)) #ifdef BOOST_METAPARSE_CONCAT # error BOOST_METAPARSE_CONCAT already defined #endif #define BOOST_METAPARSE_CONCAT(z, n, unused) \ template < \ BOOST_PP_ENUM_PARAMS(n, int A) BOOST_PP_COMMA_IF(n) \ BOOST_PP_ENUM_PARAMS(BOOST_METAPARSE_LIMIT_STRING_SIZE, int B) \ > \ struct \ concat_impl< \ string< \ BOOST_PP_ENUM_PARAMS(n, A) \ BOOST_PP_COMMA_IF( \ BOOST_PP_MUL( \ BOOST_PP_SUB(BOOST_METAPARSE_LIMIT_STRING_SIZE, n), \ n \ ) \ ) \ BOOST_PP_ENUM( \ BOOST_PP_SUB(BOOST_METAPARSE_LIMIT_STRING_SIZE, n), \ BOOST_NO_CHAR BOOST_PP_TUPLE_EAT(3), \ ~ \ ) \ >, \ string< \ BOOST_PP_ENUM_PARAMS(BOOST_METAPARSE_LIMIT_STRING_SIZE, B) \ > \ > : \ concat< \ string<BOOST_PP_ENUM_PARAMS(n, A) BOOST_PP_COMMA_IF(n) B0>, \ string< \ BOOST_PP_ENUM( \ BOOST_PP_DEC(BOOST_METAPARSE_LIMIT_STRING_SIZE), \ BOOST_METAPARSE_ARG, \ ~ \ ) \ > \ > \ {}; BOOST_PP_REPEAT( BOOST_METAPARSE_LIMIT_STRING_SIZE, BOOST_METAPARSE_CONCAT, ~ ) #undef BOOST_METAPARSE_ARG #undef BOOST_METAPARSE_CONCAT template <class S> struct concat<S, string<> > : S {}; template <class A, class B> struct concat : concat_impl<A, B> {}; #endif } } } } #endif
29.485981
78
0.57496
EuroLine
d867a852a5188947c4499ac0345549c8b066d628
3,527
cpp
C++
source/frontend/views/debug_window.cpp
GPUOpen-Tools/radeon_memory_visualizer
309ac5b04b870aef408603eaac4bd727d5d3e698
[ "MIT" ]
86
2020-05-14T17:20:22.000Z
2022-01-21T22:53:24.000Z
source/frontend/views/debug_window.cpp
GPUOpen-Tools/radeon_memory_visualizer
309ac5b04b870aef408603eaac4bd727d5d3e698
[ "MIT" ]
6
2020-05-16T18:50:00.000Z
2022-01-21T15:30:16.000Z
source/frontend/views/debug_window.cpp
GPUOpen-Tools/radeon_memory_visualizer
309ac5b04b870aef408603eaac4bd727d5d3e698
[ "MIT" ]
11
2020-10-15T15:55:56.000Z
2022-03-16T20:38:29.000Z
//============================================================================= // Copyright (c) 2018-2021 Advanced Micro Devices, Inc. All rights reserved. /// @author AMD Developer Tools Team /// @file /// @brief Implementation of the debug window. //============================================================================= #include "views/debug_window.h" #include <QApplication> #include <QtDebug> #include <QtGlobal> #include <QScrollBar> #include "rmt_assert.h" #include "util/log_file_writer.h" #include "util/rmv_util.h" #ifndef _WIN32 #include <linux/safe_crt.h> #endif // The one and only instance of the debug window. static DebugWindow* debug_window = nullptr; /// @brief Assert on a Qt message. Add the Qt message as part of the ASSERT warning. /// /// @param [in] type The Qt message type. /// @param [in] text The text string containing the error message from Qt. static void AssertOnQtMessage(const char* type, const QString text) { static char message[2048]; sprintf_s(message, 2048, "Intercepted a %s message from Qt (%s). Please fix it!", type, text.toLatin1().data()); RMT_ASSERT_MESSAGE(false, message); } /// @brief Detect the type of message sent into Qt and return it as a string. /// /// @param [in] type The Qt message type (info/error/warning/etc). /// @param [in] context The message context. /// @param [in] msg The output string. static void MyMessageHandler(QtMsgType type, const QMessageLogContext& context, const QString& msg) { Q_UNUSED(context); QString txt; switch (type) { case QtInfoMsg: txt = QString("qInfo(): %1").arg(msg); break; case QtDebugMsg: txt = QString("qDebug(): %1").arg(msg); break; case QtWarningMsg: txt = QString("qWarning(): %1").arg(msg); AssertOnQtMessage("WARNING", txt); break; case QtCriticalMsg: txt = QString("qCritical(): %1").arg(msg); AssertOnQtMessage("CRITICAL", txt); break; case QtFatalMsg: txt = QString("qFatal(): %1").arg(msg); AssertOnQtMessage("FATAL", txt); break; default: txt = QString("default: %1").arg(msg); break; } debug_window->EmitSetText(txt); } DebugWindow::DebugWindow() : QDialog(nullptr) , ui_(new Ui::DebugWindow) { ui_->setupUi(this); setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint); // Use monospace font style so that things align. QFont font("unexistent"); font.setStyleHint(QFont::Monospace); ui_->plain_text_edit_->setFont(font); connect(this, &DebugWindow::EmitSetText, this, &DebugWindow::SetText); RegisterDbgWindow(); } DebugWindow::~DebugWindow() { delete ui_; } void DebugWindow::ScrollToBottom() { QScrollBar* scroll_bar = ui_->plain_text_edit_->verticalScrollBar(); scroll_bar->setValue(scroll_bar->maximum()); } void DebugWindow::SetText(const QString& string) { ui_->plain_text_edit_->appendPlainText(string); ScrollToBottom(); } void DebugWindow::RegisterDbgWindow() { debug_window = this; qInstallMessageHandler(MyMessageHandler); } void DebugWindow::DbgMsg(const char* pFormat, ...) { if (debug_window != nullptr) { char buffer[2048]; va_list args; va_start(args, pFormat); vsnprintf(buffer, 2048, pFormat, args); debug_window->EmitSetText(QString(buffer)); rmv::LogFileWriter::Get().WriteLog(rmv::LogFileWriter::kDebug, buffer); va_end(args); } }
25.744526
116
0.633116
GPUOpen-Tools
d86e6d943a900d2b32bbb8f844002f43074e01ee
2,017
cpp
C++
Homeworks/Homework_10/Task_02/main.cpp
sdvelev/Data-Structures-and-Algorithms
286c29dc550bae1936869cf2c3a2c57c1242c60b
[ "MIT" ]
null
null
null
Homeworks/Homework_10/Task_02/main.cpp
sdvelev/Data-Structures-and-Algorithms
286c29dc550bae1936869cf2c3a2c57c1242c60b
[ "MIT" ]
null
null
null
Homeworks/Homework_10/Task_02/main.cpp
sdvelev/Data-Structures-and-Algorithms
286c29dc550bae1936869cf2c3a2c57c1242c60b
[ "MIT" ]
null
null
null
#include <cmath> #include <cstdio> #include <vector> #include<queue> #include <iostream> #include <algorithm> using namespace std; vector<pair<long long, long long>> neighbourSeats = { {-1, 0}, {0, 1}, {1, 0}, {0, -1} }; int main() { long long rows; cin >> rows; long long cols; cin >> cols; long long durationOfFilm; cin >> durationOfFilm; long long numberOfIllStudents; cin >> numberOfIllStudents; long long rowIll; long long colIll; vector<bool>* checked = new vector<bool>[rows]; for (long long i = 0; i < rows; i++) { checked[i].assign(cols, false); } queue<pair<long long, long long>> illQueue; queue<pair<long long, long long>> illQueue2; for (long long i = 0; i < numberOfIllStudents; i++) { cin >> rowIll; cin >> colIll; illQueue.push({ rowIll - 1, colIll - 1 }); checked[rowIll - 1][colIll - 1] = true; } long long healthyStudents = rows * cols - numberOfIllStudents; long long currentIter = 0; while (!illQueue.empty() && currentIter < durationOfFilm) { pair<long long, long long> currentElement = illQueue.front(); illQueue.pop(); for (long long t = 0; t < 4; t++) { long long nextIllRow = currentElement.first + neighbourSeats[t].first; long long nextIllCol = currentElement.second + neighbourSeats[t].second; if (nextIllRow < 0 || nextIllCol < 0 || nextIllRow >= rows || nextIllCol >= cols || checked[nextIllRow][nextIllCol] == true) { continue; } illQueue2.push({ nextIllRow, nextIllCol }); checked[nextIllRow][nextIllCol] = true; --healthyStudents; } if (illQueue.empty()) { ++currentIter; queue<pair<long long, long long>> temp = illQueue; illQueue = illQueue2; illQueue2 = temp; } } cout << healthyStudents; return 0; }
25.858974
102
0.567675
sdvelev
d86ec1d1d3fe451ce227964f3e0aab7d4dd1a32f
4,003
cc
C++
unique-binary-search-trees-2.cc
sonald/leetcode
3c34e2779a736acc880876f4244f1becd7b199ed
[ "MIT" ]
null
null
null
unique-binary-search-trees-2.cc
sonald/leetcode
3c34e2779a736acc880876f4244f1becd7b199ed
[ "MIT" ]
null
null
null
unique-binary-search-trees-2.cc
sonald/leetcode
3c34e2779a736acc880876f4244f1becd7b199ed
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> #include <cmath> #include <random> #include <set> #include <map> #include <unordered_map> #include <unordered_set> #include <queue> #include <algorithm> using namespace std; template<class T, class S> ostream& operator<<(ostream& os, const unordered_map<T, S>& v) { bool f = true; os << "{"; for (auto& t: v) { if (f) os << "(" << t.first << "," << t.second << ")"; else os << "," << "(" << t.first << "," << t.second << ")"; } return os << "}"; } template <class T> ostream& operator<<(ostream& os, const vector<T>& vs) { os << "["; for (auto& s: vs) { os << s << " "; } return os <<"]"; } /** * Definition for binary tree */ struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x, TreeNode* l = NULL, TreeNode* r = NULL) : val(x), left(l), right(r) {} }; class Solution { public: using Level = std::vector<TreeNode*>; vector<TreeNode *> generateTrees(int n) { if (n == 0) return {nullptr}; std::vector<Level> f(n+1); f[1] = { new TreeNode{1} }; for (int i = 2; i <= n; i++) { auto& l = f[i]; for (int j = 0; j < i; j++) { auto&& v = merge(f, j ,i-j-1); for (auto&& x: v) { l.push_back(x); } } } return f[n]; } Level merge(std::vector<Level> f, int i, int j) { Level res; auto& l = f[i]; auto& r = f[j]; int n = max((int)l.size(), 1), m = max((int)r.size(), 1); for (i = 0; i < n; i++) { for (j = 0; j < m; j++) { TreeNode* nd = new TreeNode(0); if (l.size()) cloneTree(&nd->left, l[i]); if (r.size()) cloneTree(&nd->right, r[j]); res.push_back(decorateTree(nd)); } } return res; } void cloneTree(TreeNode** pp, TreeNode* nd) { if (!nd) return; TreeNode* n = new TreeNode {nd->val}; *pp = n; if (nd->left) cloneTree(&(*pp)->left, nd->left); if (nd->right) cloneTree(&(*pp)->right, nd->right); } TreeNode* decorateTree(TreeNode* nd) { //inorder auto* root = nd; int i = 1; std::vector<TreeNode*> sp; while (nd || sp.size()) { while (nd) { sp.push_back(nd); nd = nd->left; } nd = sp.back(); sp.pop_back(); nd->val = i++; nd = nd->right; } return root; } }; class Solution2 { public: vector<TreeNode *> generateTrees(int n) { if (n == 0) return {nullptr}; return helper(1, n); } vector<TreeNode*> helper(int l, int r) { if (l > r) return {nullptr}; std::vector<TreeNode*> v; for (int id = l; id <= r; id++) { auto ls = helper(l, id-1); auto rs = helper(id+1, r); for (int i = 0; i < ls.size(); i++) { for (int j = 0; j < rs.size(); j++) { auto *r = new TreeNode(id); r->left = ls[i]; r->right = rs[j]; v.push_back(r); } } } return v; } }; void dump(TreeNode* nd) { // preorder std::vector<TreeNode*> sp; sp.push_back(nd); while (sp.size()) { auto* p = sp.back(); sp.pop_back(); if (p) cout << p->val << " "; else cout << "# "; if (p) { sp.push_back(p->right); sp.push_back(p->left); } } cout << endl; } void test(int n) { auto res = Solution2().generateTrees(n); cout << res.size() << endl; for (auto& p: res) dump(p); } int main(int argc, char const *argv[]) { // test(0); // test(1); test(2); test(3); // test(4); // 2 // Output: [{0,#,1},{0,1}] // Expected: [{1,#,2},{2,1}] return 0; }
23.686391
65
0.439171
sonald
d86f7530fc7e0e69adabc7a514cb22ba76c74ccf
1,440
cpp
C++
node_modules/lzz-gyp/lzz-source/gram_GetEnumtorSet.cpp
SuperDizor/dizornator
9f57dbb3f6af80283b4d977612c95190a3d47900
[ "ISC" ]
3
2019-09-18T16:44:33.000Z
2021-03-29T13:45:27.000Z
node_modules/lzz-gyp/lzz-source/gram_GetEnumtorSet.cpp
SuperDizor/dizornator
9f57dbb3f6af80283b4d977612c95190a3d47900
[ "ISC" ]
null
null
null
node_modules/lzz-gyp/lzz-source/gram_GetEnumtorSet.cpp
SuperDizor/dizornator
9f57dbb3f6af80283b4d977612c95190a3d47900
[ "ISC" ]
2
2019-03-29T01:06:38.000Z
2019-09-18T16:44:34.000Z
// gram_GetEnumtorSet.cpp // #include "gram_GetEnumtorSet.h" // gram #include "gram_BlockTable.h" #include "gram_GetNodeName.h" #include "gram_Nonterm.h" #include "gram_Visitor.h" // semantic #include "smtc_GetEnumtor.h" #define LZZ_INLINE inline namespace { using namespace gram; } namespace { struct GetEnumtorSet : Visitor { smtc::EnumtorPtrVector & enumtor_set; void visit (EnumtorDecl1Node & node) const; void visit (EnumtorDecl2Node & node) const; public: explicit GetEnumtorSet (smtc::EnumtorPtrVector & enumtor_set); ~ GetEnumtorSet (); }; } namespace { void GetEnumtorSet::visit (EnumtorDecl1Node & node) const { smtc::NamePtr name = getNodeName (node.getObjName ()); enumtor_set.push_back (smtc::getEnumtor (name)); } } namespace { void GetEnumtorSet::visit (EnumtorDecl2Node & node) const { smtc::NamePtr name = getNodeName (node.getObjName ()); Block init = getBlock (node.getBLOCK_TOKEN ().getLexeme ()); enumtor_set.push_back (smtc::getEnumtor (name, init)); } } namespace { LZZ_INLINE GetEnumtorSet::GetEnumtorSet (smtc::EnumtorPtrVector & enumtor_set) : enumtor_set (enumtor_set) {} } namespace { GetEnumtorSet::~ GetEnumtorSet () {} } namespace gram { void getEnumtorSet (basl::Nonterm & nonterm, smtc::EnumtorPtrVector & enumtor_set) { nonterm.accept (GetEnumtorSet (enumtor_set)); } } #undef LZZ_INLINE
21.818182
84
0.696528
SuperDizor
d873762ac3639ce333cbfad0522ba12c595fc408
22,294
cpp
C++
ReadThread.cpp
cyrilcluzel/CarbonCD
0ad3c5e9e19b1451cd71ae48f45c0aef9ebb94bc
[ "MIT" ]
8
2017-10-21T16:44:25.000Z
2021-06-04T13:00:54.000Z
ReadThread.cpp
cyrilcluzel/CarbonCD
0ad3c5e9e19b1451cd71ae48f45c0aef9ebb94bc
[ "MIT" ]
null
null
null
ReadThread.cpp
cyrilcluzel/CarbonCD
0ad3c5e9e19b1451cd71ae48f45c0aef9ebb94bc
[ "MIT" ]
4
2018-01-20T20:43:30.000Z
2021-06-04T13:00:56.000Z
#include "StdAfx.h" #include "Resource.h" #include "readthread.h" #include "ReadProgressDialog.h" #include "Setting.h" #include "CheckSector.h" #define PGB(a) ((BYTE *)(((DWORD)(a) + 0x0f) & ~0x0f)) static LPCSTR AudioMethod[11][2] = { {"READ D8", "A"}, {"MMC READ CDDA LBA", "B"}, {"MMC READ CDDA MSF", "B"}, {"MMC LBA", "C"}, {"MMC MSF", "C"}, {"MMC LBA(RAW)", "D"}, {"MMC MSF(RAW)", "D"}, {"READ(10)", "E"}, {"READ D4(10)", "X"}, {"READ D4(12)", "X"}, {"READ D5", "X"}, }; // Thread function for CReadThread static DWORD WINAPI ReadThread ( LPVOID Thread ) { DWORD RetValue; RetValue = ( ( CReadThread* ) Thread )->ThreadFunction(); ExitThread ( RetValue ); return RetValue; } DWORD CReadThread::ThreadFunction ( void ) { DWORD RetValue; CReadProgressDialog *Dlg = ( CReadProgressDialog* ) m_ParentWnd; m_ErrorCount = 0; if ( m_ReadImage ) { if ( theSetting.m_ReadEngine == 0 ) { RetValue = ReadDiscSS(); } else if ( theSetting.m_ReadEngine == 1 ) { RetValue = ReadDiscMS(); //#if ALPHA_MODE } else if ( theSetting.m_ReadEngine == 2 ) { RetValue = ReadDiscAlpha(); //#endif } else if ( theSetting.m_ReadEngine == 3 ) { RetValue = CompareData(); } } else { RetValue = ReadTrack(); } m_CD->SetErrorCorrectMode ( true ); // check & correct MODE1 ECC/EDC m_Success = false; if ( !m_StopFlag ) { Dlg->m_Percent = "100%"; Dlg->m_Progress.SetPos ( 100 ); if ( RetValue ) { if ( theSetting.m_IgnoreError && m_ErrorCount > 0 ) { CString cs; cs.Format ( MSG ( 98 ), m_ErrorCount ); m_LogWnd->AddMessage ( LOG_NORMAL, cs ); } Dlg->m_Message = MSG ( 99 ); m_LogWnd->AddMessage ( LOG_NORMAL, MSG ( 99 ) ); m_Success = true; PostMessage ( Dlg->m_hWnd, WM_COMMAND, ID_UPDATE_DIALOG, 0 ); } } Dlg->PostMessage ( WM_COMMAND, ID_WINDOW_CLOSE, 0 ); m_LogWnd->AutoSave(); return RetValue; } DWORD CReadThread::ReadTrack ( void ) { TableOfContents *Toc; CReadProgressDialog *Dlg = ( CReadProgressDialog* ) m_ParentWnd; int track, FileType; CString FileName; CString cs, tmp; Dlg->m_Progress.SetRange ( 0, 100 ); cs.Format ( "%s : Rip tracks", MSG ( 136 ) ); m_LogWnd->AddMessage ( LOG_NORMAL, cs ); if ( theSetting.m_AutoDetectMethod ) { DetectReadCommand(); } m_CD->SetErrorCorrectMode ( true ); // check & correct MODE1 ECC/EDC if ( m_StopFlag ) { return 0; } Toc = m_CD->GetTOC(); for ( track = 0; track < Toc->m_LastTrack; track++ ) { if ( Toc->m_Track[track].m_SelectFlag ) { if ( Toc->m_Track[track].m_TrackType == TRACKTYPE_AUDIO ) { FileName.Format ( "%s%02d.wav", m_FileName, track + 1 ); FileType = FILE_AUDIO; } else { FileName.Format ( "%s%02d.iso", m_FileName, track + 1 ); FileType = FILE_DATA; } if ( !m_ImageFile.Open ( FileName, FileType ) ) { cs.Format ( MSG ( 100 ), m_ImgFileName ); m_LogWnd->AddMessage ( LOG_ERROR, cs ); } else { if ( Toc->m_Track[track].m_TrackType == TRACKTYPE_AUDIO ) { cs.Format ( MSG ( 103 ), track + 1, AudioMethod[theSetting.m_ReadAudioMethod][0] ); } else { cs.Format ( MSG ( 104 ), track + 1 ); } cs += tmp; m_LogWnd->AddMessage ( LOG_INFO, cs ); Dlg->m_Message = cs; PostMessage ( Dlg->m_hWnd, WM_COMMAND, ID_UPDATE_DIALOG, 0 ); cs.Format ( MSG ( 105 ), FileName ); m_LogWnd->AddMessage ( LOG_INFO, cs ); ReadCD ( Toc->m_Track[track].m_MSF, Toc->m_Track[track].m_EndMSF, Toc->m_Track[track].m_TrackType ); m_ImageFile.Close(); if ( m_StopFlag ) { break; } } } } return 1; } CReadThread::CReadThread ( void ) { int i, c, crc; // generate crc table for ( i = 0; i < 256; i++ ) { crc = i << 8; for ( c = 0; c < 8; c++ ) { if ( crc & 0x8000 ) { crc = ( crc << 1 ) ^ 0x1021; } else { crc = ( crc << 1 ); } } m_SubcodeCRCTable[i] = crc & 0xffff; } // clear members m_StopFlag = false; m_hThread = INVALID_HANDLE_VALUE; m_CD = NULL; m_LogWnd = NULL; m_ParentWnd = NULL; m_CDTextLength = 0; } CReadThread::~CReadThread ( void ) { StopThread(); } void CReadThread::StartThread ( void ) { StopThread(); m_CurrentTrackType = -1; m_hThread = CreateThread ( NULL, 0, ReadThread, this, 0, &m_ThreadID ); if ( m_hThread == INVALID_HANDLE_VALUE ) { return; } SetThreadPriority ( m_hThread, THREAD_PRIORITY_NORMAL ); } void CReadThread::StopThread ( void ) { DWORD retcode; if ( m_hThread == INVALID_HANDLE_VALUE ) { return; } m_StopFlag = true; GetExitCodeThread ( m_hThread, &retcode ); if ( retcode == STILL_ACTIVE ) { retcode = WaitForSingleObject ( m_hThread, 3000 ); } GetExitCodeThread ( m_hThread, &retcode ); if ( retcode == STILL_ACTIVE ) { TerminateThread ( m_hThread, 1 ); } CloseHandle ( m_hThread ); m_hThread = INVALID_HANDLE_VALUE; } void CReadThread::CreateCueSheet ( void ) { CReadProgressDialog *Dlg = ( CReadProgressDialog* ) m_ParentWnd; FILE *fp; TableOfContents *Toc; MSFAddress PrevAddr, Tmp; DWORD HeadLBA; int track; fp = fopen ( m_CuePath, "w" ); if ( fp == NULL ) { CString cs; cs.Format ( MSG ( 106 ), m_CueFileName ); m_LogWnd->AddMessage ( LOG_ERROR, cs ); return; } Toc = m_CD->GetTOC(); PrevAddr = 150; HeadLBA = 150; fprintf ( fp, "FILE \"%s\" BINARY\n", m_ImgFileName ); for ( track = 0; track < Toc->m_LastTrack; track++ ) { if ( Toc->m_Track[track].m_TrackType == TRACKTYPE_AUDIO ) { fprintf ( fp, " TRACK %02d AUDIO\n", track + 1 ); } else if ( Toc->m_Track[track].m_TrackType == TRACKTYPE_DATA ) { fprintf ( fp, " TRACK %02d MODE1/2352\n", track + 1 ); } else if ( Toc->m_Track[track].m_TrackType == TRACKTYPE_DATA_2 ) { fprintf ( fp, " TRACK %02d MODE2/2352\n", track + 1 ); } if ( ! ( PrevAddr.GetByLBA() == Toc->m_Track[track].m_MSF.GetByLBA() ) ) { Tmp = PrevAddr - 150; fprintf ( fp, " INDEX 00 %02d:%02d:%02d\n", Tmp.Minute, Tmp.Second, Tmp.Frame ); } Tmp = Toc->m_Track[track].m_MSF.GetByLBA() - HeadLBA; fprintf ( fp, " INDEX 01 %02d:%02d:%02d\n", Tmp.Minute, Tmp.Second, Tmp.Frame ); PrevAddr = Toc->m_Track[track].m_EndMSF; } fclose ( fp ); { CString cs; cs.Format ( MSG ( 107 ), m_CuePath ); m_LogWnd->AddMessage ( LOG_NORMAL, cs ); } } void CReadThread::CreateFileName ( void ) { char Buffer[1024]; BYTE *p; BYTE *q; p = ( BYTE* ) ( ( LPCSTR ) m_FileName ); while ( *p != '\0' ) { if ( *p == '\\' ) { break; } p++; } if ( *p == '\\' ) { lstrcpy ( Buffer, m_FileName ); } else { lstrcpy ( Buffer, ".\\" ); lstrcat ( Buffer, m_FileName ); } // create CDM toc file name m_CCDPath = Buffer; // create base file name p = ( BYTE* ) Buffer + lstrlen ( Buffer ); while ( *p != '.' && p > ( BYTE* ) Buffer ) { p--; } if ( *p == '.' ) { *p = '\0'; } // create cue file name m_CuePath.Format ( "%s.cue", Buffer ); q = ( BYTE* ) ( ( LPCSTR ) m_CuePath ); while ( *q != '\0' ) { if ( ( *q >= 0x80 && *q <= 0x9f ) || *q > 0xe0 ) { q++; } else if ( *q == '\\' ) { m_CueFileName = ( LPCSTR ) ( q + 1 ); } q++; } // create image file name m_ImgPath.Format ( "%s.img", Buffer ); q = ( BYTE* ) ( ( LPCSTR ) ( m_ImgPath ) ); while ( *q != '\0' ) { if ( ( *q >= 0x80 && *q <= 0x9f ) || *q > 0xe0 ) { q++; } else if ( *q == '\\' ) { m_ImgFileName = LPCSTR ( q + 1 ); } q++; } // create subcode file name m_SubPath.Format ( "%s.sub", Buffer ); // create pregap file name m_PREPath.Format ( "%s.pre", Buffer ); // create temporary file name m_TmpPath.Format ( "%s.tmp", Buffer ); m_TmpSubPath.Format ( "%s.tms", Buffer ); } DWORD CReadThread::GetTime ( void ) { SYSTEMTIME st; GetSystemTime ( &st ); return st.wMilliseconds + 1000 * ( st.wSecond + 60 * ( st.wMinute + 60 * ( st.wHour + 24 * ( st.wDay + 365 * st.wYear ) ) ) ); } bool CReadThread::ReadCD ( MSFAddress Start, MSFAddress End, int TrackType ) { CReadProgressDialog *Dlg = ( CReadProgressDialog* ) m_ParentWnd; DWORD lba, lbaStart, lbaEnd; MSFAddress msf; DWORD Percent; BYTE *Buffer, B[2352 + 12 + 15]; bool RetFlag; BYTE TrackMode; int BurstErrorCount; Buffer = PGB ( B ); lbaStart = Start.GetByLBA(); lbaEnd = End.GetByLBA(); Dlg->m_Progress.SetPos ( 0 ); Percent = 0; m_TrackMode = 0; BurstErrorCount = 0; // view read speed if ( m_CurrentTrackType != TrackType ) { if ( TrackType == TRACKTYPE_DATA ) { m_CD->SetSpeed ( theSetting.m_Speed_Data, 0xff ); if ( theSetting.m_Speed_Data == 0xff ) { Dlg->m_Multi = "Max"; } else { Dlg->m_Multi.Format ( "x%d", theSetting.m_Speed_Data ); } } else { m_CD->SetSpeed ( theSetting.m_Speed_Audio, 0xff ); if ( theSetting.m_Speed_Audio == 0xff ) { Dlg->m_Multi = "Max"; } else { Dlg->m_Multi.Format ( "x%d", theSetting.m_Speed_Audio ); } } PostMessage ( Dlg->m_hWnd, WM_COMMAND, ID_UPDATE_DIALOG, 0 ); m_CurrentTrackType = TrackType; } TrackMode = 0; for ( lba = lbaStart; lba < lbaEnd; lba++ ) { if ( m_StopFlag ) { return false; } msf = lba; // read if ( TrackType == TRACKTYPE_DATA ) { RetFlag = m_CD->ReadCDRaw ( msf, Buffer ); if ( RetFlag == false && ( lba + 150 ) >= lbaEnd ) { RetFlag = m_CD->ReadCDAudio ( msf, Buffer ); if ( RetFlag ) { TrackType = TRACKTYPE_AUDIO; } } } else { RetFlag = m_CD->ReadCDAudio ( msf, Buffer ); if ( RetFlag == false && ( lba + 150 ) >= lbaEnd ) { RetFlag = m_CD->ReadCDRaw ( msf, Buffer ); if ( RetFlag ) { TrackType = TRACKTYPE_DATA; } } } // error recovery if ( RetFlag == false && TrackType == TRACKTYPE_DATA && lba >= ( lbaEnd - 149 ) ) { CString cs; memset ( Buffer, 0, 2352 ); if ( TrackMode == 2 ) { const BYTE MODE2Sync[23] = { 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x20 }; memcpy ( Buffer, MODE2Sync, 22 ); Buffer[0x000c] = ( ( msf.Minute / 10 ) * 0x10 ) + ( msf.Minute % 10 ); Buffer[0x000d] = ( ( msf.Second / 10 ) * 0x10 ) + ( msf.Second % 10 ); Buffer[0x000e] = ( ( msf.Frame / 10 ) * 0x10 ) + ( msf.Frame % 10 ); // set edc Buffer[0x092c] = 0x3f; Buffer[0x092d] = 0x13; Buffer[0x092e] = 0xb0; Buffer[0x092f] = 0xbe; } else if ( TrackMode == 1 ) { CCheckSector edc; edc.Mode1Raw ( Buffer, msf.Minute, msf.Second, msf.Frame ); } RetFlag = true; cs.Format ( "%02d:%02d.%02d(%6ld) %x", msf.Minute, msf.Second, msf.Frame, lba, MSG ( 108 ) ); m_LogWnd->AddMessage ( LOG_WARNING, cs ); } else if ( RetFlag == false && TrackMode != 0 ) { const BYTE MODE1Sync[16] = { 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x01 }; memset ( Buffer, 0x55, 2352 ); memcpy ( Buffer, MODE1Sync, 16 ); Buffer[0x000c] = ( ( msf.Minute / 10 ) * 0x10 ) + ( msf.Minute % 10 ); Buffer[0x000d] = ( ( msf.Second / 10 ) * 0x10 ) + ( msf.Second % 10 ); Buffer[0x000e] = ( ( msf.Frame / 10 ) * 0x10 ) + ( msf.Frame % 10 ); if ( TrackMode == 2 ) { Buffer[0x000f] = 0x02; } } else if ( RetFlag == false ) { memset ( Buffer, 0, 2352 ); } // ignore error(s) if ( RetFlag == false && theSetting.m_IgnoreError == true ) { CString cs; cs.Format ( "%02d:%02d.%02d(%6ld) %s", msf.Minute, msf.Second, msf.Frame, lba, MSG ( 109 ) ); m_LogWnd->AddMessage ( LOG_WARNING, cs ); RetFlag = true; m_ErrorCount++; BurstErrorCount++; } else { BurstErrorCount = 0; } // write if ( RetFlag ) { // reading is successful if ( TrackType == TRACKTYPE_DATA ) { TrackMode = Buffer[0x0f]; if ( m_TrackMode == 0 ) { m_TrackMode = TrackMode; } } else if ( TrackType == TRACKTYPE_AUDIO && theSetting.m_SwapChannel == true ) { int i; short tmp, *p; for ( i = 0; i < 2352; i += 4 ) { p = ( short* ) ( Buffer + i ); tmp = p[0]; p[0] = p[1]; p[1] = tmp; } } m_ImageFile.Write ( Buffer ); if ( BurstErrorCount > theSetting.m_BurstErrorCount && theSetting.m_BurstErrorScan ) { DWORD ErrorStart; ErrorStart = lba; lba = BurstErrorScan ( lba, End.GetByLBA(), TrackType, TrackMode ); m_ErrorCount += lba - ErrorStart; } } else { // reading is failure CString cs; DWORD ErrorCode; cs.Format ( "%02d:%02d.%02d(%6ld) ", msf.Minute, msf.Second, msf.Frame, lba, MSG ( 110 ) ); m_LogWnd->AddMessage ( LOG_ERROR, cs ); ErrorCode = m_CD->GetErrorStatus(); cs.Format ( "ErrorCode : %d SK:%02X ASC:%02X ASCQ:%02X", ErrorCode & 0xff, ( ErrorCode >> 24 ) & 0xff, ( ErrorCode >> 16 ) & 0xff, ( ErrorCode >> 8 ) & 0xff ); m_LogWnd->AddMessage ( LOG_ERROR, cs ); return false; } // display { DWORD p; p = ( ( lba - lbaStart ) * 100 ) / ( lbaEnd - lbaStart ); if ( p != Percent ) { Percent = p; Dlg->m_Percent.Format ( "%d%%", Percent ); PostMessage ( Dlg->m_hWnd, WM_COMMAND, ID_UPDATE_DIALOG, 0 ); Dlg->m_Progress.SetPos ( ( int ) Percent ); } } } Dlg->m_Progress.SetPos ( 100 ); Dlg->m_Percent = "100%"; PostMessage ( Dlg->m_hWnd, WM_COMMAND, ID_UPDATE_DIALOG, 0 ); return true; } void CReadThread::DetectReadCommand ( void ) { TableOfContents *Toc; int i, j; int Command; MSFAddress msf; BYTE Buffer[2352]; CString cs; Toc = m_CD->GetTOC(); for ( i = 0; i < Toc->m_LastTrack; i++ ) { if ( Toc->m_Track[i].m_TrackType == TRACKTYPE_AUDIO ) { msf = Toc->m_Track[i].m_MSF; break; } } if ( i == Toc->m_LastTrack ) { return; } m_LogWnd->AddMessage ( LOG_INFO, MSG ( 111 ) ); Command = -1; for ( i = 0; i < 11; i++ ) { memset ( Buffer, 0x55, 2352 ); theSetting.m_ReadAudioMethod = i; if ( m_CD->ReadCDAudio ( msf, Buffer ) ) { for ( j = 0; j < 2352; j++ ) { if ( Buffer[j] != 0x55 ) { break; } } if ( j < 2352 ) { cs.Format ( MSG ( 112 ), AudioMethod[i][0] ); m_LogWnd->AddMessage ( LOG_NORMAL, cs ); if ( Command == -1 ) { Command = i; } if ( *AudioMethod[Command][1] > *AudioMethod[i][1] ) { Command = i; } break; } } } if ( Command == -1 ) { Command = 0; m_LogWnd->AddMessage ( LOG_ERROR, MSG ( 113 ) ); } }
30.290761
130
0.375258
cyrilcluzel
d87c2759295b3ff40f17b255d110ce1d113b63a8
4,350
cpp
C++
src/PositionsFile.cpp
adbailey4/embed_fast5
4416fab3927a4f3deae2f4637ff6c7344b4098c9
[ "MIT" ]
null
null
null
src/PositionsFile.cpp
adbailey4/embed_fast5
4416fab3927a4f3deae2f4637ff6c7344b4098c9
[ "MIT" ]
1
2021-12-14T13:31:42.000Z
2022-03-12T17:41:30.000Z
src/PositionsFile.cpp
adbailey4/embed_fast5
4416fab3927a4f3deae2f4637ff6c7344b4098c9
[ "MIT" ]
null
null
null
// // Created by Andrew Bailey on 2019-07-15. // // Embed libs #include "PositionsFile.hpp" #include "EmbedUtils.hpp" using namespace std; using namespace embed_utils; /** * Deconstructor for PositionsFile. */ PositionsFile::~PositionsFile() = default; /** * Default constructor for PositionsFile. */ PositionsFile::PositionsFile(){ this->ambig_bases = create_ambig_bases(); } /** * Constructor which only initializes file path and does not "load" data. * @param input_reads_filename: path to positions file */ PositionsFile::PositionsFile(const std::string& input_reads_filename) { this->file_path = input_reads_filename; this->ambig_bases = create_ambig_bases(); } /** * Constructor for PositionsFile. * loads data and throws error if k is zero * @param input_reads_filename: path to positions file * @param k: kmer size */ PositionsFile::PositionsFile(const std::string& input_reads_filename, int64_t k){ throw_assert(k!=0, "k is zero. Check initialization of PositionsFile") this->file_path = input_reads_filename; this->ambig_bases = create_ambig_bases(); this->load_interval_map(k); } /** * Load positions file into interval map @param input_reads_filename: path to positions file @param k: kmer length */ void PositionsFile::load_interval_map(int64_t k) { for (auto &position_line: this->iterate()){ int64_t end_position = position_line.position - (k - 1); string contig_strand = position_line.contig+position_line.strand; if ( m_data.find(contig_strand) == m_data.end() ) { // not found interval_set<int64_t> intervalSet; m_data[contig_strand] = intervalSet; } // create interval discrete_interval<int64_t>::type positions(end_position, position_line.position, interval_bounds::closed()); m_data[contig_strand].insert(positions); } } /** * Load positions into map * * [contig+strand][position] = {change_from, change_to} * @param input_reads_filename: path to positions file @param k: kmer length */ void PositionsFile::load_positions_map(const std::string& input_reads_filename){ this->file_path = input_reads_filename; this->load_positions_map(); } /** * Load positions into map * * [contig+strand][position] = {change_from, change_to} * @param k: kmer length */ void PositionsFile::load_positions_map() { for (auto &position_line: this->iterate()){ string contig_strand = position_line.contig+position_line.strand; if ( positions_map.find(contig_strand) == positions_map.end() ) { // create contig strand map and position map map<uint64_t, tuple<string, string>> contig_positions = {{position_line.position, make_tuple(position_line.change_from, position_line.change_to)}}; positions_map[contig_strand] = contig_positions; } else { // add position to positions map positions_map[contig_strand][position_line.position] = make_tuple(position_line.change_from, position_line.change_to); } } } /** * check to see if position is in interval tree */ bool PositionsFile::is_in(string& contig, int64_t position){ const auto& iter = m_data.find(contig); if(iter == m_data.end()) { return false; } else { return contains(m_data[contig], position) ; } } /** Generate push type positions coroutine object file format: contig position strand change_from change_to ecoli 20 + A T */ void PositionsFile::positions_coroutine(positions_coro::push_type& yield){ std::ifstream in_file(this->file_path.c_str()); if(in_file.good()) { // read the file std::string line; while(getline(in_file, line)) { std::vector<std::string> fields = embed_utils::split_string(line, '\t'); string contig = fields[0]; int64_t start_position = embed_utils::string_to_int(fields[1]); string strand = fields[2]; string change_from = fields[3]; string change_to = fields[4]; yield(PositionLine(contig, start_position, strand, change_from, change_to)); } } else { cout << "Error loading file: " << this->file_path << "\n"; } in_file.close(); } /** Call push type coroutine to create a pull type coroutine */ positions_coro::pull_type PositionsFile::iterate(){ positions_coro::pull_type seq {bind(&PositionsFile::positions_coroutine, this, std::placeholders::_1)}; return seq; }
28.431373
153
0.708276
adbailey4