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
3e3f11d9a1f3ab6310eae363f1f436339e3d4e20
144
cpp
C++
ue4/Source/NaNRPG/Database/NaDatabaseConst.cpp
mekamarimo7777/NaNRPG
7f039319e0a40bf8df6ad449f5f8539d2be6a2c4
[ "MIT" ]
null
null
null
ue4/Source/NaNRPG/Database/NaDatabaseConst.cpp
mekamarimo7777/NaNRPG
7f039319e0a40bf8df6ad449f5f8539d2be6a2c4
[ "MIT" ]
null
null
null
ue4/Source/NaNRPG/Database/NaDatabaseConst.cpp
mekamarimo7777/NaNRPG
7f039319e0a40bf8df6ad449f5f8539d2be6a2c4
[ "MIT" ]
null
null
null
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "NaNRPG.h" #include "NaDatabaseConst.h"
20.571429
79
0.763889
mekamarimo7777
3e3f185fda335f99cb3b88719ae8a3e69d84d1e2
39,122
cpp
C++
EnsightMatlab/mexfiles/EnsightLib_interface.cpp
ITWM-TVFS/Ensight4Matlab
bafc148aaac9451c780483b8fb065571275d5bc1
[ "MIT" ]
7
2017-11-16T16:21:40.000Z
2022-02-21T12:48:16.000Z
EnsightMatlab/mexfiles/EnsightLib_interface.cpp
ITWM-TVFS/Ensight4Matlab
bafc148aaac9451c780483b8fb065571275d5bc1
[ "MIT" ]
null
null
null
EnsightMatlab/mexfiles/EnsightLib_interface.cpp
ITWM-TVFS/Ensight4Matlab
bafc148aaac9451c780483b8fb065571275d5bc1
[ "MIT" ]
3
2017-08-16T19:10:15.000Z
2020-06-18T08:43:04.000Z
/* * Copyright (c) 2016 Fraunhofer ITWM * * 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 "EnsightLib_interface.h" #include <QStringList> // ********** EnSight-MATLAB interface function ****// void mexFunction(int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]) { try { if (nrhs == 0) throw std::runtime_error("Expected at least one argument, got none."); // Load command string char command[64]; MexTools::MethodType methodType; int mID; MexTools::mapCommand(prhs, nrhs, command, sizeof(command), mID); methodType = MexTools::MethodType(mID); // Verify datatypes given by MATLAB MexTools::checkInputParam(prhs, nrhs, nlhs); if (methodType == MexTools::EInterface) { if (strcmp(command, "create") == 0) EnsightMatlab::createEnsight(plhs); else if (strcmp(command, "delete") == 0) EnsightMatlab::deleteEnsight(prhs); else if (strcmp(command, "read") == 0) EnsightMatlab::readEnsight(prhs, plhs); else throw std::runtime_error("Unknown method."); } else if (methodType == MexTools::EObject) { EnsightObj* object = EnsightMatlab::getEnsightObject(prhs); if (strcmp(command, "write") == 0) EnsightMatlab::writeEnsight(object, prhs); else if (strcmp(command, "beginEdit") == 0) EnsightMatlab::beginEdit(object); else if (strcmp(command, "endEdit") == 0) EnsightMatlab::endEdit(object); else if (strcmp(command, "createPart") == 0) EnsightMatlab::createEnsightPart(object, prhs); else if (strcmp(command, "clean") == 0) EnsightMatlab::cleanObject(object, prhs); else if (strcmp(command, "setStatic") == 0) EnsightMatlab::setStatic(object); else if (strcmp(command, "setTransient") == 0) EnsightMatlab::setTransient(object, prhs); else if (strcmp(command, "getGeometryBounds") == 0) EnsightMatlab::getObjectGeometryBounds(object, prhs, plhs); else if (strcmp(command, "createVariable") == 0) EnsightMatlab::createVariable(object, prhs); else if (strcmp(command, "addConstant") == 0) EnsightMatlab::addConstant(object, prhs); else if (strcmp(command, "replaceConstants") == 0) EnsightMatlab::replaceConstants(object, prhs); else if (strcmp(command, "getVariableBounds") == 0) EnsightMatlab::getVariableBounds(object, prhs, plhs); else if (strcmp(command, "createSubdivTree") == 0) EnsightMatlab::createSubdivTree(object, prhs); else if (strcmp(command, "interpolate") == 0) EnsightMatlab::interpolate(object, prhs, plhs); else if (strcmp(command, "findCell") == 0) EnsightMatlab::findCell(object, prhs, plhs); else if (strcmp(command, "getSubdivTreeBounds") == 0) EnsightMatlab::getSubdivTreeBounds(object, plhs); else throw std::runtime_error("Unknown method for EnsightObj."); } else if (methodType == MexTools::EPart) { EnsightObj* object = EnsightMatlab::getEnsightObject(prhs); EnsightPart* part = EnsightMatlab::getEnsightPart(object, prhs); if (strcmp(command, "clean") == 0) EnsightMatlab::cleanPart(part, prhs); else if (strcmp(command, "getGeometryBounds") == 0) EnsightMatlab::getPartGeometryBounds(part, prhs, plhs); else if (strcmp(command, "setVertices") == 0) EnsightMatlab::setVerticesOfPart(part, prhs); else if (strcmp(command, "getVertices") == 0) EnsightMatlab::getVerticesOfPart(part, prhs, plhs); else if (strcmp(command, "setCells") == 0) EnsightMatlab::setCellsOfPart(part, prhs); else if (strcmp(command, "getCellValues") == 0) EnsightMatlab::getCellValuesOfPart(part, prhs, plhs); else if (strcmp(command, "getCellBounds") == 0) EnsightMatlab::getCellBoundsOfPart(part, prhs, plhs); else if (strcmp(command, "getVertexCount") == 0) EnsightMatlab::getVertexCountOfPart(part, prhs, plhs); else if (strcmp(command, "setVariable") == 0) EnsightMatlab::setVariableForPart(part, prhs, plhs); else if (strcmp(command, "getVariableBounds") == 0) EnsightMatlab::getVariableBoundsOfPart(part, prhs, plhs); else if (strcmp(command, "getVariableValues") == 0) EnsightMatlab::getVariableValuesOfPart(part, prhs, plhs); else if (strcmp(command, "hasCellType") == 0) EnsightMatlab::partHasCelltype(part, prhs, plhs); else if (strcmp(command, "hasVariable") == 0) EnsightMatlab::partHasVariable(part, prhs, plhs); else if (strcmp(command, "getCellList") == 0) EnsightMatlab::getCellListOfPart(part, prhs, plhs); else throw std::runtime_error("Unknown method for EnsightPart."); } } catch (const std::runtime_error& e) { mexErrMsgIdAndTxt("EnsightMatlab:interfaceException", e.what()); } catch (const std::bad_alloc& e) { mexErrMsgIdAndTxt("EnsightMatlab:badAllocException", e.what()); } catch (const std::exception& e) { mexErrMsgIdAndTxt("EnsightMatlab:exception", e.what()); } catch (...) { mexErrMsgIdAndTxt("EnsightMatlab:unknownException", "An unknown error occured."); } return; } // ********** MEX helper functions ****// void MexTools::mapCommand(const mxArray* prhs[], int nrhs, char* command, int cmdSize, int& mID) { if (nrhs < 2) throw std::runtime_error("Expected at least two arguments. "); char level[64]; if (mxGetString(prhs[0], level, sizeof(level))) throw std::runtime_error("Input[0]: Could not read command string."); if (mxGetString(prhs[1], command, cmdSize)) throw std::runtime_error("Input[1]: Could not read command string."); if (strcmp(level, "obj") == 0) mID = 1; else if (strcmp(level, "part") == 0) mID = 2; else if (strcmp(level, "interface") == 0) mID = 0; else throw std::runtime_error("Invalid method type identifier."); } void MexTools::checkInputParam(const mxArray* prhs[], int nrhs, int nlhs) { /* * EnsightLib_interface function call Layout * prhs[0] : (string) method level * prhs[1] : (string) method name * prhs[2] : (ptr) EnsightObj pointer * prhs[3] : (numeric) [nArguments, ArgTypes ... ] * prhs[4] : ... first parameter * prhs[3+nArguments] : ... last parameter */ if (nrhs < 3) throw std::runtime_error("Expected at least three arguments. "); double* typeList = mxGetPr(prhs[2]); const mwSize* dim = mxGetDimensions(prhs[2]); int n = std::max(static_cast<int>(dim[0]), static_cast<int>(dim[1])); int nIn = static_cast<int>(typeList[0]); int nOut = static_cast<int>(typeList[1]); if (nrhs < nIn + 3) { char err[128]; sprintf(err, "Invalid number of input arguments. Got: %d , Expected: %d", nrhs - 3, nIn); throw std::runtime_error(err); } if (nlhs != nOut) { char err[128]; sprintf(err, "Invalid number of output arguments. Got: %d , Expected: %d", nlhs, nOut); throw std::runtime_error(err); } if (n < nIn + 2) throw std::runtime_error("Invalid valueTypeArray."); MexTools::Type type; for (int i = 0; i < nIn; i++) { if (((int)typeList[i + 2] < 0) || ((int)typeList[i + 2] > 5)) { char err[128]; sprintf(err, "Input[%d]: Invalid type identifier. ID:%d", i, (int)typeList[i + 2]); throw std::runtime_error(err); } type = MexTools::Type(static_cast<int>(typeList[i + 2])); if (type == MexTools::TAbstract) { } else if ((type == MexTools::TNumeric) && (!mxIsNumeric(prhs[i + 3]))) { char err[128]; sprintf(err, "Input[%d]: Numeric value expected.", i); throw std::runtime_error(err); } else if ((type == MexTools::TStruct) && (!mxIsStruct(prhs[i + 3]))) { char err[128]; sprintf(err, "Input[%d]: Struct expected.", i); throw std::runtime_error(err); } else if ((type == MexTools::TCell) && (!mxIsCell(prhs[i + 3]))) { char err[128]; sprintf(err, "Input[%d]: Cell array expected.", i); throw std::runtime_error(err); } else if ((type == MexTools::TString) && (!mxIsChar(prhs[i + 3]))) { char err[128]; sprintf(err, "Input[%d]: String expected.", i); throw std::runtime_error(err); } else if ((type == MexTools::TBool) && (!mxIsLogical(prhs[i + 3]))) { char err[128]; sprintf(err, "Input[%d]: Boolean value expected.", i); throw std::runtime_error(err); } } } const Mati MexTools::getIntegerMatrix(const mxArray* prhs[], int slot) { const mwSize* dim = mxGetDimensions(prhs[slot]); double* input = mxGetPr(prhs[slot]); int m = static_cast<int>(dim[0]); int n = static_cast<int>(dim[1]); Eigen::MatrixXi Matrix(m, n); for (int i = 0; i < m; i++) for (int j = 0; j < n; j++) Matrix(i, j) = static_cast<int>(input[i + m * j]); return Matrix; } const Matx MexTools::getDoubleMatrix(const mxArray* prhs[], int slot) { const mwSize* dim = mxGetDimensions(prhs[slot]); double* input = mxGetPr(prhs[slot]); int m = static_cast<int>(dim[0]); int n = static_cast<int>(dim[1]); //auto mat = std::allocate_shared<Matx>( Matx(m,n) ); Matx matrix(m,n); for (int i = 0; i < m; i++) for (int j = 0; j < n; j++) matrix(i,j) = static_cast<double>(input[i + j * m]); return matrix; } const Vecx MexTools::getDoubleVector(const mxArray* prhs[], int slot) { const mwSize* dim = mxGetDimensions(prhs[slot]); double* input = mxGetPr(prhs[slot]); int m = static_cast<int>(dim[0]); int n = static_cast<int>(dim[1]); if (m > 1 && n > 1) throw std::runtime_error("Invalid dimensions."); int N = std::max(m, n); Eigen::VectorXd Vector(N); for (int i = 0; i < N; i++) Vector(i) = static_cast<double>(input[i]); return Vector; } const Veci MexTools::getIntegerVector(const mxArray* prhs[], int slot) { const mwSize* dim = mxGetDimensions(prhs[slot]); double* input = mxGetPr(prhs[slot]); int m = static_cast<int>(dim[0]); int n = static_cast<int>(dim[1]); if (m > 1 && n > 1) throw std::runtime_error("Invalid dimensions."); int N = std::max(m, n); Eigen::VectorXi Vector(N); for (int i = 0; i < N; i++) Vector(i) = static_cast<int>(input[i]); return Vector; } const double MexTools::getDoubleScalar(const mxArray* prhs[], int slot) { const mwSize* dim = mxGetDimensions(prhs[slot]); int m = static_cast<int>(dim[0]); int n = static_cast<int>(dim[1]); if (m > 1 || n > 1) throw std::runtime_error("Expected scalar, but got Vector."); double scalar = static_cast<double>(mxGetPr(prhs[slot])[0]); return scalar; } const int MexTools::getIntegerScalar(const mxArray* prhs[], int slot) { const mwSize* dim = mxGetDimensions(prhs[slot]); int m = static_cast<int>(dim[0]); int n = static_cast<int>(dim[1]); if (m > 1 || n > 1) throw std::runtime_error("Expected scalar, but got Vector."); int scalar = static_cast<int>(mxGetPr(prhs[slot])[0]); return scalar; } void MexTools::mexAllocateAndCopyMatrix(const Eigen::MatrixXd& Matrix, mxArray* plhs[], int slot) { int m = Matrix.rows(); int n = Matrix.cols(); plhs[slot] = mxCreateDoubleMatrix(m, n, mxREAL); double* output = mxGetPr(plhs[slot]); for (int i = 0; i < m; i++) for (int j = 0; j < n; j++) output[i + j * m] = Matrix(i, j); } void MexTools::mexAllocateAndCopyMatrix(const Eigen::MatrixXi& Matrix, mxArray* plhs[], int slot) { int m = Matrix.rows(); int n = Matrix.cols(); plhs[slot] = mxCreateDoubleMatrix(m, n, mxREAL); double* output = mxGetPr(plhs[slot]); for (int i = 0; i < m; i++) for (int j = 0; j < n; j++) output[i + j * m] = Matrix(i, j); } void MexTools::mexAllocateAndCopyMatrix(const Eigen::VectorXd& Vector, mxArray* plhs[], int slot) { int n = Vector.cols(); plhs[slot] = mxCreateDoubleMatrix(n, 1, mxREAL); double* output = mxGetPr(plhs[slot]); for (int i = 0; i < n; i++) output[i] = static_cast<double>(Vector(i)); } void MexTools::mexAllocateAndCopyMatrix(const Eigen::VectorXi& Vector, mxArray* plhs[], int slot) { int n = Vector.cols(); plhs[slot] = mxCreateDoubleMatrix(n, 1, mxREAL); double* output = mxGetPr(plhs[slot]); for (int i = 0; i < n; i++) output[i] = static_cast<double>(Vector(i)); } // ********** EnSightLib interface methods ****// EnsightObj* EnsightMatlab::getEnsightObject(const mxArray* prhs[]) { EnsightObj* object = convertMat2Ptr<EnsightObj>(prhs[3]); if (object == 0) throw std::runtime_error("Pointer to EnsightObject is invalid."); return object; } EnsightPart* EnsightMatlab::getEnsightPart(EnsightObj* object, const mxArray* prhs[]) { int partID = static_cast<int>(mxGetPr(prhs[4])[0]); EnsightPart* part = object->getPartById(partID); if (part == 0) throw std::runtime_error("Invalid partID."); return part; } void EnsightMatlab::createEnsight(mxArray* plhs[]) { // Return a handle to a new C++ instance of EnsightObj EnsightObj* object = EnsightLib::createEnsight(); if (object == 0) throw std::runtime_error("Could not create EnSight object."); plhs[0] = convertPtr2Mat<EnsightObj>(object); } void EnsightMatlab::deleteEnsight(const mxArray* prhs[]) { destroyObject<EnsightLib>(prhs[3]); } void EnsightMatlab::readEnsight(const mxArray* prhs[], mxArray* plhs[]) { char filename[2048]; double* outArray; mxArray* valueArray; mxGetString(prhs[3], filename, sizeof(filename)); // Return a handle to a new C++ instance of EnsightObj EnsightObj* object = EnsightLib::readEnsight(QString(filename)); if (object == 0) throw std::runtime_error(std::string("Could not read file. EnsightObj::ERROR_STR='") + EnsightObj::ERROR_STR.toStdString() + "'"); int NTstep = object->getNumberOfTimesteps(); int NVar = object->getNumberOfVariables(); int NParts = object->getNumberOfParts(); int NConst = object->getNumberOfConstants(); // Object Handle plhs[0] = convertPtr2Mat<EnsightObj>(object); // Create NParts_x_2 CellArray {part_id, part_name} representing the underlying parts plhs[1] = mxCreateCellMatrix(NParts, 2); for (int i = 0; i < NParts; i++) { EnsightPart* part = object->getPart(i); if (part != 0) { // Part ID valueArray = mxCreateDoubleScalar(part->getId()); mxSetCell(plhs[1], i, valueArray); mxSetCell(plhs[1], i + NParts, mxCreateString(part->getName().toLatin1().data())); } } // Create NConst_x_2 CellArray {const_name, const_value} representing the constants plhs[2] = mxCreateCellMatrix(NConst, 2); // Members of QHash can be easily accessed using an iterator for (int i = 0; i < NConst; ++i) { // mxCreateString only takes C-style char[]-Arrays, no std::String ! // qstring.toLatin1().data() converts a QString variable to char[] const EnsightConstant cnst = object->getConstant(i); mxSetCell(plhs[2], i, mxCreateString(cnst.getName().toLatin1().data())); // Insert constant value (double) valueArray = mxCreateDoubleScalar(cnst.getValue()); mxSetCell(plhs[2], i + NConst, valueArray); } // Create NVar_x_4 CellArray {variable_name, type, dimensions} representing the variables plhs[3] = mxCreateCellMatrix(NVar, 3); for (int i = 0; i < NVar; i++) { EnsightVariableIdentifier var = object->getVariable(i); // mxCreateString only takes C-style char[]-Arrays, no std::String ! // qstring.toLatin1().data() converts a QString variable to char[] valueArray = mxCreateString(var.getName().toLatin1().data()); mxSetCell(plhs[3], i, valueArray); // Variable Type mxSetCell(plhs[3], i + NVar, mxCreateDoubleScalar(static_cast<int>(var.getType()))); // dimension of variable(i) valueArray = mxCreateDoubleScalar(static_cast<double>(var.getDim())); mxSetCell(plhs[3], i + 2 * NVar, valueArray); } // SubdivTree struct-array with five fields (is not saved in .case files) const char* field_names[] = {"created", "maxLevel", "maxElements", "offset", "bounds"}; mwSize dims[2] = {1, 1}; // Create Struct plhs[4] = mxCreateStructArray(2, dims, 5, field_names); // 0: created->false valueArray = mxCreateLogicalScalar(false); mxSetFieldByNumber(plhs[4], 0, 0, valueArray); // 1: maxLevel->0 valueArray = mxCreateDoubleScalar(0); mxSetFieldByNumber(plhs[4], 0, 1, valueArray); // 2: maxLevel->0 valueArray = mxCreateDoubleScalar(0); mxSetFieldByNumber(plhs[4], 0, 2, valueArray); // 3: offset->0.0 valueArray = mxCreateDoubleScalar(0.0); mxSetFieldByNumber(plhs[4], 0, 3, valueArray); // 4: bounds->[0 0 0; 0 0 0] valueArray = mxCreateDoubleMatrix(3, 2, mxREAL); mxSetFieldByNumber(plhs[4], 0, 4, valueArray); double* values = mxGetPr(valueArray); for (int i = 0; i < 6; i++) values[i] = 0.0; // return timesteps plhs[5] = mxCreateDoubleMatrix(1, NTstep, mxREAL); outArray = mxGetPr(plhs[5]); if (NTstep == 1) outArray[0] = 0.0; else { Vecx timesteps = object->getTimesteps(); for (int i = 0; i < NTstep; i++) outArray[i] = timesteps(i); } } void EnsightMatlab::writeEnsight(EnsightObj* object, const mxArray* prhs[]) { char filename[2048]; if (mxGetString(prhs[4], filename, sizeof(filename))) throw std::runtime_error("Second input (filename) should be a string less than 512 characters long."); const bool mode = static_cast<bool>(MexTools::getIntegerScalar(prhs, 5)); const double timestep = MexTools::getIntegerScalar(prhs, 6); bool success = EnsightLib::writeEnsight(object, QString(filename), mode, timestep); if (!success) throw std::runtime_error(object->ERROR_STR.toLatin1().data()); } // ********** EnsightObj methods ***********// void EnsightMatlab::beginEdit(EnsightObj* object) { object->beginEdit(); } void EnsightMatlab::endEdit(EnsightObj* object) { bool success = object->endEdit(); if (!success) throw std::runtime_error(object->ERROR_STR.toLatin1().data()); } void EnsightMatlab::createEnsightPart(EnsightObj* object, const mxArray* prhs[]) { char partname[64]; // Get parameters mxGetString(prhs[4], partname, sizeof(partname)); const int id = MexTools::getIntegerScalar(prhs, 5); bool success = object->createEnsightPart(QString(partname), id); if (!success) throw std::runtime_error(object->ERROR_STR.toLatin1().data()); } void EnsightMatlab::setStatic(EnsightObj* object) { bool success = object->setStatic(); if (!success) throw std::runtime_error(object->ERROR_STR.toLatin1().data()); } void EnsightMatlab::setTransient(EnsightObj* object, const mxArray* prhs[]) { // read MATLAB input const Vecx timesteps = MexTools::getDoubleVector(prhs, 4); bool success = object->setTransient(timesteps); if (!success) throw std::runtime_error(object->ERROR_STR.toLatin1().data()); } void EnsightMatlab::cleanObject(EnsightObj* object, const mxArray* prhs[]) { const int timestep = MexTools::getIntegerScalar(prhs, 4); object->clean(timestep); } void EnsightMatlab::getObjectGeometryBounds(EnsightObj* object, const mxArray* prhs[], mxArray* plhs[]) { // Access first input const int timestep = MexTools::getIntegerScalar(prhs, 4); // Get bounding box from C++ object Bbox bound; for (int i = 0; i < object->getNumberOfParts(); i++) bound.extend(object->getPart(i)->getGeometryBounds(timestep)); Eigen::MatrixXd output(3, 2); output.block(0, 0, 3, 1) = bound.minCorner(); output.block(0, 1, 3, 1) = bound.maxCorner(); MexTools::mexAllocateAndCopyMatrix(output, plhs, 0); } void EnsightMatlab::createVariable(EnsightObj* object, const mxArray* prhs[]) { char name[64]; mxGetString(prhs[4], name, sizeof(name)); const int type = MexTools::getIntegerScalar(prhs, 5); bool success = object->createVariable(QString(name), Ensight::VarTypes(type)); if (!success) throw std::runtime_error(object->ERROR_STR.toLatin1().data()); } void EnsightMatlab::addConstant(EnsightObj* object, const mxArray* prhs[]) { char name[64]; mxGetString(prhs[4], name, sizeof(name)); const double value = MexTools::getDoubleScalar(prhs, 5); const QString qName(name); bool success = object->addConstant(qName, value); if (!success) throw std::runtime_error(object->ERROR_STR.toLatin1().data()); } void EnsightMatlab::replaceConstants(EnsightObj* object, const mxArray* prhs[]) { char name[64]; mxArray* cellPointer; const mwSize* dims = mxGetDimensions(prhs[2]); int m = static_cast<int>(dims[0]); for (int i = 0; i < m; i++) { cellPointer = mxGetCell(prhs[2], i); mxGetString(cellPointer, name, sizeof(name)); cellPointer = mxGetCell(prhs[2], i + m); if (object->hasConstant(QString(name))) { double value = static_cast<double>(mxGetPr(cellPointer)[0]); const QString qName(name); bool success = object->removeConstant(qName); success &= object->addConstant(qName, value); if (!success) throw std::runtime_error(object->ERROR_STR.toLatin1().data()); } else { char warnmsg[128]; sprintf(warnmsg, "obj_replaceConstants - invalid constant name '%c'\n", name); mexWarnMsgTxt(warnmsg); } } } void EnsightMatlab::getVariableBounds(EnsightObj* object, const mxArray* prhs[], mxArray* plhs[]) { // Access parameters char name[64]; mxGetString(prhs[4], name, sizeof(name)); const int timestep = MexTools::getIntegerScalar(prhs, 5); // Get matrix with variable bounds Matx bounds = object->getVariableBounds(QString(name), timestep); MexTools::mexAllocateAndCopyMatrix(bounds, plhs, 0); } void EnsightMatlab::getSubdivTreeBounds(EnsightObj* object, mxArray* plhs[]) { EnsightSubdivTree* subdivTree = object->getSubdivTree(); Eigen::MatrixXd output = Eigen::MatrixXd::Zero(3, 2); if (subdivTree == 0) mexWarnMsgTxt("Searchtree has not been initialized yet."); else { Bbox bounds = subdivTree->getBounds(); output.block(0, 0, 3, 1) = bounds.minCorner(); output.block(0, 1, 3, 1) = bounds.maxCorner(); } MexTools::mexAllocateAndCopyMatrix(output, plhs, 0); } // *************** EnsightPart methods ******************* // void EnsightMatlab::cleanPart(EnsightPart* part, const mxArray* prhs[]) { const int timestep = MexTools::getIntegerScalar(prhs, 5); part->clean(timestep); } void EnsightMatlab::getPartGeometryBounds(EnsightPart* part, const mxArray* prhs[], mxArray* plhs[]) { // Access parameters const int timestep = MexTools::getIntegerScalar(prhs, 5); Eigen::MatrixXd output = Eigen::MatrixXd::Zero(3, 2); Bbox bounds = part->getGeometryBounds(timestep); output.block(0, 0, 3, 1) = bounds.minCorner(); output.block(0, 1, 3, 1) = bounds.maxCorner(); MexTools::mexAllocateAndCopyMatrix(output, plhs, 0); } void EnsightMatlab::setVerticesOfPart(EnsightPart* part, const mxArray* prhs[]) { // Access parameters const Matx vertices = MexTools::getDoubleMatrix(prhs, 5); const int timestep = MexTools::getIntegerScalar(prhs, 6); part->setVertices( vertices, timestep); } void EnsightMatlab::getVerticesOfPart(EnsightPart* part, const mxArray* prhs[], mxArray* plhs[]) { // Access first parameter const int timestep = MexTools::getIntegerScalar(prhs, 5); // Call C++ method Matx vertices = part->getVertices(timestep); MexTools::mexAllocateAndCopyMatrix(vertices, plhs, 0); } void EnsightMatlab::partHasCelltype(EnsightPart* part, const mxArray* prhs[], mxArray* plhs[]) { const int timestep = MexTools::getIntegerScalar(prhs, 5); const int celltype = MexTools::getIntegerScalar(prhs, 6); bool result = part->hasCellType(timestep, Ensight::Cell(celltype)); plhs[0] = mxCreateLogicalScalar(result); } void EnsightMatlab::setCellsOfPart(EnsightPart* part, const mxArray* prhs[]) { // Access parameters const Mati nodes = MexTools::getIntegerMatrix(prhs, 5); const int timestep = MexTools::getIntegerScalar(prhs, 6); const int celltype = MexTools::getIntegerScalar(prhs, 7); part->setCells(nodes, timestep, Ensight::Cell(celltype)); } void EnsightMatlab::getCellListOfPart(EnsightPart* part, const mxArray* prhs[], mxArray* plhs[]) { const int timestep = MexTools::getIntegerScalar(prhs, 5); Eigen::MatrixXd output = Eigen::MatrixXd::Zero(1, 8); for (int i = 0; i < 8; i++) { EnsightCellList* cellist = part->getCells(timestep, Ensight::Cell(i)); if (cellist != 0) output(i) = cellist->getValues().cols(); } MexTools::mexAllocateAndCopyMatrix(output, plhs, 0); } void EnsightMatlab::getCellValuesOfPart(EnsightPart* part, const mxArray* prhs[], mxArray* plhs[]) { const int celltype = MexTools::getIntegerScalar(prhs, 5); const int timestep = MexTools::getIntegerScalar(prhs, 6); EnsightCellList* cellList = part->getCells(timestep, Ensight::Cell(celltype)); if (cellList == 0) throw std::runtime_error("Cells of this type do not exist."); Eigen::MatrixXi values = cellList->getValues(); MexTools::mexAllocateAndCopyMatrix(values, plhs, 0); } void EnsightMatlab::getCellBoundsOfPart(EnsightPart* part, const mxArray* prhs[], mxArray* plhs[]) { const Veci cell = MexTools::getIntegerVector(prhs, 5); const int timestep = MexTools::getIntegerScalar(prhs, 6); Eigen::MatrixXd output = Eigen::MatrixXd::Zero(3, 2); Bbox bounds = part->getCellBounds(cell, timestep); output.block(0, 0, 3, 1) = bounds.minCorner(); output.block(0, 1, 3, 1) = bounds.maxCorner(); MexTools::mexAllocateAndCopyMatrix(output, plhs, 0); } void EnsightMatlab::getVertexCountOfPart(EnsightPart* part, const mxArray* prhs[], mxArray* plhs[]) { const int timestep = MexTools::getIntegerScalar(prhs, 5); int vertexCount = part->getVertexCount(timestep); plhs[0] = mxCreateDoubleScalar(vertexCount); } void EnsightMatlab::setVariableForPart(EnsightPart* part, const mxArray* prhs[], mxArray* plhs[]) { // Access parameters const Matx variableValues = MexTools::getDoubleMatrix(prhs, 6); char variableName[64]; mxGetString(prhs[5], variableName, sizeof(variableName)); const int variableType = MexTools::getIntegerScalar(prhs, 7); const int timestep = MexTools::getIntegerScalar(prhs, 8); part->setVariable(QString(variableName), variableValues, Ensight::VarTypes(variableType), timestep); } void EnsightMatlab::getVariableBoundsOfPart(EnsightPart* part, const mxArray* prhs[], mxArray* plhs[]) { // Access parameters char variableName[64]; mxGetString(prhs[5], variableName, sizeof(variableName)); const int timestep = MexTools::getIntegerScalar(prhs, 6); // Get matrix with variable bounds const Matx bounds = part->getVariableBounds(QString(variableName), timestep); MexTools::mexAllocateAndCopyMatrix(bounds, plhs, 0); } void EnsightMatlab::getVariableValuesOfPart(EnsightPart* part, const mxArray* prhs[], mxArray* plhs[]) { // Access parameters char variableName[64]; mxGetString(prhs[5], variableName, sizeof(variableName)); const int timestep = MexTools::getIntegerScalar(prhs, 6); const Matx values = part->getVariableValues(QString(variableName), timestep); MexTools::mexAllocateAndCopyMatrix(values, plhs, 0); } void EnsightMatlab::partHasVariable(EnsightPart* part, const mxArray* prhs[], mxArray* plhs[]) { // Access parameters char variableName[64]; mxGetString(prhs[5], variableName, sizeof(variableName)); const int timestep = MexTools::getIntegerScalar(prhs, 6); // Call C++ routine bool result = part->hasVariable(QString(variableName), timestep); plhs[0] = mxCreateLogicalScalar(result); } // ********** EnsightSubdivTree and interpolation methods ***********// void EnsightMatlab::createSubdivTree(EnsightObj* object, const mxArray* prhs[]) { // Access input parameters const int maxDepth = MexTools::getIntegerScalar(prhs, 4); const int maxElements = MexTools::getIntegerScalar(prhs, 5); const double sizeOffset = MexTools::getDoubleScalar(prhs, 6); QStringList partsToExclude; bool success = object->createSubdivTree(maxDepth, maxElements, partsToExclude, sizeOffset); if (!success) throw std::runtime_error(object->ERROR_STR.toLatin1().data()); } void EnsightMatlab::interpolate(EnsightObj* object, const mxArray* prhs[], mxArray* plhs[]) { char variableName[64]; mxGetString(prhs[5], variableName, sizeof(variableName)); const Vec3 pos = MexTools::getDoubleVector(prhs, 4); if (!object->hasVariable(QString(variableName))) throw std::runtime_error("Variable does not exist."); if (object->getSubdivTree() == 0) { QStringList partsToExclude; object->createSubdivTree(7, 50, partsToExclude, 0.0); } // Search SubdivTree EnsightBarycentricCoordinates barycoords; EnsightCellIdentifier* cell = object->interpolate(pos, barycoords); if (cell == NULL) { plhs[0] = mxCreateDoubleScalar(0.0); plhs[1] = mxCreateLogicalScalar(false); } else { try { const Eigen::MatrixXd values = cell->getValues(QString(variableName)); Eigen::VectorXd result = barycoords.evaluate(values); MexTools::mexAllocateAndCopyMatrix(result, plhs, 0); plhs[1] = mxCreateLogicalScalar(true); } catch (...) { throw std::runtime_error(object->ERROR_STR.toLatin1().data()); } } } void EnsightMatlab::findCell(EnsightObj* object, const mxArray* prhs[], mxArray* plhs[]) { int optLength = 0; bool ok_volume = false, ok_centroid = false; if (object->getSubdivTree() == 0) { QStringList partsToExclude; object->createSubdivTree(7, 50, partsToExclude, 0.0); } // Access parameters const Matx lineSegments = MexTools::getDoubleMatrix(prhs, 4); char options[64]; mxGetString(prhs[5], options, sizeof(options)); // Specify further options optLength = options[0] - '0'; for (int i = 1; i <= optLength; ++i) if (options[i] == 'v') ok_volume = true; else if (options[i] == 'c') ok_centroid = true; // Get pointer to EnsightSubdivTree EnsightSubdivTree* subdivTree = object->getSubdivTree(); if (subdivTree == 0) { mexWarnMsgTxt("SubdivTree has not been created. Attempting to create it."); QStringList partsToExclude; bool success = object->createSubdivTree(7, 50, partsToExclude, 0.0); if (!success) throw std::runtime_error("Could not create SubdivTree."); } EnsightBarycentricCoordinates bary; int numberOfPoints = lineSegments.cols(); // Save handle_pointers in cell array if (ok_volume && ok_centroid) { Eigen::MatrixXd output(7, numberOfPoints); EnsightCellIdentifier* cell; // Run subdiv tree search for each point for (int i = 0; i < numberOfPoints; i++) { cell = subdivTree->search( lineSegments.col(i), bary); // Cell found // Compute a unique triplet (cell_id, type_id, part_id) representing the cell if (cell != 0) { // Compute centroid Veci vId = cell->getCell(); Vec3 centroid = Eigen::Vector3d::Zero(); double scale = 1.0 / vId.rows(); for (int c = 0; c < vId.rows(); c++) centroid += scale * cell->getVertex(c); // Save results output(0, i) = cell->getIndex(); output(1, i) = cell->getCellList()->getType(); output(2, i) = object->getPartByName(cell->getCellList()->getPartName())->getId(); output(3, i) = cell->computeVolume(); output(4, i) = centroid(0); output(5, i) = centroid(1); output(6, i) = centroid(2); } else { // Convention: Set result to (-1,-1,-1,0,0,0,0) if result is empty output(0, i) = -1; output(1, i) = -1; output(2, i) = -1; output(3, i) = 0.0; output(4, i) = 0.0; output(5, i) = 0.0; output(6, i) = 0.0; } } MexTools::mexAllocateAndCopyMatrix(output, plhs, 0); } else if (ok_volume) { Eigen::MatrixXd output(4, numberOfPoints); EnsightCellIdentifier* cell; // Run subdiv tree search for each point for (int i = 0; i < numberOfPoints; i++) { cell = subdivTree->search(lineSegments.col(i), bary); // Cell found // Compute a unique triplet (cell_id, type_id, part_id) representing the cell if (cell != 0) { // Save results output(0, i) = cell->getIndex(); output(1, i) = cell->getCellList()->getType(); output(2, i) = object->getPartByName(cell->getCellList()->getPartName())->getId(); output(3, i) = cell->computeVolume(); } else { // Convention: Set result to (-1,-1,-1,0) if result is empty output(0, i) = -1; output(1, i) = -1; output(2, i) = -1; output(3, i) = 0.0; } } MexTools::mexAllocateAndCopyMatrix(output, plhs, 0); } else if (ok_centroid) { Eigen::MatrixXd output(6, numberOfPoints); EnsightCellIdentifier* cell; // Run subdiv tree search for each point for (int i = 0; i < numberOfPoints; i++) { cell = subdivTree->search(lineSegments.col(i), bary); // Cell found // Compute a unique triplet (cell_id, type_id, part_id) representing the cell if (cell != 0) { // Compute centroid Veci vId = cell->getCell(); Vec3 centroid = Eigen::Vector3d::Zero(); double scale = 1.0 / vId.rows(); for (int c = 0; c < vId.rows(); c++) centroid += scale * cell->getVertex(c); // Save results output(0, i) = cell->getIndex(); output(1, i) = cell->getCellList()->getType(); output(2, i) = object->getPartByName(cell->getCellList()->getPartName())->getId(); output(3, i) = centroid(0); output(4, i) = centroid(1); output(5, i) = centroid(2); } else { // Convention: Set result to (-1,-1,-1,0,0,0,0) if result is empty output(0, i) = -1; output(1, i) = -1; output(2, i) = -1; output(3, i) = 0.0; output(4, i) = 0.0; output(5, i) = 0.0; } } MexTools::mexAllocateAndCopyMatrix(output, plhs, 0); } else { Eigen::MatrixXd output(3, numberOfPoints); EnsightCellIdentifier* cell; // Run subdiv tree search for each point for (int i = 0; i < numberOfPoints; i++) { cell = subdivTree->search(lineSegments.col(i), bary); // Cell found // Compute a unique triplet (cell_id, type_id, part_id) representing the cell if (cell != 0) { // Save results output(0, i) = cell->getIndex(); output(1, i) = cell->getCellList()->getType(); output(2, i) = object->getPartByName(cell->getCellList()->getPartName())->getId(); } else { // Convention: Set result to (-1,-1,-1) if result is empty output(0, i) = -1; output(1, i) = -1; output(2, i) = -1; } } MexTools::mexAllocateAndCopyMatrix(output, plhs, 0); } }
34.468722
110
0.603113
ITWM-TVFS
3e47e9ff77e151fd06aa6577e6ef145518fdbdee
3,696
cpp
C++
cpp/fft.cpp
petuhovskiy/Templates-CP
7419d5b5c6a92a98ba4d93525f6db22b7c3afa9e
[ "MIT" ]
8
2016-06-05T19:19:27.000Z
2019-05-14T10:33:37.000Z
cpp/fft.cpp
petuhovskiy/Templates-CP
7419d5b5c6a92a98ba4d93525f6db22b7c3afa9e
[ "MIT" ]
2
2017-02-21T12:38:27.000Z
2018-01-28T20:05:00.000Z
cpp/fft.cpp
petuhovskiy/Templates-CP
7419d5b5c6a92a98ba4d93525f6db22b7c3afa9e
[ "MIT" ]
6
2015-12-26T21:12:17.000Z
2022-03-26T21:40:17.000Z
namespace fft { inline uint8_t countBin(uint32_t x) { for (uint8_t i = 0; i != 32; ++i) { if (x & 1) { return i; } x >>= 1; } return 32; } inline uint32_t reverse(uint32_t x) { uint32_t res = 0; for (uint8_t i = 0; i != 32; ++i) { res <<= 1; res |= x & 1; x >>= 1; } return res; } inline uint32_t highestBit(uint32_t x) { if (x == 0) { return 0; } uint32_t cnt = 0; while (x != 0) { cnt++; x >>= 1; } x = 1; return x << (--cnt); } template <typename T> void fft(std::vector<T>& a, std::vector<T>& b, bool invert) { const T PI = acos(-1); uint32_t n = a.size(); uint32_t shift = 32 - countBin(n); for (uint32_t i = 1; i < n; ++i) { uint32_t j = reverse(i << shift); if (i < j) { std::swap(a[i], a[j]); std::swap(b[i], b[j]); } } for (uint32_t len = 2; len <= n; len <<= 1) { uint32_t halfLen = len >> 1; T angle = 2 * PI / len * (invert ? -1 : 1); T wLenA = cos(angle); T wLenB = sin(angle); for (uint32_t i = 0; i < n; i += len) { T wA = 1; T wB = 0; for (uint32_t j = 0; j != halfLen; ++j) { T uA = a[i + j]; T uB = b[i + j]; T vA = a[i + j + halfLen] * wA - b[i + j + halfLen] * wB; T vB = a[i + j + halfLen] * wB + b[i + j + halfLen] * wA; a[i + j] = uA + vA; b[i + j] = uB + vB; a[i + j + halfLen] = uA - vA; b[i + j + halfLen] = uB - vB; T nextWA = wA * wLenA - wB * wLenB; wB = wA * wLenB + wB * wLenA; wA = nextWA; } } } if (invert) { for (uint32_t i = 0; i != n; ++i) { a[i] /= n; b[i] /= n; } } } template <typename T = uint32_t, typename F = double, T Base = T(-1)> std::vector<T> multiply(const std::vector<T>& a, const std::vector<T>& b) { uint32_t resultSize = highestBit(std::max(a.size(), b.size()) - 1) << 2; resultSize = std::max(resultSize, 2u); std::vector<F> aReal(resultSize); std::vector<F> aImaginary(resultSize); std::vector<F> bReal(resultSize); std::vector<F> bImaginary(resultSize); for (size_t i = 0; i != a.size(); ++i) { aReal[i] = a[i]; } for (size_t i = 0; i != b.size(); ++i) { bReal[i] = b[i]; } fft(aReal, aImaginary, false); fft(bReal, bImaginary, false); for (size_t i = 0; i != resultSize; ++i) { F real = aReal[i] * bReal[i] - aImaginary[i] * bImaginary[i]; aImaginary[i] = aImaginary[i] * bReal[i] + bImaginary[i] * aReal[i]; aReal[i] = real; } fft(aReal, aImaginary, true); std::vector<T> result(resultSize); if (Base != T(-1)) { T carry = 0; for (size_t i = 0; i != resultSize; ++i) { carry += round(aReal[i]); result[i] = carry % Base; carry /= Base; } } else { for (size_t i = 0; i != resultSize; ++i) { result[i] = round(aReal[i]); } } return result; } };
30.04878
80
0.381494
petuhovskiy
3e4e687a1425f6f2db6b21e8297a403d0240159f
446
cpp
C++
SimulationTest/common/NewtonFirstLawTestHelper.cpp
KevinMcGin/Simulation
f1dbed05d6024274f6a69e0679f529feaae1e26e
[ "MIT" ]
4
2021-12-11T17:59:07.000Z
2021-12-24T11:08:55.000Z
SimulationTest/common/NewtonFirstLawTestHelper.cpp
KevinMcGin/Simulation
f1dbed05d6024274f6a69e0679f529feaae1e26e
[ "MIT" ]
121
2021-12-11T09:20:47.000Z
2022-03-13T18:36:48.000Z
SimulationTest/common/NewtonFirstLawTestHelper.cpp
KevinMcGin/Simulation
f1dbed05d6024274f6a69e0679f529feaae1e26e
[ "MIT" ]
null
null
null
#include "NewtonFirstLawTestHelper.h" std::vector<Particle*> NewtonFirstLawTestHelper::getParticleMove() { std::vector<Particle*> particles = { new ParticleSimple(1,1,{0,0,0},{1,-1,0}) }; return particles; } void NewtonFirstLawTestHelper::testParticleMove(std::vector<Particle*> particles) { Vector3D<float> positions = particles.front()->position; EXPECT_EQ(1, positions.x); EXPECT_EQ(-1, positions.y); EXPECT_EQ(0, positions.z); }
34.307692
84
0.735426
KevinMcGin
3e4fcdaad5cf05f8478acf2874113fd19d7e8798
392
hpp
C++
Sniper.hpp
or2209/wargame
e239c991c9f5f05fe571de41057f08ea10e8037e
[ "MIT" ]
null
null
null
Sniper.hpp
or2209/wargame
e239c991c9f5f05fe571de41057f08ea10e8037e
[ "MIT" ]
null
null
null
Sniper.hpp
or2209/wargame
e239c991c9f5f05fe571de41057f08ea10e8037e
[ "MIT" ]
null
null
null
// // Created by netanel on 25/05/2020. // #ifndef WARGAME_SNIPER_HPP #define WARGAME_SNIPER_HPP #include "Soldier.hpp" #include <iostream> #include <vector> using namespace std; class Sniper:public Soldier{ public: Sniper(int num_p):Soldier(100,50,num_p,100){ } void Fight(vector<vector<Soldier *>> &board, pair<int, int> location) override; }; #endif //WARGAME_SNIPER_HPP
18.666667
84
0.719388
or2209
3e517e031dfa940820372c6d37ed662197954234
1,189
cpp
C++
ex00/src/main.cpp
42cursus-youkim/-Rank04-CPP-Module02
f83b37150a4fda6130835b5a50291ed4ab867ebe
[ "MIT" ]
null
null
null
ex00/src/main.cpp
42cursus-youkim/-Rank04-CPP-Module02
f83b37150a4fda6130835b5a50291ed4ab867ebe
[ "MIT" ]
null
null
null
ex00/src/main.cpp
42cursus-youkim/-Rank04-CPP-Module02
f83b37150a4fda6130835b5a50291ed4ab867ebe
[ "MIT" ]
null
null
null
#include <iostream> #include "Fixed.hpp" #include "test.hpp" void testDefault() { test::header("Mandatory"); Fixed a; Fixed b(a); Fixed c; c = b; std::cout << a.getRawBits() << std::endl; std::cout << b.getRawBits() << std::endl; std::cout << c.getRawBits() << std::endl; } void testCustom() { test::header("Custom"); { test::subject("Default Constructor value is 0"); TEST_EXPECT(Fixed().getRawBits() == 0); } { test::subject("Copy Constructor Works (is deep copied)"); Fixed* a = new Fixed; a->setRawBits(42); int temp_a_rawbits = a->getRawBits(); Fixed b(*a); // construct a new Fixed with the value of a delete a; // b should have been deep copied TEST_EXPECT(b.getRawBits() == temp_a_rawbits); } { test::subject("Copy Assignment Works"); Fixed a; a.setRawBits(42); Fixed b; b = a; TEST_EXPECT(b.getRawBits() == a.getRawBits()); } { test::subject("Getter and Setter Works"); Fixed a; a.setRawBits(42); TEST_EXPECT(a.getRawBits() == 42); a.setRawBits(12); TEST_EXPECT(a.getRawBits() == 12); } } int main(void) { testDefault(); testCustom(); return 0; }
21.618182
62
0.600505
42cursus-youkim
3e5224055b66f6e922cc89d62d67211ce2b01efa
159
cc
C++
Tests/CentralHelix_unit.cc
orionning676/KinKal
689ec932155b7fe31d46c398bcb78bcac93581d7
[ "Apache-1.1" ]
2
2020-04-21T18:24:55.000Z
2020-09-24T19:01:47.000Z
Tests/CentralHelix_unit.cc
orionning676/KinKal
689ec932155b7fe31d46c398bcb78bcac93581d7
[ "Apache-1.1" ]
45
2020-03-16T18:27:59.000Z
2022-01-13T05:18:35.000Z
Tests/CentralHelix_unit.cc
orionning676/KinKal
689ec932155b7fe31d46c398bcb78bcac93581d7
[ "Apache-1.1" ]
15
2020-02-21T01:10:49.000Z
2022-03-24T12:13:35.000Z
#include "KinKal/Trajectory/CentralHelix.hh" #include "KinKal/Tests/Trajectory.hh" int main(int argc, char **argv) { return test<CentralHelix>(argc,argv); }
26.5
44
0.748428
orionning676
3e54464aac14107f9ec43a946ac0a4d9f1e90c5a
5,175
cpp
C++
src/src/symbolizer_p.cpp
degiz/sldparser
d11a40aa58f2f1bc8f439c5888645ba637a30a28
[ "MIT" ]
1
2021-01-25T08:41:59.000Z
2021-01-25T08:41:59.000Z
src/src/symbolizer_p.cpp
degiz/sldparser
d11a40aa58f2f1bc8f439c5888645ba637a30a28
[ "MIT" ]
null
null
null
src/src/symbolizer_p.cpp
degiz/sldparser
d11a40aa58f2f1bc8f439c5888645ba637a30a28
[ "MIT" ]
null
null
null
#include "symbolizer_p.h" namespace SldParser { std::vector<std::string> SymbolizerPrivate::_symbolizerTypes = { "PolygonSymbolizer", "LineSymbolizer", "PointSymbolizer", "TextSymbolizer", "RasterSymbolizer" }; SymbolizerPrivate::SymbolizerPrivate(XmlIterator iterator) : SLDNode(iterator) { _parseNode(); } SymbolizerPrivate::~SymbolizerPrivate() { } bool SymbolizerPrivate::isSymbolizer(std::string nodeName) { return std::find(_symbolizerTypes.begin(), _symbolizerTypes.end(), nodeName) != _symbolizerTypes.end(); } SymbolizerTypes SymbolizerPrivate::type() const { return _type; } std::string SymbolizerPrivate::color() const { return _color; } std::string SymbolizerPrivate::wellKnownName() const { return _wellKnownName; } double SymbolizerPrivate::opacity() const { return _opacity; } double SymbolizerPrivate::width() const { return _width; } std::string SymbolizerPrivate::linecap() const { return _linecap; } std::string SymbolizerPrivate::linejoin() const { return _linejoin; } double SymbolizerPrivate::dashoffset() const { return _dashoffset; } unsigned int SymbolizerPrivate::size() const { return _size; } unsigned int SymbolizerPrivate::rotation() const { return _rotation; } void SymbolizerPrivate::_parseNode() { if (_nodeName == "PolygonSymbolizer") { _type = SymbolizerTypes::PolygonSymbolizer; _parsePolygon(); } else if (_nodeName == "PointSymbolizer") { _type = SymbolizerTypes::PointSymbolizer; _parsePoint(); } else if (_nodeName == "TextSymbolizer") { _type = SymbolizerTypes::TextSymbolizer; _parseText(); } else if (_nodeName == "RasterSymbolizer") { _type = SymbolizerTypes::RasterSymbolizer; _parseRaster(); } else if (_nodeName == "LineSymbolizer") { _type = SymbolizerTypes::LineSymbolizer; _parseLine(); } } void SymbolizerPrivate::_parsePolygon() { while (_iterator.moveToNextNode()) { if (_iterator.name() == "Fill") { CssCollection css(_iterator); _fill = css; } else if (_iterator.name() == "Stroke") { CssCollection css(_iterator); _stroke = css; } } _prepareStroke(); _prepareFill(); } void SymbolizerPrivate::_parseLine() { while (_iterator.moveToNextNode()) { if (_iterator.name() == "Stroke") { CssCollection css(_iterator); _stroke = css; } } _prepareStroke(); } void SymbolizerPrivate::_parsePoint() { while (_iterator.moveToNextNode()) { if (_iterator.name() == "Graphic") { XmlIterator it(_iterator); it.moveToChildNode(); while (it.moveToNextNode()) { if (it.name() == "Mark") { Mark mark(it); _wellKnownName = mark.name(); _fill = mark.fill(); _mark = mark; } else if (it.name() == "Rotation") { _rotation = Variant(it.value()).asUInt(); } else if (it.name() == "Size") { _size = Variant(it.value()).asUInt(); } } //CssCollection css(_iterator); //_graphic = css; } } _prepareFill(); } void SymbolizerPrivate::_parseText() { } void SymbolizerPrivate::_parseRaster() { } void SymbolizerPrivate::_prepareStroke() { for (size_t i = 0; i < _stroke.cssElements().size(); i++) { if (_stroke.cssElements()[i].name() == "stroke") { _color = _stroke.cssElements()[i].value().asString(); } else if (_stroke.cssElements()[i].name() == "stroke-width") { _width = _stroke.cssElements()[i].value().asDouble(); } else if (_stroke.cssElements()[i].name() == "stroke-linecap") { _linecap = _stroke.cssElements()[i].value().asString(); } else if (_stroke.cssElements()[i].name() == "stroke-linejoin") { _linejoin = _stroke.cssElements()[i].value().asString(); } else if (_stroke.cssElements()[i].name() == "stroke-dashoffset") { _dashoffset = _stroke.cssElements()[i].value().asDouble(); } else if (_stroke.cssElements()[i].name() == "stroke-opacity") { _opacity = _stroke.cssElements()[i].value().asDouble(); } } } void SymbolizerPrivate::_prepareFill() { for (size_t i = 0; i < _fill.cssElements().size(); i++) { if (_fill.cssElements()[i].name() == "fill") { _color = _fill.cssElements()[i].value().asString(); } else if (_fill.cssElements()[i].name() == "fill-opacity") { _opacity = _fill.cssElements()[i].value().asDouble(); } } } }
23.630137
107
0.548213
degiz
3e54bed01516fd860fb7aca07dfd6088d9de39d5
40,525
cpp
C++
src/game_api/script/usertypes/entities_monsters_lua.cpp
iojon/overlunky
096902bf8f0de28522ab140d900d64354ce536ac
[ "MIT" ]
null
null
null
src/game_api/script/usertypes/entities_monsters_lua.cpp
iojon/overlunky
096902bf8f0de28522ab140d900d64354ce536ac
[ "MIT" ]
null
null
null
src/game_api/script/usertypes/entities_monsters_lua.cpp
iojon/overlunky
096902bf8f0de28522ab140d900d64354ce536ac
[ "MIT" ]
1
2020-11-14T14:45:16.000Z
2020-11-14T14:45:16.000Z
#include "entities_monsters_lua.hpp" #include "entities_monsters.hpp" #include "entity.hpp" #include <sol/sol.hpp> namespace NEntitiesMonsters { void register_usertypes(sol::state& lua) { lua["Entity"]["as_monster"] = &Entity::as<Monster>; lua["Entity"]["as_roomowner"] = &Entity::as<RoomOwner>; lua["Entity"]["as_walkingmonster"] = &Entity::as<WalkingMonster>; lua["Entity"]["as_npc"] = &Entity::as<NPC>; lua["Entity"]["as_ghost"] = &Entity::as<Ghost>; lua["Entity"]["as_bat"] = &Entity::as<Bat>; lua["Entity"]["as_jiangshi"] = &Entity::as<Jiangshi>; lua["Entity"]["as_monkey"] = &Entity::as<Monkey>; lua["Entity"]["as_goldmonkey"] = &Entity::as<GoldMonkey>; lua["Entity"]["as_mole"] = &Entity::as<Mole>; lua["Entity"]["as_spider"] = &Entity::as<Spider>; lua["Entity"]["as_hangspider"] = &Entity::as<HangSpider>; lua["Entity"]["as_shopkeeper"] = &Entity::as<Shopkeeper>; lua["Entity"]["as_yang"] = &Entity::as<Yang>; lua["Entity"]["as_tun"] = &Entity::as<Tun>; lua["Entity"]["as_pet"] = &Entity::as<Pet>; lua["Entity"]["as_caveman"] = &Entity::as<Caveman>; lua["Entity"]["as_cavemanshopkeeper"] = &Entity::as<CavemanShopkeeper>; lua["Entity"]["as_hornedlizard"] = &Entity::as<HornedLizard>; lua["Entity"]["as_mosquito"] = &Entity::as<Mosquito>; lua["Entity"]["as_mantrap"] = &Entity::as<Mantrap>; lua["Entity"]["as_skeleton"] = &Entity::as<Skeleton>; lua["Entity"]["as_scarab"] = &Entity::as<Scarab>; lua["Entity"]["as_imp"] = &Entity::as<Imp>; lua["Entity"]["as_lavamander"] = &Entity::as<Lavamander>; lua["Entity"]["as_firebug"] = &Entity::as<Firebug>; lua["Entity"]["as_firebugunchained"] = &Entity::as<FirebugUnchained>; lua["Entity"]["as_robot"] = &Entity::as<Robot>; lua["Entity"]["as_quillback"] = &Entity::as<Quillback>; lua["Entity"]["as_leprechaun"] = &Entity::as<Leprechaun>; lua["Entity"]["as_crocman"] = &Entity::as<Crocman>; lua["Entity"]["as_mummy"] = &Entity::as<Mummy>; lua["Entity"]["as_vanhorsing"] = &Entity::as<VanHorsing>; lua["Entity"]["as_witchdoctor"] = &Entity::as<WitchDoctor>; lua["Entity"]["as_witchdoctorskull"] = &Entity::as<WitchDoctorSkull>; lua["Entity"]["as_forestsister"] = &Entity::as<ForestSister>; lua["Entity"]["as_vampire"] = &Entity::as<Vampire>; lua["Entity"]["as_vlad"] = &Entity::as<Vlad>; lua["Entity"]["as_waddler"] = &Entity::as<Waddler>; lua["Entity"]["as_octopus"] = &Entity::as<Octopus>; lua["Entity"]["as_bodyguard"] = &Entity::as<Bodyguard>; lua["Entity"]["as_fish"] = &Entity::as<Fish>; lua["Entity"]["as_giantfish"] = &Entity::as<GiantFish>; lua["Entity"]["as_crabman"] = &Entity::as<Crabman>; lua["Entity"]["as_kingu"] = &Entity::as<Kingu>; lua["Entity"]["as_anubis"] = &Entity::as<Anubis>; lua["Entity"]["as_cobra"] = &Entity::as<Cobra>; lua["Entity"]["as_catmummy"] = &Entity::as<CatMummy>; lua["Entity"]["as_sorceress"] = &Entity::as<Sorceress>; lua["Entity"]["as_magmaman"] = &Entity::as<MagmaMan>; lua["Entity"]["as_bee"] = &Entity::as<Bee>; lua["Entity"]["as_ammit"] = &Entity::as<Ammit>; lua["Entity"]["as_apeppart"] = &Entity::as<ApepPart>; lua["Entity"]["as_apephead"] = &Entity::as<ApepHead>; lua["Entity"]["as_osirishead"] = &Entity::as<OsirisHead>; lua["Entity"]["as_osirishand"] = &Entity::as<OsirisHand>; lua["Entity"]["as_alien"] = &Entity::as<Alien>; lua["Entity"]["as_ufo"] = &Entity::as<UFO>; lua["Entity"]["as_lahamu"] = &Entity::as<Lahamu>; lua["Entity"]["as_yetiqueen"] = &Entity::as<YetiQueen>; lua["Entity"]["as_yetiking"] = &Entity::as<YetiKing>; lua["Entity"]["as_lamassu"] = &Entity::as<Lamassu>; lua["Entity"]["as_olmite"] = &Entity::as<Olmite>; lua["Entity"]["as_tiamat"] = &Entity::as<Tiamat>; lua["Entity"]["as_giantfrog"] = &Entity::as<GiantFrog>; lua["Entity"]["as_frog"] = &Entity::as<Frog>; lua["Entity"]["as_firefrog"] = &Entity::as<FireFrog>; lua["Entity"]["as_grub"] = &Entity::as<Grub>; lua["Entity"]["as_tadpole"] = &Entity::as<Tadpole>; lua["Entity"]["as_giantfly"] = &Entity::as<GiantFly>; lua["Entity"]["as_ghist"] = &Entity::as<Ghist>; lua["Entity"]["as_jumpdog"] = &Entity::as<JumpDog>; lua["Entity"]["as_eggplantminister"] = &Entity::as<EggplantMinister>; lua["Entity"]["as_yama"] = &Entity::as<Yama>; lua["Entity"]["as_hundun"] = &Entity::as<Hundun>; lua["Entity"]["as_hundunhead"] = &Entity::as<HundunHead>; lua["Entity"]["as_megajellyfish"] = &Entity::as<MegaJellyfish>; lua["Entity"]["as_scorpion"] = &Entity::as<Scorpion>; lua["Entity"]["as_hermitcrab"] = &Entity::as<Hermitcrab>; lua["Entity"]["as_necromancer"] = &Entity::as<Necromancer>; lua["Entity"]["as_protoshopkeeper"] = &Entity::as<ProtoShopkeeper>; lua["Entity"]["as_beg"] = &Entity::as<Beg>; lua["Entity"]["as_terra"] = &Entity::as<Terra>; lua["Entity"]["as_critter"] = &Entity::as<Critter>; lua["Entity"]["as_critterbeetle"] = &Entity::as<CritterBeetle>; lua["Entity"]["as_crittercrab"] = &Entity::as<CritterCrab>; lua["Entity"]["as_critterbutterfly"] = &Entity::as<CritterButterfly>; lua["Entity"]["as_critterlocust"] = &Entity::as<CritterLocust>; lua["Entity"]["as_crittersnail"] = &Entity::as<CritterSnail>; lua["Entity"]["as_critterfish"] = &Entity::as<CritterFish>; lua["Entity"]["as_critterpenguin"] = &Entity::as<CritterPenguin>; lua["Entity"]["as_critterfirefly"] = &Entity::as<CritterFirefly>; lua["Entity"]["as_critterdrone"] = &Entity::as<CritterDrone>; lua["Entity"]["as_critterslime"] = &Entity::as<CritterSlime>; lua.new_usertype<Monster>( "Monster", "chased_target_uid", &Monster::chased_target_uid, "target_selection_timer", &Monster::target_selection_timer, sol::base_classes, sol::bases<Entity, Movable, PowerupCapable>()); lua.new_usertype<RoomOwner>( "RoomOwner", "room_index", &RoomOwner::room_index, "climb_y_direction", &RoomOwner::climb_y_direction, "ai_state", &RoomOwner::ai_state, "patrol_timer", &RoomOwner::patrol_timer, "lose_interest_timer", &RoomOwner::lose_interest_timer, "countdown_timer", &RoomOwner::countdown_timer, "is_patrolling", &RoomOwner::is_patrolling, "aggro_trigger", &RoomOwner::aggro_trigger, "was_hurt", &RoomOwner::was_hurt, sol::base_classes, sol::bases<Entity, Movable, PowerupCapable, Monster>()); lua.new_usertype<WalkingMonster>( "WalkingMonster", "chatting_to_uid", &WalkingMonster::chatting_to_uid, "walk_pause_timer", &WalkingMonster::walk_pause_timer, "cooldown_timer", &WalkingMonster::cooldown_timer, sol::base_classes, sol::bases<Entity, Movable, PowerupCapable, Monster>()); lua.new_usertype<NPC>( "NPC", "climb_direction", &NPC::climb_direction, "target_in_sight_timer", &NPC::target_in_sight_timer, "ai_state", &NPC::ai_state, "aggro", &NPC::aggro, sol::base_classes, sol::bases<Entity, Movable, PowerupCapable, Monster>()); lua.create_named_table("GHOST_BEHAVIOR", "SAD", GHOST_BEHAVIOR::SAD, "MEDIUM_SAD", GHOST_BEHAVIOR::MEDIUM_SAD, "MEDIUM_HAPPY", GHOST_BEHAVIOR::MEDIUM_HAPPY, "SMALL_ANGRY", GHOST_BEHAVIOR::SMALL_ANGRY, "SMALL_SURPRISED", GHOST_BEHAVIOR::SMALL_SURPRISED, "SMALL_SAD", GHOST_BEHAVIOR::SMALL_SAD, "SMALL_HAPPY", GHOST_BEHAVIOR::SMALL_HAPPY); lua.new_usertype<Ghost>( "Ghost", "split_timer", &Ghost::split_timer, "velocity_multiplier", &Ghost::velocity_multiplier, "ghost_behaviour", &Ghost::ghost_behaviour, "emitted_light", &Ghost::emitted_light, "linked_ghost", &Ghost::linked_ghost, sol::base_classes, sol::bases<Entity, Movable, PowerupCapable, Monster>()); lua.new_usertype<Bat>( "Bat", "spawn_x", &Bat::spawn_x, "spawn_y", &Bat::spawn_y, sol::base_classes, sol::bases<Entity, Movable, PowerupCapable, Monster>()); lua.new_usertype<Jiangshi>( "Jiangshi", "wait_timer", &Jiangshi::wait_timer, "jump_counter", &Jiangshi::jump_counter, "on_ceiling", &Jiangshi::on_ceiling, sol::base_classes, sol::bases<Entity, Movable, PowerupCapable, Monster>()); lua.new_usertype<Monkey>( "Monkey", "jump_timer", &Monkey::jump_timer, "on_vine", &Monkey::on_vine, sol::base_classes, sol::bases<Entity, Movable, PowerupCapable, Monster>()); lua.new_usertype<GoldMonkey>( "GoldMonkey", "jump_timer", &GoldMonkey::jump_timer, "poop_timer", &GoldMonkey::poop_timer, "poop_count", &GoldMonkey::poop_count, sol::base_classes, sol::bases<Entity, Movable, PowerupCapable, Monster>()); lua.new_usertype<Mole>( "Mole", "burrowing_particle", &Mole::burrowing_particle, "burrow_dir_x", &Mole::burrow_dir_x, "burrow_dir_y", &Mole::burrow_dir_y, "burrowing_in_uid", &Mole::burrowing_in_uid, "counter_burrowing", &Mole::counter_burrowing, "counter_nonburrowing", &Mole::counter_nonburrowing, "countdown_for_appearing", &Mole::countdown_for_appearing, "digging_state", &Mole::digging_state, sol::base_classes, sol::bases<Entity, Movable, PowerupCapable, Monster>()); lua.new_usertype<Spider>( "Spider", "ceiling_pos_x", &Spider::ceiling_pos_x, "ceiling_pos_y", &Spider::ceiling_pos_y, "jump_timer", &Spider::jump_timer, "trigger_distance", &Spider::trigger_distance, sol::base_classes, sol::bases<Entity, Movable, PowerupCapable, Monster>()); lua.new_usertype<HangSpider>( "HangSpider", "dangle_jump_timer", &HangSpider::dangle_jump_timer, "ceiling_pos_x", &HangSpider::ceiling_pos_x, "ceiling_pos_y", &HangSpider::ceiling_pos_y, sol::base_classes, sol::bases<Entity, Movable, PowerupCapable, Monster>()); lua.new_usertype<Shopkeeper>( "Shopkeeper", "name", &Shopkeeper::name, "shotgun_attack_delay", &Shopkeeper::shotgun_attack_delay, "shop_owner", &Shopkeeper::shop_owner, sol::base_classes, sol::bases<Entity, Movable, PowerupCapable, Monster, RoomOwner>()); lua.new_usertype<Yang>( "Yang", "first_message_shown", &Yang::first_message_shown, "quest_incomplete", &Yang::quest_incomplete, "special_message_shown", &Yang::special_message_shown, sol::base_classes, sol::bases<Entity, Movable, PowerupCapable, Monster, RoomOwner>()); lua.new_usertype<Tun>( "Tun", "arrows_left", &Tun::arrows_left, "reload_timer", &Tun::reload_timer, "challenge_fee_paid", &Tun::challenge_fee_paid, "congrats_challenge", &Tun::congrats_challenge, "murdered", &Tun::murdered, "shop_entered", &Tun::shop_entered, "tiamat_encounter", &Tun::tiamat_encounter, sol::base_classes, sol::bases<Entity, Movable, PowerupCapable, Monster, RoomOwner>()); lua.new_usertype<Pet>( "Pet", "fx_button", &Pet::fx_button, "petting_by_uid", &Pet::petting_by_uid, "yell_counter", &Pet::yell_counter, "func_timer", &Pet::func_timer, "active_state", &Pet::active_state, sol::base_classes, sol::bases<Entity, Movable, PowerupCapable, Monster>()); lua.new_usertype<Caveman>( "Caveman", "wake_up_timer", &Caveman::wake_up_timer, "can_pick_up_timer", &Caveman::can_pick_up_timer, "aggro_timer", &Caveman::aggro_timer, sol::base_classes, sol::bases<Entity, Movable, PowerupCapable, Monster, WalkingMonster>()); lua.new_usertype<CavemanShopkeeper>( "CavemanShopkeeper", "tripping", &CavemanShopkeeper::tripping, "shop_entered", &CavemanShopkeeper::shop_entered, sol::base_classes, sol::bases<Entity, Movable, PowerupCapable, Monster, WalkingMonster>()); lua.new_usertype<HornedLizard>( "HornedLizard", "eaten_uid", &HornedLizard::eaten_uid, "walk_pause_timer", &HornedLizard::walk_pause_timer, "attack_cooldown_timer", &HornedLizard::attack_cooldown_timer, "blood_squirt_timer", &HornedLizard::blood_squirt_timer, "particle", &HornedLizard::particle, sol::base_classes, sol::bases<Entity, Movable, PowerupCapable, Monster>()); lua.new_usertype<Mosquito>( "Mosquito", "direction_x", &Mosquito::direction_x, "direction_y", &Mosquito::direction_y, "stuck_rel_pos_x", &Mosquito::stuck_rel_pos_x, "stuck_rel_pos_y", &Mosquito::stuck_rel_pos_y, "timer", &Mosquito::timer, sol::base_classes, sol::bases<Entity, Movable, PowerupCapable, Monster>()); lua.new_usertype<Mantrap>( "Mantrap", "walk_pause_timer", &Mantrap::walk_pause_timer, "eaten_uid", &Mantrap::eaten_uid, sol::base_classes, sol::bases<Entity, Movable, PowerupCapable, Monster>()); lua.new_usertype<Skeleton>( "Skeleton", "explosion_timer", &Skeleton::explosion_timer, sol::base_classes, sol::bases<Entity, Movable, PowerupCapable, Monster>()); lua.new_usertype<Scarab>( "Scarab", "emitted_light", &Scarab::emitted_light, "timer", &Scarab::timer, sol::base_classes, sol::bases<Entity, Movable, PowerupCapable, Monster>()); lua.new_usertype<Imp>( "Imp", "carrying_uid", &Imp::carrying_uid, "patrol_y_level", &Imp::patrol_y_level, sol::base_classes, sol::bases<Entity, Movable, PowerupCapable, Monster>()); lua.new_usertype<Lavamander>( "Lavamander", "emitted_light", &Lavamander::emitted_light, "shoot_lava_timer", &Lavamander::shoot_lava_timer, "jump_pause_timer", &Lavamander::jump_pause_timer, "lava_detection_timer", &Lavamander::lava_detection_timer, "is_hot", &Lavamander::is_hot, "player_detect_state", &Lavamander::player_detect_state, sol::base_classes, sol::bases<Entity, Movable, PowerupCapable, Monster>()); lua.new_usertype<Firebug>( "Firebug", "fire_timer", &Firebug::fire_timer, "going_up", &Firebug::going_up, "detached_from_chain", &Firebug::detached_from_chain, sol::base_classes, sol::bases<Entity, Movable, PowerupCapable, Monster>()); lua.new_usertype<FirebugUnchained>( "FirebugUnchained", "max_flight_height", &FirebugUnchained::max_flight_height, "ai_timer", &FirebugUnchained::ai_timer, "walking_timer", &FirebugUnchained::walking_timer, sol::base_classes, sol::bases<Entity, Movable, PowerupCapable, Monster>()); lua.new_usertype<Robot>( "Robot", "emitted_light_explosion", &Robot::emitted_light_explosion, sol::base_classes, sol::bases<Entity, Movable, PowerupCapable, Monster, WalkingMonster>()); lua.new_usertype<Quillback>( "Quillback", "particle", &Quillback::particle, sol::base_classes, sol::bases<Entity, Movable, PowerupCapable, Monster, WalkingMonster>()); lua.new_usertype<Leprechaun>( "Leprechaun", "hump_timer", &Leprechaun::hump_timer, "target_in_sight_timer", &Leprechaun::target_in_sight_timer, "gold", &Leprechaun::gold, "timer_after_humping", &Leprechaun::timer_after_humping, sol::base_classes, sol::bases<Entity, Movable, PowerupCapable, Monster, WalkingMonster>()); lua.new_usertype<Crocman>( "Crocman", "teleport_cooldown", &Crocman::teleport_cooldown, sol::base_classes, sol::bases<Entity, Movable, PowerupCapable, Monster, WalkingMonster>()); lua.new_usertype<Mummy>( "Mummy", "walk_pause_timer", &Mummy::walk_pause_timer, sol::base_classes, sol::bases<Entity, Movable, PowerupCapable, Monster>()); lua.new_usertype<VanHorsing>( "VanHorsing", "show_text", &VanHorsing::show_text, sol::base_classes, sol::bases<Entity, Movable, PowerupCapable, Monster, NPC>()); lua.new_usertype<WitchDoctor>( "WitchDoctor", "skull_regen_timer", &WitchDoctor::skull_regen_timer, sol::base_classes, sol::bases<Entity, Movable, PowerupCapable, Monster, WalkingMonster>()); lua.new_usertype<WitchDoctorSkull>( "WitchDoctorSkull", "witch_doctor_uid", &WitchDoctorSkull::witch_doctor_uid, "emitted_light", &WitchDoctorSkull::emitted_light, "rotation_angle", &WitchDoctorSkull::rotation_angle, sol::base_classes, sol::bases<Entity, Movable, PowerupCapable, Monster>()); lua.new_usertype<ForestSister>( "ForestSister", "walk_pause_timer", &ForestSister::walk_pause_timer, sol::base_classes, sol::bases<Entity, Movable, PowerupCapable, Monster, NPC>()); lua.new_usertype<Vampire>( "Vampire", "jump_trigger_distance_x", &Vampire::jump_trigger_distance_x, "jump_trigger_distance_y", &Vampire::jump_trigger_distance_y, "sleep_pos_x", &Vampire::sleep_pos_x, "sleep_pos_y", &Vampire::sleep_pos_y, "walk_pause_timer", &Vampire::walk_pause_timer, sol::base_classes, sol::bases<Entity, Movable, PowerupCapable, Monster>()); lua.new_usertype<Vlad>( "Vlad", "teleport_timer", &Vlad::teleport_timer, "aggro", &Vlad::aggro, sol::base_classes, sol::bases<Entity, Movable, PowerupCapable, Monster, Vampire>()); lua.new_usertype<Waddler>( "Waddler", "player_detected", &Waddler::player_detected, "on_the_ground", &Waddler::on_the_ground, "air_timer", &Waddler::air_timer, sol::base_classes, sol::bases<Entity, Movable, PowerupCapable, Monster, RoomOwner>()); lua.new_usertype<Octopus>( "Octopus", sol::base_classes, sol::bases<Entity, Movable, PowerupCapable, Monster, WalkingMonster>()); lua.new_usertype<Bodyguard>( "Bodyguard", "position_state", &Bodyguard::position_state, "message_shown", &Bodyguard::message_shown, sol::base_classes, sol::bases<Entity, Movable, PowerupCapable, Monster, NPC>()); lua.new_usertype<Fish>( "Fish", "change_direction_timer", &Fish::change_direction_timer, sol::base_classes, sol::bases<Entity, Movable, PowerupCapable, Monster>()); lua.new_usertype<GiantFish>( "GiantFish", "change_direction_timer", &GiantFish::change_direction_timer, "lose_interest_timer", &GiantFish::lose_interest_timer, sol::base_classes, sol::bases<Entity, Movable, PowerupCapable, Monster>()); lua.new_usertype<Crabman>( "Crabman", "walk_pause_timer", &Crabman::walk_pause_timer, "invincibility_timer", &Crabman::invincibility_timer, "poison_attack_timer", &Crabman::poison_attack_timer, "attacking_claw_uid", &Crabman::attacking_claw_uid, "at_maximum_attack", &Crabman::at_maximum_attack, sol::base_classes, sol::bases<Entity, Movable, PowerupCapable, Monster>()); lua.new_usertype<Kingu>( "Kingu", "climb_direction_x", &Kingu::climb_direction_x, "climb_direction_y", &Kingu::climb_direction_y, "climb_pause_timer", &Kingu::climb_pause_timer, "shell_invincibility_timer", &Kingu::shell_invincibility_timer, "monster_spawn_timer", &Kingu::monster_spawn_timer, "initial_shell_health", &Kingu::initial_shell_health, "player_seen_by_kingu", &Kingu::player_seen_by_kingu, sol::base_classes, sol::bases<Entity, Movable, PowerupCapable, Monster>()); lua.new_usertype<Anubis>( "Anubis", "spawn_x", &Anubis::spawn_x, "spawn_y", &Anubis::spawn_y, "attack_proximity_y", &Anubis::attack_proximity_y, "attack_proximity_x", &Anubis::attack_proximity_x, "ai_timer", &Anubis::ai_timer, "next_attack_timer", &Anubis::next_attack_timer, "psychic_orbs_counter", &Anubis::psychic_orbs_counter, "awake", &Anubis::awake, sol::base_classes, sol::bases<Entity, Movable, PowerupCapable, Monster>()); lua.new_usertype<Cobra>( "Cobra", "spit_timer", &Cobra::spit_timer, sol::base_classes, sol::bases<Entity, Movable, PowerupCapable, Monster>()); lua.new_usertype<CatMummy>( "CatMummy", "ai_state", &CatMummy::ai_state, "attack_timer", &CatMummy::attack_timer, sol::base_classes, sol::bases<Entity, Movable, PowerupCapable, Monster>()); lua.new_usertype<Sorceress>( "Sorceress", "inbetween_attack_timer", &Sorceress::inbetween_attack_timer, "in_air_timer", &Sorceress::in_air_timer, "halo_emitted_light", &Sorceress::halo_emitted_light, "fx_entity", &Sorceress::fx_entity, "hover_timer", &Sorceress::hover_timer, sol::base_classes, sol::bases<Entity, Movable, PowerupCapable, Monster, WalkingMonster>()); lua.new_usertype<MagmaMan>( "MagmaMan", "emitted_light", &MagmaMan::emitted_light, "particle", &MagmaMan::particle, "jump_timer", &MagmaMan::jump_timer, "alive_timer", &MagmaMan::alive_timer, sol::base_classes, sol::bases<Entity, Movable, PowerupCapable, Monster>()); lua.new_usertype<Bee>( "Bee", "can_rest", &Bee::can_rest, "fly_hang_timer", &Bee::fly_hang_timer, "targeting_timer", &Bee::targeting_timer, "wobble_x", &Bee::wobble_x, "wobble_y", &Bee::wobble_y, sol::base_classes, sol::bases<Entity, Movable, PowerupCapable, Monster>()); lua.new_usertype<Ammit>( "Ammit", "walk_pause_timer", &Ammit::walk_pause_timer, "particle", &Ammit::particle, sol::base_classes, sol::bases<Entity, Movable, PowerupCapable, Monster>()); lua.new_usertype<ApepPart>( "ApepPart", "y_pos", &ApepPart::y_pos, "sine_angle", &ApepPart::sine_angle, "sync_timer", &ApepPart::sync_timer, sol::base_classes, sol::bases<Entity, Movable, PowerupCapable, Monster>()); lua.new_usertype<ApepHead>( "ApepHead", "distance_traveled", &ApepHead::distance_traveled, "tail_uid", &ApepHead::tail_uid, "fx_mouthpiece1_uid", &ApepHead::fx_mouthpiece1_uid, "fx_mouthpiece2_uid", &ApepHead::fx_mouthpiece2_uid, sol::base_classes, sol::bases<Entity, Movable, PowerupCapable, Monster, ApepPart>()); lua.new_usertype<OsirisHead>( "OsirisHead", "right_hand_uid", &OsirisHead::right_hand_uid, "left_hand_uid", &OsirisHead::left_hand_uid, "moving_left", &OsirisHead::moving_left, "targeting_timer", &OsirisHead::targeting_timer, "invincibility_timer", &OsirisHead::invincibility_timer, sol::base_classes, sol::bases<Entity, Movable, PowerupCapable, Monster>()); lua.new_usertype<OsirisHand>( "OsirisHand", "attack_cooldown_timer", &OsirisHand::attack_cooldown_timer, sol::base_classes, sol::bases<Entity, Movable, PowerupCapable, Monster>()); lua.new_usertype<Alien>( "Alien", "jump_timer", &Alien::jump_timer, sol::base_classes, sol::bases<Entity, Movable, PowerupCapable, Monster>()); lua.new_usertype<UFO>( "UFO", "patrol_distance", &UFO::patrol_distance, "attack_cooldown_timer", &UFO::attack_cooldown_timer, "is_falling", &UFO::is_falling, sol::base_classes, sol::bases<Entity, Movable, PowerupCapable, Monster>()); lua.new_usertype<Lahamu>( "Lahamu", "attack_cooldown_timer", &Lahamu::attack_cooldown_timer, sol::base_classes, sol::bases<Entity, Movable, PowerupCapable, Monster>()); lua.new_usertype<YetiQueen>( "YetiQueen", "walk_pause_timer", &YetiQueen::walk_pause_timer, sol::base_classes, sol::bases<Entity, Movable, PowerupCapable, Monster>()); lua.new_usertype<YetiKing>( "YetiKing", "walk_pause_timer", &YetiKing::walk_pause_timer, "emitted_light", &YetiKing::emitted_light, "particle_fog", &YetiKing::particle_fog, "particle_dust", &YetiKing::particle_dust, "particle_sparkles", &YetiKing::particle_sparkles, sol::base_classes, sol::bases<Entity, Movable, PowerupCapable, Monster>()); lua.new_usertype<Lamassu>( "Lamassu", "attack_effect_entity", &Lamassu::attack_effect_entity, "particle", &Lamassu::particle, "emitted_light", &Lamassu::emitted_light, "walk_pause_timer", &Lamassu::walk_pause_timer, "flight_timer", &Lamassu::flight_timer, "attack_timer", &Lamassu::attack_timer, "attack_angle", &Lamassu::attack_angle, sol::base_classes, sol::bases<Entity, Movable, PowerupCapable, Monster>()); lua.new_usertype<Olmite>( "Olmite", "armor_on", &Olmite::armor_on, "in_stack", &Olmite::in_stack, "in_stack2", &Olmite::in_stack2, "on_top_uid", &Olmite::on_top_uid, "y_offset", &Olmite::y_offset, "attack_cooldown_timer", &Olmite::attack_cooldown_timer, sol::base_classes, sol::bases<Entity, Movable, PowerupCapable, Monster, WalkingMonster>()); lua.new_usertype<Tiamat>( "Tiamat", "fx_tiamat_head", &Tiamat::fx_tiamat_head_uid, "fx_tiamat_arm_right1", &Tiamat::fx_tiamat_arm_right1_uid, "fx_tiamat_arm_right2", &Tiamat::fx_tiamat_arm_right2_uid, "frown_timer", &Tiamat::invincibility_timer, "damage_timer", &Tiamat::damage_timer, "attack_timer", &Tiamat::attack_timer, "tail_angle", &Tiamat::tail_angle, "tail_radian", &Tiamat::tail_radian, "tail_move_speed", &Tiamat::tail_move_speed, "right_arm_angle", &Tiamat::right_arm_angle, sol::base_classes, sol::bases<Entity, Movable, PowerupCapable, Monster>()); lua.new_usertype<GiantFrog>( "GiantFrog", "door_front_layer", &GiantFrog::door_front_layer, "door_back_layer", &GiantFrog::door_back_layer, "platform", &GiantFrog::platform, "attack_timer", &GiantFrog::attack_timer, "frogs_ejected_in_cycle", &GiantFrog::frogs_ejected_in_cycle, "invincibility_timer", &GiantFrog::invincibility_timer, "mouth_close_timer", &GiantFrog::mouth_close_timer, "mouth_open_trigger", &GiantFrog::mouth_open_trigger, sol::base_classes, sol::bases<Entity, Movable, PowerupCapable, Monster>()); lua.new_usertype<Frog>( "Frog", "grub_being_eaten_uid", &Frog::grub_being_eaten_uid, "jump_timer", &Frog::jump_timer, "pause", &Frog::pause, sol::base_classes, sol::bases<Entity, Movable, PowerupCapable, Monster>()); lua.new_usertype<FireFrog>( "FireFrog", sol::base_classes, sol::bases<Entity, Movable, PowerupCapable, Monster, Frog>()); lua.new_usertype<Grub>( "Grub", "rotation_delta", &Grub::rotation_delta, "drop", &Grub::drop, "looking_for_new_direction_timer", &Grub::looking_for_new_direction_timer, "walk_pause_timer", &Grub::walk_pause_timer, "turn_into_fly_timer", &Grub::turn_into_fly_timer, "particle", &Grub::particle, sol::base_classes, sol::bases<Entity, Movable, PowerupCapable, Monster>()); lua.new_usertype<Tadpole>( "Tadpole", "acceleration_timer", &Tadpole::acceleration_timer, "player_spotted", &Tadpole::player_spotted, sol::base_classes, sol::bases<Entity, Movable, PowerupCapable, Monster>()); lua.new_usertype<GiantFly>( "GiantFly", "head_entity", &GiantFly::head_entity, "particle", &GiantFly::particle, "sine_amplitude", &GiantFly::sine_amplitude, "sine_frequency", &GiantFly::sine_frequency, "delta_y_angle", &GiantFly::delta_y_angle, "sine_counter", &GiantFly::sine_counter, sol::base_classes, sol::bases<Entity, Movable, PowerupCapable, Monster>()); lua.new_usertype<Ghist>( "Ghist", "body_uid", &Ghist::body_uid, "idle_timer", &Ghist::idle_timer, "transparency", &Ghist::transparency, "fadeout", &Ghist::fadeout, sol::base_classes, sol::bases<Entity, Movable, PowerupCapable, Monster>()); lua.new_usertype<JumpDog>( "JumpDog", "walk_pause_timer", &JumpDog::walk_pause_timer, "squish_timer", &JumpDog::squish_timer, sol::base_classes, sol::bases<Entity, Movable, PowerupCapable, Monster>()); lua.new_usertype<EggplantMinister>( "EggplantMinister", "walk_pause_timer", &EggplantMinister::walk_pause_timer, "squish_timer", &EggplantMinister::squish_timer, sol::base_classes, sol::bases<Entity, Movable, PowerupCapable, Monster>()); lua.new_usertype<Yama>( "Yama", "message_shown", &Yama::message_shown, sol::base_classes, sol::bases<Entity, Movable, PowerupCapable, Monster>()); lua.new_usertype<Hundun>( "Hundun", "applied_hor_velocity", &Hundun::applied_hor_velocity, "applied_ver_velocity", &Hundun::applied_ver_velocity, "birdhead_entity_uid", &Hundun::birdhead_entity_uid, "snakehead_entity_uid", &Hundun::snakehead_entity_uid, "y_level", &Hundun::y_level, "bounce_timer", &Hundun::bounce_timer, "fireball_timer", &Hundun::fireball_timer, "birdhead_defeated", &Hundun::birdhead_defeated, "snakehead_defeated", &Hundun::snakehead_defeated, "hundun_flags", &Hundun::hundun_flags, sol::base_classes, sol::bases<Entity, Movable, PowerupCapable, Monster>()); lua.create_named_table("HUNDUNFLAGS", "WILLMOVELEFT", 1, "BIRDHEADEMERGED", 2, "SNAKEHEADEMERGED", 4, "TOPLEVELARENAREACHED", 8, "BIRDHEADSHOTLAST", 16); lua.new_usertype<HundunHead>( "HundunHead", "attack_position_x", &HundunHead::attack_position_x, "attack_position_y", &HundunHead::attack_position_y, "egg_crack_effect_uid", &HundunHead::egg_crack_effect_uid, "targeted_player_uid", &HundunHead::targeted_player_uid, "looking_for_target_timer", &HundunHead::looking_for_target_timer, "invincibility_timer", &HundunHead::invincibility_timer, sol::base_classes, sol::bases<Entity, Movable, PowerupCapable, Monster>()); lua.new_usertype<MegaJellyfish>( "MegaJellyfish", "flipper1", &MegaJellyfish::flipper1, "flipper2", &MegaJellyfish::flipper2, "orb_uid", &MegaJellyfish::orb_uid, "tail_bg_uid", &MegaJellyfish::tail_bg_uid, "applied_velocity", &MegaJellyfish::applied_velocity, "wagging_tail_counter", &MegaJellyfish::wagging_tail_counter, "flipper_distance", &MegaJellyfish::flipper_distance, "velocity_application_timer", &MegaJellyfish::velocity_application_timer, sol::base_classes, sol::bases<Entity, Movable, PowerupCapable, Monster>()); lua.new_usertype<Scorpion>( "Scorpion", "walk_pause_timer", &Scorpion::walk_pause_timer, "jump_cooldown_timer", &Scorpion::jump_cooldown_timer, sol::base_classes, sol::bases<Entity, Movable, PowerupCapable, Monster>()); lua.new_usertype<Hermitcrab>( "Hermitcrab", "carried_entity_type", &Hermitcrab::carried_entity_type, "carried_entity_uid", &Hermitcrab::carried_entity_uid, "walk_spit_timer", &Hermitcrab::walk_spit_timer, "is_active", &Hermitcrab::is_active, "is_inactive", &Hermitcrab::is_inactive, "spawn_new_carried_item", &Hermitcrab::spawn_new_carried_item, sol::base_classes, sol::bases<Entity, Movable, PowerupCapable, Monster>()); lua.new_usertype<Necromancer>( "Necromancer", "red_skeleton_spawn_x", &Necromancer::red_skeleton_spawn_x, "red_skeleton_spawn_y", &Necromancer::red_skeleton_spawn_y, "resurrection_uid", &Necromancer::resurrection_uid, "resurrection_timer", &Necromancer::resurrection_timer, sol::base_classes, sol::bases<Entity, Movable, PowerupCapable, Monster, WalkingMonster>()); lua.new_usertype<ProtoShopkeeper>( "ProtoShopkeeper", "movement_state", &ProtoShopkeeper::movement_state, "walk_pause_explode_timer", &ProtoShopkeeper::walk_pause_explode_timer, "walking_speed", &ProtoShopkeeper::walking_speed, sol::base_classes, sol::bases<Entity, Movable, PowerupCapable, Monster>()); lua.new_usertype<Beg>( "Beg", "walk_pause_timer", &Beg::walk_pause_timer, "disappear_timer", &Beg::disappear_timer, sol::base_classes, sol::bases<Entity, Movable, PowerupCapable, Monster, NPC>()); lua.new_usertype<Terra>( "Terra", "fx_button", &Terra::fx_button, "x_pos", &Terra::x_pos, "abuse_speechbubble_timer", &Terra::abuse_speechbubble_timer, sol::base_classes, sol::bases<Entity, Movable, PowerupCapable, Monster>()); lua.new_usertype<Critter>( "Critter", "last_picked_up_by_uid", &Critter::last_picked_up_by_uid, "holding_state", &Critter::holding_state, sol::base_classes, sol::bases<Entity, Movable, PowerupCapable, Monster>()); lua.new_usertype<CritterBeetle>( "CritterBeetle", "pause", &CritterBeetle::pause, sol::base_classes, sol::bases<Entity, Movable, PowerupCapable, Monster, Critter>()); lua.new_usertype<CritterCrab>( "CritterCrab", "walk_pause_timer", &CritterCrab::walk_pause_timer, "walking_left", &CritterCrab::walking_left, sol::base_classes, sol::bases<Entity, Movable, PowerupCapable, Monster, Critter>()); lua.new_usertype<CritterButterfly>( "CritterButterfly", "change_direction_timer", &CritterButterfly::change_direction_timer, "vertical_flight_direction", &CritterButterfly::vertical_flight_direction, sol::base_classes, sol::bases<Entity, Movable, PowerupCapable, Monster, Critter>()); lua.new_usertype<CritterLocust>( "CritterLocust", "jump_timer", &CritterLocust::jump_timer, sol::base_classes, sol::bases<Entity, Movable, PowerupCapable, Monster, Critter>()); lua.new_usertype<CritterSnail>( "CritterSnail", "x_direction", &CritterSnail::x_direction, "y_direction", &CritterSnail::y_direction, "pos_x", &CritterSnail::pos_x, "pos_y", &CritterSnail::pos_y, "rotation_center_x", &CritterSnail::rotation_center_x, "rotation_center_y", &CritterSnail::rotation_center_y, "rotation_angle", &CritterSnail::rotation_angle, "rotation_speed", &CritterSnail::rotation_speed, sol::base_classes, sol::bases<Entity, Movable, PowerupCapable, Monster, Critter>()); lua.new_usertype<CritterFish>( "CritterFish", "swim_pause_timer", &CritterFish::swim_pause_timer, "player_in_proximity", &CritterFish::player_in_proximity, sol::base_classes, sol::bases<Entity, Movable, PowerupCapable, Monster, Critter>()); lua.new_usertype<CritterPenguin>( "CritterPenguin", "walk_pause_timer", &CritterPenguin::walk_pause_timer, "jump_timer", &CritterPenguin::jump_timer, sol::base_classes, sol::bases<Entity, Movable, PowerupCapable, Monster, Critter>()); lua.new_usertype<CritterFirefly>( "CritterFirefly", "sine_amplitude", &CritterFirefly::sine_amplitude, "sine_frequency", &CritterFirefly::sine_frequency, "sine_angle", &CritterFirefly::sine_angle, "change_direction_timer", &CritterFirefly::change_direction_timer, "sit_timer", &CritterFirefly::sit_timer, "sit_cooldown_timer", &CritterFirefly::sit_cooldown_timer, sol::base_classes, sol::bases<Entity, Movable, PowerupCapable, Monster, Critter>()); lua.new_usertype<CritterDrone>( "CritterDrone", "emitted_light", &CritterDrone::emitted_light, "applied_hor_momentum", &CritterDrone::applied_hor_momentum, "applied_ver_momentum", &CritterDrone::applied_ver_momentum, "move_timer", &CritterDrone::move_timer, sol::base_classes, sol::bases<Entity, Movable, PowerupCapable, Monster, Critter>()); lua.new_usertype<CritterSlime>( "CritterSlime", "x_direction", &CritterSlime::x_direction, "y_direction", &CritterSlime::y_direction, "pos_x", &CritterSlime::pos_x, "pos_y", &CritterSlime::pos_y, "rotation_center_x", &CritterSlime::rotation_center_x, "rotation_center_y", &CritterSlime::rotation_center_y, "rotation_angle", &CritterSlime::rotation_angle, "rotation_speed", &CritterSlime::rotation_speed, "walk_pause_timer", &CritterSlime::walk_pause_timer, sol::base_classes, sol::bases<Entity, Movable, PowerupCapable, Monster, Critter>()); } } // namespace NEntitiesMonsters
32.497995
341
0.606416
iojon
3e587c703115cbaa6f337bf6e0d18d4d9d33a0bc
1,227
hpp
C++
base/include/ntt.hpp
OrbitZore/ATL
a0ade2176459cda6886efd67c2c22916a1092dea
[ "CC0-1.0" ]
2
2021-05-22T13:17:54.000Z
2021-11-23T15:10:10.000Z
base/include/ntt.hpp
OrbitZore/ATL
a0ade2176459cda6886efd67c2c22916a1092dea
[ "CC0-1.0" ]
null
null
null
base/include/ntt.hpp
OrbitZore/ATL
a0ade2176459cda6886efd67c2c22916a1092dea
[ "CC0-1.0" ]
null
null
null
template<class T> struct ntt{ int size,l,n; vector<int> r; const int mod{998244353}; const array<const T,2> P{3,332748118}; array<vector<T>,2> W; int floorintlog2(int i){ int k=0; while (i) i>>=1,k++; return k; } ntt(int size):size(size){ l=floorintlog2(size); n=1<<l; r.resize(n,0); W.fill(vector<T>(n)); for (int i=0;i<n;i++) r[i]=(r[i>>1]>>1)|((i&1)<<(l-1)); for (int type:{0,1}) for (int i=0;i<l;i++) W[type][i]=power(P[type],(mod-1)/(1<<i<<1)); } template<int type,class U> valarray<T> _NTT(const U& B)const{ valarray<T> A(n); copy(std::begin(B),std::end(B),begin(A)); for (int i=0;i<n;i++) if(i<r[i]) swap(A[i],A[r[i]]); for (int mid=1,midj=0;mid<n;mid<<=1,midj++){ T Wn=W[type][midj]; for (int R=mid<<1,j=0;j<n;j+=R){ T w=1; for (int k=0;k<mid;k++,w*=Wn){ const T x=A[j+k],y=w*A[j+mid+k]; A[j+k]=x+y; A[j+mid+k]=x-y; } } } if (type) A*=power(T(n),mod-2); return A; } template<class U> valarray<T> NTT(const U& A)const{return _NTT<0>(A);} valarray<T> DNT(const valarray<T>& A)const{return _NTT<1>(A);} };
26.106383
63
0.492258
OrbitZore
3e59a1107c0e381af43cb1355784123a302684f6
64
hh
C++
inc/Matrix/Matrix2x2.hh
KPO-2020-2021/zad5_2-Poresh2222
d9627b315549b0232dbb7f963e31c0de161a0452
[ "Unlicense" ]
null
null
null
inc/Matrix/Matrix2x2.hh
KPO-2020-2021/zad5_2-Poresh2222
d9627b315549b0232dbb7f963e31c0de161a0452
[ "Unlicense" ]
null
null
null
inc/Matrix/Matrix2x2.hh
KPO-2020-2021/zad5_2-Poresh2222
d9627b315549b0232dbb7f963e31c0de161a0452
[ "Unlicense" ]
null
null
null
#pragma once #include "Matrix.hh" typedef Matrix<2> Matrix2D;
10.666667
27
0.734375
KPO-2020-2021
3e5e1d07c056ec1928417aaf83317563216ab927
23,615
cpp
C++
src/NotesLoaderKSF.cpp
ohsix/stepmania
ea9fa7efcb728b25e9f4b21e6cd93268684057e8
[ "MIT" ]
null
null
null
src/NotesLoaderKSF.cpp
ohsix/stepmania
ea9fa7efcb728b25e9f4b21e6cd93268684057e8
[ "MIT" ]
null
null
null
src/NotesLoaderKSF.cpp
ohsix/stepmania
ea9fa7efcb728b25e9f4b21e6cd93268684057e8
[ "MIT" ]
null
null
null
#include "global.h" #include "NotesLoaderKSF.h" #include "RageUtil_CharConversions.h" #include "MsdFile.h" #include "RageLog.h" #include "RageUtil.h" #include "NoteData.h" #include "NoteTypes.h" #include "Song.h" #include "Steps.h" static void HandleBunki( TimingData &timing, const float fEarlyBPM, const float fCurBPM, const float fGap, const float fPos ) { const float BeatsPerSecond = fEarlyBPM / 60.0f; const float beat = (fPos + fGap) * BeatsPerSecond; LOG->Trace( "BPM %f, BPS %f, BPMPos %f, beat %f", fEarlyBPM, BeatsPerSecond, fPos, beat ); timing.AddSegment( BPMSegment(BeatToNoteRow(beat), fCurBPM) ); } static bool LoadFromKSFFile( const RString &sPath, Steps &out, Song &song, bool bKIUCompliant ) { LOG->Trace( "Steps::LoadFromKSFFile( '%s' )", sPath.c_str() ); MsdFile msd; if( !msd.ReadFile( sPath, false ) ) // don't unescape { LOG->UserLog( "Song file", sPath, "couldn't be opened: %s", msd.GetError().c_str() ); return false; } // this is the value we read for TICKCOUNT int iTickCount = -1; // used to adapt weird tickcounts //float fScrollRatio = 1.0f; -- uncomment when ready to use. vector<RString> vNoteRows; // According to Aldo_MX, there is a default BPM and it's 60. -aj bool bDoublesChart = false; TimingData stepsTiming; float SMGap1 = 0, SMGap2 = 0, BPM1 = -1, BPMPos2 = -1, BPM2 = -1, BPMPos3 = -1, BPM3 = -1; for( unsigned i=0; i<msd.GetNumValues(); i++ ) { const MsdFile::value_t &sParams = msd.GetValue( i ); RString sValueName = sParams[0]; sValueName.MakeUpper(); /* handle the data...well, not this data: not related to steps. * Skips INTRO, MUSICINTRO, TITLEFILE, DISCFILE, SONGFILE. */ if (sValueName=="TITLE" || EndsWith(sValueName, "INTRO") || EndsWith(sValueName, "FILE") ) { } else if( sValueName=="BPM" ) { BPM1 = StringToFloat(sParams[1]); stepsTiming.AddSegment( BPMSegment(0, BPM1) ); } else if( sValueName=="BPM2" ) { if (bKIUCompliant) { BPM2 = StringToFloat( sParams[1] ); } else { // LOG an error. } } else if( sValueName=="BPM3" ) { if (bKIUCompliant) { BPM3 = StringToFloat( sParams[1] ); } else { // LOG an error. } } else if( sValueName=="BUNKI" ) { if (bKIUCompliant) { BPMPos2 = StringToFloat( sParams[1] ) / 100.0f; } else { // LOG an error. } } else if( sValueName=="BUNKI2" ) { if (bKIUCompliant) { BPMPos3 = StringToFloat( sParams[1] ) / 100.0f; } else { // LOG an error. } } else if( sValueName=="STARTTIME" ) { SMGap1 = -StringToFloat( sParams[1] )/100; stepsTiming.m_fBeat0OffsetInSeconds = SMGap1; } // This is currently required for more accurate KIU BPM changes. else if( sValueName=="STARTTIME2" ) { if (bKIUCompliant) { SMGap2 = -StringToFloat( sParams[1] )/100; } else { // LOG an error. } } else if ( sValueName=="STARTTIME3" ) { // STARTTIME3 only ensures this is a KIU compliant simfile. bKIUCompliant = true; } else if( sValueName=="TICKCOUNT" ) { iTickCount = std::stoi( sParams[1] ); if( iTickCount <= 0 ) { LOG->UserLog( "Song file", sPath, "has an invalid tick count: %d.", iTickCount ); return false; } stepsTiming.AddSegment( TickcountSegment(0, iTickCount)); } else if( sValueName=="DIFFICULTY" ) { out.SetMeter( max(std::stoi(sParams[1]), 1) ); } // new cases from Aldo_MX's fork: else if( sValueName=="PLAYER" ) { RString sPlayer = sParams[1]; sPlayer.MakeLower(); if( sPlayer.find( "double" ) != string::npos ) bDoublesChart = true; } // This should always be last. else if( sValueName=="STEP" ) { RString theSteps = sParams[1]; TrimLeft( theSteps ); split( theSteps, "\n", vNoteRows, true ); } } if( iTickCount == -1 ) { iTickCount = 4; LOG->UserLog( "Song file", sPath, "doesn't have a TICKCOUNT. Defaulting to %i.", iTickCount ); } // Prepare BPM stuff already if the file uses KSF syntax. if( bKIUCompliant ) { if( BPM2 > 0 && BPMPos2 > 0 ) { HandleBunki( stepsTiming, BPM1, BPM2, SMGap1, BPMPos2 ); } if( BPM3 > 0 && BPMPos3 > 0 ) { HandleBunki( stepsTiming, BPM2, BPM3, SMGap2, BPMPos3 ); } } NoteData notedata; // read it into here { RString sDir, sFName, sExt; splitpath( sPath, sDir, sFName, sExt ); sFName.MakeLower(); out.SetDescription(sFName); // Check another before anything else... is this okay? -DaisuMaster if( sFName.find("another") != string::npos ) { out.SetDifficulty( Difficulty_Edit ); if( !out.GetMeter() ) out.SetMeter( 25 ); } else if(sFName.find("wild") != string::npos || sFName.find("wd") != string::npos || sFName.find("crazy+") != string::npos || sFName.find("cz+") != string::npos || sFName.find("hardcore") != string::npos ) { out.SetDifficulty( Difficulty_Challenge ); if( !out.GetMeter() ) out.SetMeter( 20 ); } else if(sFName.find("crazy") != string::npos || sFName.find("cz") != string::npos || sFName.find("nightmare") != string::npos || sFName.find("nm") != string::npos || sFName.find("crazydouble") != string::npos ) { out.SetDifficulty( Difficulty_Hard ); if( !out.GetMeter() ) out.SetMeter( 14 ); // Set the meters to the Pump scale, not DDR. } else if(sFName.find("hard") != string::npos || sFName.find("hd") != string::npos || sFName.find("freestyle") != string::npos || sFName.find("fs") != string::npos || sFName.find("double") != string::npos ) { out.SetDifficulty( Difficulty_Medium ); if( !out.GetMeter() ) out.SetMeter( 8 ); } else if(sFName.find("easy") != string::npos || sFName.find("ez") != string::npos || sFName.find("normal") != string::npos ) { // I wonder if I should leave easy fall into the Beginner difficulty... -DaisuMaster out.SetDifficulty( Difficulty_Easy ); if( !out.GetMeter() ) out.SetMeter( 4 ); } else if(sFName.find("beginner") != string::npos || sFName.find("practice") != string::npos || sFName.find("pr") != string::npos ) { out.SetDifficulty( Difficulty_Beginner ); if( !out.GetMeter() ) out.SetMeter( 4 ); } else { out.SetDifficulty( Difficulty_Hard ); if( !out.GetMeter() ) out.SetMeter( 10 ); } out.m_StepsType = StepsType_pump_single; // Check for "halfdouble" before "double". if(sFName.find("halfdouble") != string::npos || sFName.find("half-double") != string::npos || sFName.find("h_double") != string::npos || sFName.find("hdb") != string::npos ) out.m_StepsType = StepsType_pump_halfdouble; // Handle bDoublesChart from above as well. -aj else if(sFName.find("double") != string::npos || sFName.find("nightmare") != string::npos || sFName.find("freestyle") != string::npos || sFName.find("db") != string::npos || sFName.find("nm") != string::npos || sFName.find("fs") != string::npos || bDoublesChart ) out.m_StepsType = StepsType_pump_double; else if( sFName.find("_1") != string::npos ) out.m_StepsType = StepsType_pump_single; else if( sFName.find("_2") != string::npos ) out.m_StepsType = StepsType_pump_couple; } switch( out.m_StepsType ) { case StepsType_pump_single: notedata.SetNumTracks( 5 ); break; case StepsType_pump_couple: notedata.SetNumTracks( 10 ); break; case StepsType_pump_double: notedata.SetNumTracks( 10 ); break; case StepsType_pump_routine: notedata.SetNumTracks( 10 ); break; // future files may have this? case StepsType_pump_halfdouble: notedata.SetNumTracks( 6 ); break; default: FAIL_M( ssprintf("%i", out.m_StepsType) ); } int t = 0; int iHoldStartRow[13]; for( t=0; t<13; t++ ) iHoldStartRow[t] = -1; bool bTickChangeNeeded = false; int newTick = -1; float fCurBeat = 0.0f; float prevBeat = 0.0f; // Used for hold tails. for( unsigned r=0; r<vNoteRows.size(); r++ ) { RString& sRowString = vNoteRows[r]; StripCrnl( sRowString ); if( sRowString == "" ) continue; // skip // All 2s indicates the end of the song. else if( sRowString == "2222222222222" ) { // Finish any holds that didn't get...well, finished. for( t=0; t < notedata.GetNumTracks(); t++ ) { if( iHoldStartRow[t] != -1 ) // this ends the hold { if( iHoldStartRow[t] == BeatToNoteRow(prevBeat) ) notedata.SetTapNote( t, iHoldStartRow[t], TAP_ORIGINAL_TAP ); else notedata.AddHoldNote(t, iHoldStartRow[t], BeatToNoteRow(prevBeat), TAP_ORIGINAL_HOLD_HEAD ); } } /* have this row be the last moment in the song, unless * a future step ends later. */ //float curTime = stepsTiming.GetElapsedTimeFromBeat(fCurBeat); //if (curTime > song.GetSpecifiedLastSecond()) //{ // song.SetSpecifiedLastSecond(curTime); //} song.SetSpecifiedLastSecond( song.GetSpecifiedLastSecond() + 4 ); break; } else if( BeginsWith(sRowString, "|") ) { /* if (bKIUCompliant) { // Log an error, ignore the line. continue; } */ // gotta do something tricky here: if the bpm is below one then a couple of calculations // for scrollsegments will be made, example, bpm 0.2, tick 4000, the scrollsegment will // be 0. if the tickcount is non a stepmania standard then it will be adapted, a scroll // segment will then be added based on approximations. -DaisuMaster // eh better do it considering the tickcount (high tickcounts) // I'm making some experiments, please spare me... //continue; RString temp = sRowString.substr(2,sRowString.size()-3); float numTemp = StringToFloat(temp); if (BeginsWith(sRowString, "|T")) { // duh iTickCount = static_cast<int>(numTemp); // I have been owned by the man -DaisuMaster stepsTiming.SetTickcountAtBeat( fCurBeat, clamp(iTickCount, 0, ROWS_PER_BEAT) ); } else if (BeginsWith(sRowString, "|B")) { // BPM stepsTiming.SetBPMAtBeat( fCurBeat, numTemp ); } else if (BeginsWith(sRowString, "|E")) { // DelayBeat float fCurDelay = 60 / stepsTiming.GetBPMAtBeat(fCurBeat) * numTemp / iTickCount; fCurDelay += stepsTiming.GetDelayAtRow(BeatToNoteRow(fCurBeat) ); stepsTiming.SetDelayAtBeat( fCurBeat, fCurDelay ); } else if (BeginsWith(sRowString, "|D")) { // Delays float fCurDelay = stepsTiming.GetStopAtRow(BeatToNoteRow(fCurBeat) ); fCurDelay += numTemp / 1000; stepsTiming.SetDelayAtBeat( fCurBeat, fCurDelay ); } else if (BeginsWith(sRowString, "|M") || BeginsWith(sRowString, "|C")) { // multipliers/combo ComboSegment seg( BeatToNoteRow(fCurBeat), int(numTemp) ); stepsTiming.AddSegment( seg ); } else if (BeginsWith(sRowString, "|S")) { // speed segments } else if (BeginsWith(sRowString, "|F")) { // fakes } else if (BeginsWith(sRowString, "|X")) { // scroll segments ScrollSegment seg = ScrollSegment( BeatToNoteRow(fCurBeat), numTemp ); stepsTiming.AddSegment( seg ); //return true; } continue; } // Half-doubles is offset; "0011111100000". if( out.m_StepsType == StepsType_pump_halfdouble ) sRowString.erase( 0, 2 ); // Update TICKCOUNT for Direct Move files. if( bTickChangeNeeded ) { iTickCount = newTick; bTickChangeNeeded = false; } for( t=0; t < notedata.GetNumTracks(); t++ ) { if( sRowString[t] == '4' ) { /* Remember when each hold starts; ignore the middle. */ if( iHoldStartRow[t] == -1 ) iHoldStartRow[t] = BeatToNoteRow(fCurBeat); continue; } if( iHoldStartRow[t] != -1 ) // this ends the hold { int iEndRow = BeatToNoteRow(prevBeat); if( iHoldStartRow[t] == iEndRow ) notedata.SetTapNote( t, iHoldStartRow[t], TAP_ORIGINAL_TAP ); else { //notedata.AddHoldNote( t, iHoldStartRow[t], iEndRow , TAP_ORIGINAL_PUMP_HEAD ); notedata.AddHoldNote( t, iHoldStartRow[t], iEndRow , TAP_ORIGINAL_HOLD_HEAD ); } iHoldStartRow[t] = -1; } TapNote tap; switch( sRowString[t] ) { case '0': tap = TAP_EMPTY; break; case '1': tap = TAP_ORIGINAL_TAP; break; //allow setting more notetypes on ksf files, this may come in handy (it should) -DaisuMaster case 'M': case 'm': tap = TAP_ORIGINAL_MINE; break; case 'F': case 'f': tap = TAP_ORIGINAL_FAKE; break; case 'L': case 'l': tap = TAP_ORIGINAL_LIFT; break; default: LOG->UserLog( "Song file", sPath, "has an invalid row \"%s\"; corrupt notes ignored.", sRowString.c_str() ); //return false; tap = TAP_EMPTY; break; } notedata.SetTapNote(t, BeatToNoteRow(fCurBeat), tap); } prevBeat = fCurBeat; fCurBeat = prevBeat + 1.0f / iTickCount; } out.SetNoteData( notedata ); out.m_Timing = stepsTiming; out.TidyUpData(); out.SetSavedToDisk( true ); // we're loading from disk, so this is by definintion already saved return true; } static void LoadTags( const RString &str, Song &out ) { /* str is either a #TITLE or a directory component. Fill in missing information. * str is either "title", "artist - title", or "artist - title - difficulty". */ vector<RString> asBits; split( str, " - ", asBits, false ); // Ignore the difficulty, since we get that elsewhere. if( asBits.size() == 3 && ( asBits[2].EqualsNoCase("double") || asBits[2].EqualsNoCase("easy") || asBits[2].EqualsNoCase("normal") || asBits[2].EqualsNoCase("hard") || asBits[2].EqualsNoCase("crazy") || asBits[2].EqualsNoCase("nightmare")) ) { asBits.erase( asBits.begin()+2, asBits.begin()+3 ); } RString title, artist; if( asBits.size() == 2 ) { artist = asBits[0]; title = asBits[1]; } else if( asBits.size() == 1 ) { title = asBits[0]; } // Convert, if possible. Most KSFs are in Korean encodings (CP942/EUC-KR). if( !ConvertString( title, "korean" ) ) title = ""; if( !ConvertString( artist, "korean" ) ) artist = ""; if( out.m_sMainTitle == "" ) out.m_sMainTitle = title; if( out.m_sArtist == "" ) out.m_sArtist = artist; } static void ProcessTickcounts( const RString & value, int & ticks, TimingData & timing ) { /* TICKCOUNT will be used below if there are DM compliant BPM changes * and stops. It will be called again in LoadFromKSFFile for the * actual steps. */ ticks = std::stoi( value ); CLAMP( ticks, 0, ROWS_PER_BEAT ); if( ticks == 0 ) ticks = TickcountSegment::DEFAULT_TICK_COUNT; timing.AddSegment( TickcountSegment(0, ticks) ); } static bool LoadGlobalData( const RString &sPath, Song &out, bool &bKIUCompliant ) { MsdFile msd; if( !msd.ReadFile( sPath, false ) ) // don't unescape { LOG->UserLog( "Song file", sPath, "couldn't be opened: %s", msd.GetError().c_str() ); return false; } // changed up there in case of something is found inside the SONGFILE tag in the head ksf -DaisuMaster // search for music with song in the file name vector<RString> arrayPossibleMusic; GetDirListing( out.GetSongDir() + RString("song.mp3"), arrayPossibleMusic ); GetDirListing( out.GetSongDir() + RString("song.oga"), arrayPossibleMusic ); GetDirListing( out.GetSongDir() + RString("song.ogg"), arrayPossibleMusic ); GetDirListing( out.GetSongDir() + RString("song.wav"), arrayPossibleMusic ); if( !arrayPossibleMusic.empty() ) // we found a match out.m_sMusicFile = arrayPossibleMusic[0]; // ^this was below, at the end float SMGap1 = 0, SMGap2 = 0, BPM1 = -1, BPMPos2 = -1, BPM2 = -1, BPMPos3 = -1, BPM3 = -1; int iTickCount = -1; bKIUCompliant = false; vector<RString> vNoteRows; for( unsigned i=0; i < msd.GetNumValues(); i++ ) { const MsdFile::value_t &sParams = msd.GetValue(i); RString sValueName = sParams[0]; sValueName.MakeUpper(); // handle the data if( sValueName=="TITLE" ) LoadTags(sParams[1], out); else if( sValueName=="BPM" ) { BPM1 = StringToFloat(sParams[1]); out.m_SongTiming.AddSegment( BPMSegment(0, BPM1) ); } else if( sValueName=="BPM2" ) { bKIUCompliant = true; BPM2 = StringToFloat( sParams[1] ); } else if( sValueName=="BPM3" ) { bKIUCompliant = true; BPM3 = StringToFloat( sParams[1] ); } else if( sValueName=="BUNKI" ) { bKIUCompliant = true; BPMPos2 = StringToFloat( sParams[1] ) / 100.0f; } else if( sValueName=="BUNKI2" ) { bKIUCompliant = true; BPMPos3 = StringToFloat( sParams[1] ) / 100.0f; } else if( sValueName=="STARTTIME" ) { SMGap1 = -StringToFloat( sParams[1] )/100; out.m_SongTiming.m_fBeat0OffsetInSeconds = SMGap1; } // This is currently required for more accurate KIU BPM changes. else if( sValueName=="STARTTIME2" ) { bKIUCompliant = true; SMGap2 = -StringToFloat( sParams[1] )/100; } else if ( sValueName=="STARTTIME3" ) { // STARTTIME3 only ensures this is a KIU compliant simfile. //bKIUCompliant = true; } else if ( sValueName=="TICKCOUNT" ) { ProcessTickcounts(sParams[1], iTickCount, out.m_SongTiming); } else if ( sValueName=="STEP" ) { /* STEP will always be the last header in a KSF file by design. Due to * the Direct Move syntax, it is best to get the rows of notes here. */ RString theSteps = sParams[1]; TrimLeft( theSteps ); split( theSteps, "\n", vNoteRows, true ); } else if( sValueName=="DIFFICULTY" || sValueName=="PLAYER" ) { /* DIFFICULTY and PLAYER are handled only in LoadFromKSFFile. Ignore those here. */ continue; } // New cases noted in Aldo_MX's code: else if( sValueName=="MUSICINTRO" || sValueName=="INTRO" ) { out.m_fMusicSampleStartSeconds = HHMMSSToSeconds( sParams[1] ); } else if( sValueName=="TITLEFILE" ) { out.m_sBackgroundFile = sParams[1]; } else if( sValueName=="DISCFILE" ) { out.m_sBannerFile = sParams[1]; } else if( sValueName=="SONGFILE" ) { out.m_sMusicFile = sParams[1]; } //else if( sValueName=="INTROFILE" ) //{ // nothing to add... //} // end new cases else { LOG->UserLog( "Song file", sPath, "has an unexpected value named \"%s\".", sValueName.c_str() ); } } //intro length in piu mixes is generally 7 seconds out.m_fMusicSampleLengthSeconds = 7.0f; /* BPM Change checks are done here. If bKIUCompliant, it's short and sweet. * Otherwise, the whole file has to be processed. Right now, this is only * called once, for the initial file (often the Crazy steps). Hopefully that * will end up changing soon. */ if( bKIUCompliant ) { if( BPM2 > 0 && BPMPos2 > 0 ) { HandleBunki( out.m_SongTiming, BPM1, BPM2, SMGap1, BPMPos2 ); } if( BPM3 > 0 && BPMPos3 > 0 ) { HandleBunki( out.m_SongTiming, BPM2, BPM3, SMGap2, BPMPos3 ); } } else { float fCurBeat = 0.0f; bool bDMRequired = false; for( unsigned i=0; i < vNoteRows.size(); ++i ) { RString& NoteRowString = vNoteRows[i]; StripCrnl( NoteRowString ); if( NoteRowString == "" ) continue; // ignore empty rows. if( NoteRowString == "2222222222222" ) // Row of 2s = end. Confirm KIUCompliency here. { if (!bDMRequired) bKIUCompliant = true; break; } // This is where the DMRequired test will take place. if ( BeginsWith( NoteRowString, "|" ) ) { // have a static timing for everything bDMRequired = true; continue; } else { // ignore whatever else... //continue; } fCurBeat += 1.0f / iTickCount; } } // Try to fill in missing bits of information from the pathname. { vector<RString> asBits; split( sPath, "/", asBits, true); ASSERT( asBits.size() > 1 ); LoadTags( asBits[asBits.size()-2], out ); } return true; } void KSFLoader::GetApplicableFiles( const RString &sPath, vector<RString> &out ) { GetDirListing( sPath + RString("*.ksf"), out ); } bool KSFLoader::LoadNoteDataFromSimfile( const RString & cachePath, Steps &out ) { bool KIUCompliant = false; Song dummy; if (!LoadGlobalData(cachePath, dummy, KIUCompliant)) return false; Steps *notes = dummy.CreateSteps(); if (LoadFromKSFFile(cachePath, *notes, dummy, KIUCompliant)) { KIUCompliant = true; // yeah, reusing a variable. out.SetNoteData(notes->GetNoteData()); } delete notes; return KIUCompliant; } bool KSFLoader::LoadFromDir( const RString &sDir, Song &out ) { LOG->Trace( "KSFLoader::LoadFromDir(%s)", sDir.c_str() ); vector<RString> arrayKSFFileNames; GetDirListing( sDir + RString("*.ksf"), arrayKSFFileNames ); // We shouldn't have been called to begin with if there were no KSFs. ASSERT( arrayKSFFileNames.size() != 0 ); bool bKIUCompliant = false; /* With Split Timing, there has to be a backup Song Timing in case * anything goes wrong. As these files are kept in alphabetical * order (hopefully), it is best to use the LAST file for timing * purposes, for that is the "normal", or easiest difficulty. * Usually. */ // Nevermind, kiu compilancy is screwing things up: // IE, I have two simfiles, oh wich each have four ksf files, the first one has // the first ksf with directmove timing changes, and the rest are not, everything // goes fine. In the other hand I have my second simfile with the first ksf file // without directmove timing changes and the rest have changes, changes are not // loaded due to kiucompilancy in the first ksf file. // About the "normal" thing, my simfiles' ksfs uses non-standard naming so // the last chart is usually nightmare or normal, I use easy and normal // indistinctly for SM so it shouldn't matter, I use piu fiesta/ex naming // for directmove though, and we're just gathering basic info anyway, and // most of the time all the KSF files have the same info in the #TITLE:; section unsigned files = arrayKSFFileNames.size(); RString dir = out.GetSongDir(); if( !LoadGlobalData(dir + arrayKSFFileNames[files - 1], out, bKIUCompliant) ) return false; out.m_sSongFileName = dir + arrayKSFFileNames[files - 1]; // load the Steps from the rest of the KSF files for( unsigned i=0; i<files; i++ ) { Steps* pNewNotes = out.CreateSteps(); if( !LoadFromKSFFile(dir + arrayKSFFileNames[i], *pNewNotes, out, bKIUCompliant) ) { delete pNewNotes; continue; } pNewNotes->SetFilename(dir + arrayKSFFileNames[i]); out.AddSteps( pNewNotes ); } return true; } /* * (c) 2001-2006 Chris Danford, Glenn Maynard, Jason Felds * All rights reserved. * * 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, and/or sell copies of the Software, and to permit persons to * whom the Software is furnished to do so, provided that the above * copyright notice(s) and this permission notice appear in all copies of * the Software and that both the above copyright notice(s) and this * permission notice appear in supporting documentation. * * 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 OF * THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS * INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT * OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR * PERFORMANCE OF THIS SOFTWARE. */
29.118372
103
0.656151
ohsix
3e61b717b067caea8f2f25f753c5f60a64fad41c
1,016
hpp
C++
libs/fnd/type_traits/include/bksge/fnd/type_traits/is_implicitly_move_constructible.hpp
myoukaku/bksge
0f8b60e475a3f1709723906e4796b5e60decf06e
[ "MIT" ]
4
2018-06-10T13:35:32.000Z
2021-06-03T14:27:41.000Z
libs/fnd/type_traits/include/bksge/fnd/type_traits/is_implicitly_move_constructible.hpp
myoukaku/bksge
0f8b60e475a3f1709723906e4796b5e60decf06e
[ "MIT" ]
566
2017-01-31T05:36:09.000Z
2022-02-09T05:04:37.000Z
libs/fnd/type_traits/include/bksge/fnd/type_traits/is_implicitly_move_constructible.hpp
myoukaku/bksge
0f8b60e475a3f1709723906e4796b5e60decf06e
[ "MIT" ]
1
2018-07-05T04:40:53.000Z
2018-07-05T04:40:53.000Z
/** * @file is_implicitly_move_constructible.hpp * * @brief is_implicitly_move_constructible の定義 * * @author myoukaku */ #ifndef BKSGE_FND_TYPE_TRAITS_IS_IMPLICITLY_MOVE_CONSTRUCTIBLE_HPP #define BKSGE_FND_TYPE_TRAITS_IS_IMPLICITLY_MOVE_CONSTRUCTIBLE_HPP #include <bksge/fnd/config.hpp> namespace bksge { /** * @brief 型Tが暗黙にムーブ構築可能か調べる * * @tparam T チェックする型 * * @require 型Tは完全型であるか、void(cv修飾を含む)か、要素数不明の配列型でなければならない * * is_implicitly_move_constructible は、型Tが暗黙にムーブ構築可能であるならば * true_typeから派生し、そうでなければfalse_typeから派生する。 */ template <typename T> struct is_implicitly_move_constructible; #if defined(BKSGE_HAS_CXX14_VARIABLE_TEMPLATES) template <typename T> BKSGE_INLINE_VAR BKSGE_CONSTEXPR bool is_implicitly_move_constructible_v = is_implicitly_move_constructible<T>::value; #endif } // namespace bksge #include <bksge/fnd/type_traits/inl/is_implicitly_move_constructible_inl.hpp> #endif // BKSGE_FND_TYPE_TRAITS_IS_IMPLICITLY_MOVE_CONSTRUCTIBLE_HPP
23.627907
86
0.790354
myoukaku
3e62ca4347255f39db8725df734c94227dda29b6
8,188
hpp
C++
android-31/android/opengl/EGL14.hpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
12
2020-03-26T02:38:56.000Z
2022-03-14T08:17:26.000Z
android-31/android/opengl/EGL14.hpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
1
2021-01-27T06:07:45.000Z
2021-11-13T19:19:43.000Z
android-29/android/opengl/EGL14.hpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
3
2021-02-02T12:34:55.000Z
2022-03-08T07:45:57.000Z
#pragma once #include "../../JObject.hpp" class JIntArray; class JArray; namespace android::opengl { class EGLConfig; } namespace android::opengl { class EGLContext; } namespace android::opengl { class EGLDisplay; } namespace android::opengl { class EGLSurface; } class JObject; class JString; namespace android::opengl { class EGL14 : public JObject { public: // Fields static jint EGL_ALPHA_MASK_SIZE(); static jint EGL_ALPHA_SIZE(); static jint EGL_BACK_BUFFER(); static jint EGL_BAD_ACCESS(); static jint EGL_BAD_ALLOC(); static jint EGL_BAD_ATTRIBUTE(); static jint EGL_BAD_CONFIG(); static jint EGL_BAD_CONTEXT(); static jint EGL_BAD_CURRENT_SURFACE(); static jint EGL_BAD_DISPLAY(); static jint EGL_BAD_MATCH(); static jint EGL_BAD_NATIVE_PIXMAP(); static jint EGL_BAD_NATIVE_WINDOW(); static jint EGL_BAD_PARAMETER(); static jint EGL_BAD_SURFACE(); static jint EGL_BIND_TO_TEXTURE_RGB(); static jint EGL_BIND_TO_TEXTURE_RGBA(); static jint EGL_BLUE_SIZE(); static jint EGL_BUFFER_DESTROYED(); static jint EGL_BUFFER_PRESERVED(); static jint EGL_BUFFER_SIZE(); static jint EGL_CLIENT_APIS(); static jint EGL_COLOR_BUFFER_TYPE(); static jint EGL_CONFIG_CAVEAT(); static jint EGL_CONFIG_ID(); static jint EGL_CONFORMANT(); static jint EGL_CONTEXT_CLIENT_TYPE(); static jint EGL_CONTEXT_CLIENT_VERSION(); static jint EGL_CONTEXT_LOST(); static jint EGL_CORE_NATIVE_ENGINE(); static jint EGL_DEFAULT_DISPLAY(); static jint EGL_DEPTH_SIZE(); static jint EGL_DISPLAY_SCALING(); static jint EGL_DRAW(); static jint EGL_EXTENSIONS(); static jint EGL_FALSE(); static jint EGL_GREEN_SIZE(); static jint EGL_HEIGHT(); static jint EGL_HORIZONTAL_RESOLUTION(); static jint EGL_LARGEST_PBUFFER(); static jint EGL_LEVEL(); static jint EGL_LUMINANCE_BUFFER(); static jint EGL_LUMINANCE_SIZE(); static jint EGL_MATCH_NATIVE_PIXMAP(); static jint EGL_MAX_PBUFFER_HEIGHT(); static jint EGL_MAX_PBUFFER_PIXELS(); static jint EGL_MAX_PBUFFER_WIDTH(); static jint EGL_MAX_SWAP_INTERVAL(); static jint EGL_MIN_SWAP_INTERVAL(); static jint EGL_MIPMAP_LEVEL(); static jint EGL_MIPMAP_TEXTURE(); static jint EGL_MULTISAMPLE_RESOLVE(); static jint EGL_MULTISAMPLE_RESOLVE_BOX(); static jint EGL_MULTISAMPLE_RESOLVE_BOX_BIT(); static jint EGL_MULTISAMPLE_RESOLVE_DEFAULT(); static jint EGL_NATIVE_RENDERABLE(); static jint EGL_NATIVE_VISUAL_ID(); static jint EGL_NATIVE_VISUAL_TYPE(); static jint EGL_NONE(); static jint EGL_NON_CONFORMANT_CONFIG(); static jint EGL_NOT_INITIALIZED(); static android::opengl::EGLContext EGL_NO_CONTEXT(); static android::opengl::EGLDisplay EGL_NO_DISPLAY(); static android::opengl::EGLSurface EGL_NO_SURFACE(); static jint EGL_NO_TEXTURE(); static jint EGL_OPENGL_API(); static jint EGL_OPENGL_BIT(); static jint EGL_OPENGL_ES2_BIT(); static jint EGL_OPENGL_ES_API(); static jint EGL_OPENGL_ES_BIT(); static jint EGL_OPENVG_API(); static jint EGL_OPENVG_BIT(); static jint EGL_OPENVG_IMAGE(); static jint EGL_PBUFFER_BIT(); static jint EGL_PIXEL_ASPECT_RATIO(); static jint EGL_PIXMAP_BIT(); static jint EGL_READ(); static jint EGL_RED_SIZE(); static jint EGL_RENDERABLE_TYPE(); static jint EGL_RENDER_BUFFER(); static jint EGL_RGB_BUFFER(); static jint EGL_SAMPLES(); static jint EGL_SAMPLE_BUFFERS(); static jint EGL_SINGLE_BUFFER(); static jint EGL_SLOW_CONFIG(); static jint EGL_STENCIL_SIZE(); static jint EGL_SUCCESS(); static jint EGL_SURFACE_TYPE(); static jint EGL_SWAP_BEHAVIOR(); static jint EGL_SWAP_BEHAVIOR_PRESERVED_BIT(); static jint EGL_TEXTURE_2D(); static jint EGL_TEXTURE_FORMAT(); static jint EGL_TEXTURE_RGB(); static jint EGL_TEXTURE_RGBA(); static jint EGL_TEXTURE_TARGET(); static jint EGL_TRANSPARENT_BLUE_VALUE(); static jint EGL_TRANSPARENT_GREEN_VALUE(); static jint EGL_TRANSPARENT_RED_VALUE(); static jint EGL_TRANSPARENT_RGB(); static jint EGL_TRANSPARENT_TYPE(); static jint EGL_TRUE(); static jint EGL_VENDOR(); static jint EGL_VERSION(); static jint EGL_VERTICAL_RESOLUTION(); static jint EGL_VG_ALPHA_FORMAT(); static jint EGL_VG_ALPHA_FORMAT_NONPRE(); static jint EGL_VG_ALPHA_FORMAT_PRE(); static jint EGL_VG_ALPHA_FORMAT_PRE_BIT(); static jint EGL_VG_COLORSPACE(); static jint EGL_VG_COLORSPACE_LINEAR(); static jint EGL_VG_COLORSPACE_LINEAR_BIT(); static jint EGL_VG_COLORSPACE_sRGB(); static jint EGL_WIDTH(); static jint EGL_WINDOW_BIT(); // QJniObject forward template<typename ...Ts> explicit EGL14(const char *className, const char *sig, Ts...agv) : JObject(className, sig, std::forward<Ts>(agv)...) {} EGL14(QJniObject obj); // Constructors EGL14(); // Methods static jboolean eglBindAPI(jint arg0); static jboolean eglBindTexImage(android::opengl::EGLDisplay arg0, android::opengl::EGLSurface arg1, jint arg2); static jboolean eglChooseConfig(android::opengl::EGLDisplay arg0, JIntArray arg1, jint arg2, JArray arg3, jint arg4, jint arg5, JIntArray arg6, jint arg7); static jboolean eglCopyBuffers(android::opengl::EGLDisplay arg0, android::opengl::EGLSurface arg1, jint arg2); static android::opengl::EGLContext eglCreateContext(android::opengl::EGLDisplay arg0, android::opengl::EGLConfig arg1, android::opengl::EGLContext arg2, JIntArray arg3, jint arg4); static android::opengl::EGLSurface eglCreatePbufferFromClientBuffer(android::opengl::EGLDisplay arg0, jint arg1, jint arg2, android::opengl::EGLConfig arg3, JIntArray arg4, jint arg5); static android::opengl::EGLSurface eglCreatePbufferSurface(android::opengl::EGLDisplay arg0, android::opengl::EGLConfig arg1, JIntArray arg2, jint arg3); static android::opengl::EGLSurface eglCreatePixmapSurface(android::opengl::EGLDisplay arg0, android::opengl::EGLConfig arg1, jint arg2, JIntArray arg3, jint arg4); static android::opengl::EGLSurface eglCreateWindowSurface(android::opengl::EGLDisplay arg0, android::opengl::EGLConfig arg1, JObject arg2, JIntArray arg3, jint arg4); static jboolean eglDestroyContext(android::opengl::EGLDisplay arg0, android::opengl::EGLContext arg1); static jboolean eglDestroySurface(android::opengl::EGLDisplay arg0, android::opengl::EGLSurface arg1); static jboolean eglGetConfigAttrib(android::opengl::EGLDisplay arg0, android::opengl::EGLConfig arg1, jint arg2, JIntArray arg3, jint arg4); static jboolean eglGetConfigs(android::opengl::EGLDisplay arg0, JArray arg1, jint arg2, jint arg3, JIntArray arg4, jint arg5); static android::opengl::EGLContext eglGetCurrentContext(); static android::opengl::EGLDisplay eglGetCurrentDisplay(); static android::opengl::EGLSurface eglGetCurrentSurface(jint arg0); static android::opengl::EGLDisplay eglGetDisplay(jint arg0); static jint eglGetError(); static jboolean eglInitialize(android::opengl::EGLDisplay arg0, JIntArray arg1, jint arg2, JIntArray arg3, jint arg4); static jboolean eglMakeCurrent(android::opengl::EGLDisplay arg0, android::opengl::EGLSurface arg1, android::opengl::EGLSurface arg2, android::opengl::EGLContext arg3); static jint eglQueryAPI(); static jboolean eglQueryContext(android::opengl::EGLDisplay arg0, android::opengl::EGLContext arg1, jint arg2, JIntArray arg3, jint arg4); static JString eglQueryString(android::opengl::EGLDisplay arg0, jint arg1); static jboolean eglQuerySurface(android::opengl::EGLDisplay arg0, android::opengl::EGLSurface arg1, jint arg2, JIntArray arg3, jint arg4); static jboolean eglReleaseTexImage(android::opengl::EGLDisplay arg0, android::opengl::EGLSurface arg1, jint arg2); static jboolean eglReleaseThread(); static jboolean eglSurfaceAttrib(android::opengl::EGLDisplay arg0, android::opengl::EGLSurface arg1, jint arg2, jint arg3); static jboolean eglSwapBuffers(android::opengl::EGLDisplay arg0, android::opengl::EGLSurface arg1); static jboolean eglSwapInterval(android::opengl::EGLDisplay arg0, jint arg1); static jboolean eglTerminate(android::opengl::EGLDisplay arg0); static jboolean eglWaitClient(); static jboolean eglWaitGL(); static jboolean eglWaitNative(jint arg0); }; } // namespace android::opengl
42.86911
186
0.778456
YJBeetle
3e6b33a94d9acb1084cc1a4cb7557c13f954f461
1,253
cpp
C++
Core/Math/ColorConvert.cpp
laszlopapai/UAVOnboardController
ca3d9b6314903711e75920d262c7388edfb810e5
[ "Apache-2.0" ]
null
null
null
Core/Math/ColorConvert.cpp
laszlopapai/UAVOnboardController
ca3d9b6314903711e75920d262c7388edfb810e5
[ "Apache-2.0" ]
null
null
null
Core/Math/ColorConvert.cpp
laszlopapai/UAVOnboardController
ca3d9b6314903711e75920d262c7388edfb810e5
[ "Apache-2.0" ]
null
null
null
#include <algorithm> #include "ColorConvert.h" #include <math.h> using namespace IoT::Core; void ColorConvert::hsv2rgb(float H, float S, float V, float *r, float *g, float *b) { H -= ((uint64_t)(H / 360) * 360.0f); float R, G, B; if (V <= 0) { R = G = B = 0; } else if (S <= 0) { R = G = B = V; } else { float hf = fabsf(H) / 60.0f; int i = (int)hf; float f = hf - i; float pv = V * (1 - S); float qv = V * (1 - S * f); float tv = V * (1 - S * (1 - f)); // Red is the dominant color if (i == 0) { R = V; G = tv; B = pv; } if (i == 5) { R = V; G = pv; B = qv; } // Green is the dominant color if (i == 1) { R = qv; G = V; B = pv; } if (i == 2) { R = pv; G = V; B = tv; } // Blue is the dominant color if (i == 3) { R = pv; G = qv; B = V; } if (i == 4) { R = tv; G = pv; B = V; } } *r = std::max(std::min(R, 1.0f), 0.0f); *g = std::max(std::min(G, 1.0f), 0.0f); *b = std::max(std::min(B, 1.0f), 0.0f); } void ColorConvert::rgb2hsv(float R, float G, float B, float *h, float *s, float *v) { float cMax = std::max(std::max(R, G), B); float cMin = std::min(std::min(R, G), B); float d = cMax - cMin; // TODO: rgb2hsv converter }
15.6625
85
0.466879
laszlopapai
3e6c46c8f8250b16ba51476516871873f9de2581
33,636
cpp
C++
src/messagetree/server/MessageTreeDatabasePeerSession.cpp
ruurdadema/zg_choir
6de0e8be497974c0e56bb87139b18f0d6f5b4ee3
[ "BSD-3-Clause" ]
null
null
null
src/messagetree/server/MessageTreeDatabasePeerSession.cpp
ruurdadema/zg_choir
6de0e8be497974c0e56bb87139b18f0d6f5b4ee3
[ "BSD-3-Clause" ]
null
null
null
src/messagetree/server/MessageTreeDatabasePeerSession.cpp
ruurdadema/zg_choir
6de0e8be497974c0e56bb87139b18f0d6f5b4ee3
[ "BSD-3-Clause" ]
null
null
null
#include "zg/messagetree/server/ClientDataMessageTreeDatabaseObject.h" #include "zg/messagetree/server/MessageTreeDatabasePeerSession.h" #include "zg/messagetree/server/MessageTreeDatabaseObject.h" #include "zg/messagetree/server/UndoStackMessageTreeDatabaseObject.h" #include "zg/messagetree/server/ServerSideMessageTreeSession.h" #include "zg/messagetree/server/ServerSideMessageUtilityFunctions.h" namespace zg { enum { MTDPS_COMMAND_PINGSENIORPEER = 1836344432, // 'mtdp' MTDPS_COMMAND_MESSAGETOSENIORPEER, MTDPS_COMMAND_MESSAGEFROMSENIORPEER, MTDPS_COMMAND_MESSAGETOSUBSCRIBER, }; static const String MTDPS_NAME_TAG = "mtp_tag"; static const String MTDPS_NAME_SOURCE = "mtp_src"; static const String MTDPS_NAME_FILTER = "mtp_flt"; static const String MTDPS_NAME_FLAGS = "mtp_flg"; static const String MTDPS_NAME_UNDOKEY = "mtp_key"; static const String MTDPS_NAME_PAYLOAD = "mtp_pay"; static const String MTDPS_NAME_WHICHDB = "mtp_dbi"; static const String MTDPS_NAME_PATH = "mtp_pth"; MessageTreeDatabasePeerSession :: MessageTreeDatabasePeerSession(const ZGPeerSettings & zgPeerSettings) : ZGDatabasePeerSession(zgPeerSettings), ProxyTreeGateway(NULL), _muxGateway(this) { SetRoutingFlag(MUSCLE_ROUTING_FLAG_REFLECT_TO_SELF, true); // necessary because we want to be notified about updates to our own subtree } status_t MessageTreeDatabasePeerSession :: AttachedToServer() { NestCountGuard ncd(_inPeerSessionSetupOrTeardown); status_t ret = ZGDatabasePeerSession::AttachedToServer(); // Check for duplicate mount-points const uint32 numDBs = GetPeerSettings().GetNumDatabases(); for (uint32 i=0; i<numDBs; i++) { const MessageTreeDatabaseObject * idb = dynamic_cast<const MessageTreeDatabaseObject *>(GetDatabaseObject(i)); for (uint32 j=0; j<numDBs; j++) { const MessageTreeDatabaseObject * jdb = dynamic_cast<const MessageTreeDatabaseObject *>(GetDatabaseObject(j)); if ((idb)&&(jdb)&&(idb != jdb)&&(idb->GetRootPathWithoutSlash() == jdb->GetRootPathWithoutSlash())) { LogTime(MUSCLE_LOG_CRITICALERROR, "MessageTreeDatabasePeerSession::AttachedToServer: Database #" UINT32_FORMAT_SPEC " has the same root-path [%s] as previously added database #" UINT32_FORMAT_SPEC "!\n", i, idb->GetRootPathWithoutSlash()(), j); return B_LOGIC_ERROR; } } } _gestaltMessage = GetEffectiveParameters(); return ret; } void MessageTreeDatabasePeerSession :: AboutToDetachFromServer() { NestCountGuard ncd(_inPeerSessionSetupOrTeardown); ZGDatabasePeerSession::AboutToDetachFromServer(); } void MessageTreeDatabasePeerSession :: PeerHasComeOnline(const ZGPeerID & peerID, const ConstMessageRef & peerInfo) { const bool wasFullyAttached = IAmFullyAttached(); ZGDatabasePeerSession::PeerHasComeOnline(peerID, peerInfo); if ((wasFullyAttached == false)&&(IAmFullyAttached())) { GatewayCallbackBatchGuard<ITreeGateway> gcbg(this); ProxyTreeGateway::TreeGatewayConnectionStateChanged(); // notify our subscribers that we're now connected to the database. } } status_t MessageTreeDatabasePeerSession :: TreeGateway_AddSubscription(ITreeGatewaySubscriber * /*calledBy*/, const String & subscriptionPath, const ConstQueryFilterRef & optFilterRef, TreeGatewayFlags flags) { MessageRef cmdMsg; MRETURN_ON_ERROR(CreateMuscleSubscribeMessage(subscriptionPath, optFilterRef, flags, cmdMsg)); NestCountGuard ncg(_inLocalRequestNestCount); MessageReceivedFromGateway(cmdMsg, NULL); return B_NO_ERROR; } status_t MessageTreeDatabasePeerSession :: TreeGateway_RemoveSubscription(ITreeGatewaySubscriber * /*calledBy*/, const String & subscriptionPath, const ConstQueryFilterRef & /*optFilterRef*/, TreeGatewayFlags /*flags*/) { MessageRef cmdMsg; MRETURN_ON_ERROR(CreateMuscleUnsubscribeMessage(subscriptionPath, cmdMsg)); MessageReceivedFromGateway(cmdMsg, NULL); return B_NO_ERROR; } status_t MessageTreeDatabasePeerSession :: TreeGateway_RemoveAllSubscriptions(ITreeGatewaySubscriber * /*calledBy*/, TreeGatewayFlags /*flags*/) { MessageRef cmdMsg; MRETURN_ON_ERROR(CreateMuscleUnsubscribeAllMessage(cmdMsg)); MessageReceivedFromGateway(cmdMsg, NULL); return B_NO_ERROR; } status_t MessageTreeDatabasePeerSession :: TreeGateway_RequestNodeValues(ITreeGatewaySubscriber * /*calledBy*/, const String & queryString, const ConstQueryFilterRef & optFilterRef, TreeGatewayFlags /*flags*/, const String & tag) { MessageRef cmdMsg; MRETURN_ON_ERROR(CreateMuscleRequestNodeValuesMessage(queryString, optFilterRef, cmdMsg, tag)); NestCountGuard ncg(_inLocalRequestNestCount); MessageReceivedFromGateway(cmdMsg, NULL); return B_NO_ERROR; } status_t MessageTreeDatabasePeerSession :: TreeGateway_RequestNodeSubtrees(ITreeGatewaySubscriber * /*calledBy*/, const Queue<String> & queryStrings, const Queue<ConstQueryFilterRef> & queryFilters, const String & tag, uint32 maxDepth, TreeGatewayFlags /*flags*/) { MessageRef cmdMsg; MRETURN_ON_ERROR(CreateMuscleRequestNodeSubtreesMessage(queryStrings, queryFilters, tag, maxDepth, cmdMsg)); NestCountGuard ncg(_inLocalRequestNestCount); MessageReceivedFromGateway(cmdMsg, NULL); return B_NO_ERROR; } status_t MessageTreeDatabasePeerSession :: TreeGateway_UploadNodeValue(ITreeGatewaySubscriber * /*calledBy*/, const String & path, const MessageRef & optPayload, TreeGatewayFlags flags, const String & optBefore, const String & optOpTag) { String relativePath; MessageTreeDatabaseObject * mtDB = GetDatabaseForNodePath(path, &relativePath); if (mtDB) return mtDB->UploadNodeValue(relativePath, optPayload, flags, optBefore, optOpTag); else { LogTime(MUSCLE_LOG_ERROR, "MessageTreeDatabasePeerSession::TreeGateway_UploadNodeValue(): No database found for path [%s]!\n", path()); return B_BAD_ARGUMENT; } } status_t MessageTreeDatabasePeerSession :: TreeGateway_UploadNodeSubtree(ITreeGatewaySubscriber * /*calledBy*/, const String & basePath, const MessageRef & valuesMsg, TreeGatewayFlags flags, const String & optOpTag) { String relativePath; MessageTreeDatabaseObject * mtDB = GetDatabaseForNodePath(basePath, &relativePath); if (mtDB) { // I'm not sure if this is the correct logic to use, but it works for now --jaf status_t ret; MessageRef effMsg = valuesMsg; if (valuesMsg()->FindMessage(basePath, effMsg).IsError()) { LogTime(MUSCLE_LOG_ERROR, "Couldn't find basePath Message [%s] in subtree-upload! [%s]\n", basePath(), ret()); return ret; } (void) mtDB->RequestDeleteNodes(relativePath, ConstQueryFilterRef(), TreeGatewayFlags(), optOpTag); // we want a full overwrite of the specified subtree, not an add-to return mtDB->UploadNodeSubtree(relativePath, effMsg, flags, optOpTag); } else { LogTime(MUSCLE_LOG_ERROR, "MessageTreeDatabasePeerSession::TreeGateway_UploadNodeSubtree(): No database found for path [%s]!\n", basePath()); return B_BAD_ARGUMENT; } } status_t MessageTreeDatabasePeerSession :: TreeGateway_RequestDeleteNodes(ITreeGatewaySubscriber * /*calledBy*/, const String & path, const ConstQueryFilterRef & optFilterRef, TreeGatewayFlags flags, const String & optOpTag) { status_t ret; const Hashtable<MessageTreeDatabaseObject *, String> dbs = GetDatabasesForNodePath(path); for (HashtableIterator<MessageTreeDatabaseObject *, String> iter(dbs); iter.HasData(); iter++) ret |= iter.GetKey()->RequestDeleteNodes(iter.GetValue(), optFilterRef, flags, optOpTag); return ret; } status_t MessageTreeDatabasePeerSession :: TreeGateway_RequestMoveIndexEntry(ITreeGatewaySubscriber * /*calledBy*/, const String & path, const String & optBefore, const ConstQueryFilterRef & optFilterRef, TreeGatewayFlags flags, const String & optOpTag) { String relativePath; MessageTreeDatabaseObject * mtDB = GetDatabaseForNodePath(path, &relativePath); if (mtDB) return mtDB->RequestMoveIndexEntry(relativePath, optBefore, optFilterRef, flags, optOpTag); else { LogTime(MUSCLE_LOG_ERROR, "TreeGateway_RequestMoveIndexEntry: No database found for path [%s]\n", path()); return B_BAD_ARGUMENT; } } status_t MessageTreeDatabasePeerSession :: TreeGateway_PingLocalPeer(ITreeGatewaySubscriber * /*calledBy*/, const String & tag, TreeGatewayFlags flags) { if (flags.IsBitSet(TREE_GATEWAY_FLAG_NOREPLY) == false) TreeLocalPeerPonged(tag); return B_NO_ERROR; } status_t MessageTreeDatabasePeerSession :: TreeGateway_PingSeniorPeer(ITreeGatewaySubscriber * /*calledBy*/, const String & tag, uint32 whichDB, TreeGatewayFlags flags) { if (GetSeniorPeerID().IsValid() == false) return B_ERROR("PingSeniorPeer: Senior peer not available"); MessageRef seniorPingMsg = GetMessageFromPool(MTDPS_COMMAND_PINGSENIORPEER); MRETURN_OOM_ON_NULL(seniorPingMsg()); MRETURN_ON_ERROR(seniorPingMsg()->CAddString(MTDPS_NAME_TAG, tag)); MRETURN_ON_ERROR(seniorPingMsg()->CAddFlat(MTDPS_NAME_SOURCE, GetLocalPeerID())); MRETURN_ON_ERROR(seniorPingMsg()->CAddFlat(MTDPS_NAME_FLAGS, flags)); return RequestUpdateDatabaseState(whichDB, seniorPingMsg); } status_t MessageTreeDatabasePeerSession :: TreeGateway_SendMessageToSeniorPeer(ITreeGatewaySubscriber * /*calledBy*/, const MessageRef & msg, uint32 whichDB, const String & tag) { if (GetSeniorPeerID().IsValid() == false) return B_ERROR("SendMessageToSeniorPeer: Senior peer not available"); MessageRef seniorCommandMsg = GetMessageFromPool(MTDPS_COMMAND_MESSAGETOSENIORPEER); MRETURN_OOM_ON_NULL(seniorCommandMsg()); MRETURN_ON_ERROR(seniorCommandMsg()->AddMessage(MTDPS_NAME_PAYLOAD, msg)); MRETURN_ON_ERROR(seniorCommandMsg()->CAddFlat( MTDPS_NAME_SOURCE, GetLocalPeerID())); MRETURN_ON_ERROR(seniorCommandMsg()->CAddInt32( MTDPS_NAME_WHICHDB, whichDB)); MRETURN_ON_ERROR(seniorCommandMsg()->CAddString(MTDPS_NAME_TAG, tag)); return SendUnicastUserMessageToPeer(GetSeniorPeerID(), seniorCommandMsg); } ZGPeerID MessageTreeDatabasePeerSession :: GetPerClientPeerIDForNode(const DataNode & node) const { const uint32 numDBs = GetPeerSettings().GetNumDatabases(); for (uint32 i=0; i<numDBs; i++) { ClientDataMessageTreeDatabaseObject * nextDB = dynamic_cast<ClientDataMessageTreeDatabaseObject *>(GetDatabaseObject(i)); if (nextDB) { String subPath; if (nextDB->GetDatabaseSubpath(node.GetNodePath(), &subPath) > 0) { ZGPeerID ret; ret.FromString(subPath()); if (ret.IsValid()) return ret; } } } return ZGPeerID(); } class GetPerClientPeerIDsCallbackArgs { public: GetPerClientPeerIDsCallbackArgs(Hashtable<ZGPeerID, Void> & peerIDs) : _peerIDs(peerIDs), _sendToAll(false) {/* empty */} Hashtable<ZGPeerID, Void> & _peerIDs; bool _sendToAll; }; int MessageTreeDatabasePeerSession :: GetPerClientPeerIDsCallback(DataNode & node, void * ud) { GetPerClientPeerIDsCallbackArgs & args = *(static_cast<GetPerClientPeerIDsCallbackArgs *>(ud)); const ZGPeerID pid = GetPerClientPeerIDForNode(node); if (pid.IsValid()) { (void) args._peerIDs.PutWithDefault(pid); return node.GetDepth(); } else { args._sendToAll = true; return -1; // abort now -- we know we'll need to send to all peers, so there's no sense traversing further } } static ZGPeerID GetPeerIDFromReturnAddress(const String & path, String * optRetSuffix) { if (path.StartsWith('{')) { const int32 rightBraceIdx = path.IndexOf("}:"); if (rightBraceIdx >= 0) { ZGPeerID ret; ret.FromString(path.Substring(1, rightBraceIdx)); if (optRetSuffix) *optRetSuffix = path.Substring(rightBraceIdx+2); // +1 for the right-brace, and +1 for the colon return ret; } } return ZGPeerID(); // failure } // Note: If this method returns an error-code, that means we should send to all peers status_t MessageTreeDatabasePeerSession :: GetPerClientPeerIDsForPath(const String & path, const ConstQueryFilterRef & optFilter, Hashtable<ZGPeerID, Void> & retPeerIDs) { const ZGPeerID peerID = GetPeerIDFromReturnAddress(path, NULL); if (peerID.IsValid()) { // path is something like "{f01898e8e4810001:fa4c50daa9eb}:_3_:_4_:" -- we'll use this to route it back to exactly one ITreeGatewaySubscriber return retPeerIDs.PutWithDefault(peerID); } else { // path is e.g. "foo/bar/baz*" -- we want to send the Message on to any ITreeGatewaySubscribers who are subscribed to any of the nodes matching the path const bool isGlobal = path.StartsWith('/'); NodePathMatcher matcher; MRETURN_ON_ERROR(matcher.PutPathString(isGlobal?path.Substring(1):path, optFilter)); GetPerClientPeerIDsCallbackArgs args(retPeerIDs); (void) matcher.DoTraversal((PathMatchCallback) GetPerClientPeerIDsCallbackFunc, this, isGlobal?GetGlobalRoot():*GetSessionNode()(), true, &args); return args._sendToAll ? B_ERROR : B_NO_ERROR; } } status_t MessageTreeDatabasePeerSession :: TreeGateway_SendMessageToSubscriber(ITreeGatewaySubscriber * /*calledBy*/, const String & subscriberPath, const MessageRef & msg, const ConstQueryFilterRef & optFilterRef, const String & tag) { MessageRef cmdMsg = GetMessageFromPool(MTDPS_COMMAND_MESSAGETOSUBSCRIBER); MRETURN_OOM_ON_NULL(cmdMsg()); MRETURN_ON_ERROR(cmdMsg()->AddMessage(MTDPS_NAME_PAYLOAD, msg)); MRETURN_ON_ERROR(cmdMsg()->CAddString(MTDPS_NAME_PATH, subscriberPath)); MRETURN_ON_ERROR(cmdMsg()->CAddArchiveMessage(MTDPS_NAME_FILTER, optFilterRef)); MRETURN_ON_ERROR(cmdMsg()->AddString(MTDPS_NAME_TAG, String("{%1}:%2").Arg(GetLocalPeerID().ToString()).Arg(tag))); Hashtable<ZGPeerID, Void> targetPeerIDs; if (GetPerClientPeerIDsForPath(subscriberPath, optFilterRef, targetPeerIDs).IsOK()) { status_t ret; for (HashtableIterator<ZGPeerID, Void> iter(targetPeerIDs); iter.HasData(); iter++) ret |= SendUnicastUserMessageToPeer(iter.GetKey(), cmdMsg); return ret; } else return SendUnicastUserMessageToAllPeers(cmdMsg); } status_t MessageTreeDatabasePeerSession :: TreeGateway_BeginUndoSequence(ITreeGatewaySubscriber * /*calledBy*/, const String & optSequenceLabel, uint32 whichDB) { return UploadUndoRedoRequestToSeniorPeer(UNDOSTACK_COMMAND_BEGINSEQUENCE, optSequenceLabel, whichDB); } status_t MessageTreeDatabasePeerSession :: TreeGateway_EndUndoSequence(ITreeGatewaySubscriber * /*calledBy*/, const String & optSequenceLabel, uint32 whichDB) { return UploadUndoRedoRequestToSeniorPeer(UNDOSTACK_COMMAND_ENDSEQUENCE, optSequenceLabel, whichDB); } status_t MessageTreeDatabasePeerSession :: TreeGateway_RequestUndo(ITreeGatewaySubscriber * /*calledBy*/, uint32 whichDB, const String & optOpTag) { return UploadUndoRedoRequestToSeniorPeer(UNDOSTACK_COMMAND_UNDO, optOpTag, whichDB); } status_t MessageTreeDatabasePeerSession :: TreeGateway_RequestRedo(ITreeGatewaySubscriber * /*calledBy*/, uint32 whichDB, const String & optOpTag) { return UploadUndoRedoRequestToSeniorPeer(UNDOSTACK_COMMAND_REDO, optOpTag, whichDB); } status_t MessageTreeDatabasePeerSession :: UploadUndoRedoRequestToSeniorPeer(uint32 whatCode, const String & optSequenceLabelOrOpTag, uint32 whichDB) { UndoStackMessageTreeDatabaseObject * undoDB = dynamic_cast<UndoStackMessageTreeDatabaseObject *>(GetDatabaseObject(whichDB)); if (undoDB) { return undoDB->UploadUndoRedoRequestToSeniorPeer(whatCode, optSequenceLabelOrOpTag); } else { LogTime(MUSCLE_LOG_ERROR, "MessageTreeDatabasePeerSession::UploadUndoRedoRequestToSeniorPeer(): Database #" UINT32_FORMAT_SPEC " is not an UndoStackMessageTreeDatabaseObject!\n", whichDB); return B_BAD_ARGUMENT; } } void MessageTreeDatabasePeerSession :: CommandBatchEnds() { ProxyTreeGateway::CommandBatchEnds(); if (IsAttachedToServer()) PushSubscriptionMessages(); // make sure any subscription updates go out in a timely fashion } void MessageTreeDatabasePeerSession :: NotifySubscribersThatNodeChanged(DataNode & node, const MessageRef & oldDataRef, NodeChangeFlags nodeChangeFlags) { //printf("NotifySubscribersThatNodeChanged node=[%s] payload=%p nodeChangeFlags=%s\n", node.GetNodePath()(), node.GetData()(), nodeChangeFlags.ToHexString()()); GatewayCallbackBatchGuard<ITreeGateway> gcbg(this); // yes, this is necessary String relativePath; MessageTreeDatabaseObject * mtDB = GetDatabaseForNodePath(node.GetNodePath(), &relativePath); if (mtDB) mtDB->MessageTreeNodeUpdated(relativePath, node, oldDataRef, nodeChangeFlags.IsBitSet(NODE_CHANGE_FLAG_ISBEINGREMOVED)); ZGDatabasePeerSession::NotifySubscribersThatNodeChanged(node, oldDataRef, nodeChangeFlags); } void MessageTreeDatabasePeerSession :: NotifySubscribersThatNodeIndexChanged(DataNode & node, char op, uint32 index, const String & key) { //printf("NotifySubscribersThatNodeIndexChanged node=[%s] op=%c index=%u key=[%s]\n", node.GetNodePath()(), op, index, key()); GatewayCallbackBatchGuard<ITreeGateway> gcbg(this); // yes, this is necessary String relativePath; MessageTreeDatabaseObject * mtDB = GetDatabaseForNodePath(node.GetNodePath(), &relativePath); if (mtDB) mtDB->MessageTreeNodeIndexChanged(relativePath, node, op, index, key); ZGDatabasePeerSession::NotifySubscribersThatNodeIndexChanged(node, op, index, key); } void MessageTreeDatabasePeerSession :: NodeChanged(DataNode & node, const MessageRef & /*oldData*/, NodeChangeFlags nodeChangeFlags) { // deliberately NOT calling up to superclass, as I don't want any MUSCLE-update messages to be generated for this session const MessageTreeDatabaseObject * mtDB = GetDatabaseForNodePath(node.GetNodePath(), NULL); TreeNodeUpdated(node.GetNodePath().Substring(GetSessionRootPath().Length()+1), nodeChangeFlags.IsBitSet(NODE_CHANGE_FLAG_ISBEINGREMOVED)?MessageRef():node.GetData(), mtDB?mtDB->GetCurrentOpTag():GetEmptyString()); } void MessageTreeDatabasePeerSession :: NodeIndexChanged(DataNode & node, char op, uint32 index, const String & key) { // deliberately NOT calling up to superclass, as I don't want any MUSCLE-update messages to be generated for this session const MessageTreeDatabaseObject * mtDB = GetDatabaseForNodePath(node.GetNodePath(), NULL); const String & opTag = mtDB?mtDB->GetCurrentOpTag():GetEmptyString(); const String path = node.GetNodePath().Substring(GetSessionRootPath().Length()+1); switch(op) { case INDEX_OP_ENTRYINSERTED: TreeNodeIndexEntryInserted(path, index, key, opTag); break; case INDEX_OP_ENTRYREMOVED: TreeNodeIndexEntryRemoved( path, index, key, opTag); break; case INDEX_OP_CLEARED: TreeNodeIndexCleared(path, opTag); break; default: LogTime(MUSCLE_LOG_CRITICALERROR, "MessageTreeDatabasePeerSession::NodeIndexChanged: Unknown op [%c] for node [%s]\n", op, path()); } } MessageTreeDatabaseObject * MessageTreeDatabasePeerSession :: GetDatabaseForNodePath(const String & nodePath, String * optRetRelativePath) const { uint32 closestDist = MUSCLE_NO_LIMIT; MessageTreeDatabaseObject * ret = NULL; String closestSubpath, temp; const uint32 numDBs = GetPeerSettings().GetNumDatabases(); for (uint32 i=0; i<numDBs; i++) { MessageTreeDatabaseObject * nextDB = dynamic_cast<MessageTreeDatabaseObject *>(GetDatabaseObject(i)); if (nextDB) { const int32 dist = nextDB->GetDatabaseSubpath(nodePath, &temp); if ((dist >= 0)&&(((uint32)dist) < closestDist)) { ret = nextDB; closestDist = dist; closestSubpath = temp; } } } if (optRetRelativePath) *optRetRelativePath = closestSubpath; return ret; } Hashtable<MessageTreeDatabaseObject *, String> MessageTreeDatabasePeerSession :: GetDatabasesForNodePath(const String & nodePath) const { Hashtable<MessageTreeDatabaseObject *, String> ret; String temp; const uint32 numDBs = GetPeerSettings().GetNumDatabases(); for (uint32 i=0; i<numDBs; i++) { MessageTreeDatabaseObject * nextDB = dynamic_cast<MessageTreeDatabaseObject *>(GetDatabaseObject(i)); if ((nextDB)&&(nextDB->GetDatabaseSubpath(nodePath, &temp) >= 0)) (void) ret.Put(nextDB, temp); } return ret; } ConstMessageRef MessageTreeDatabasePeerSession :: SeniorUpdateLocalDatabase(uint32 whichDatabase, uint32 & dbChecksum, const ConstMessageRef & seniorDoMsg) { switch(seniorDoMsg()->what) { case MTDPS_COMMAND_PINGSENIORPEER: HandleSeniorPeerPingMessage(whichDatabase, seniorDoMsg); return seniorDoMsg; break; default: return ZGDatabasePeerSession::SeniorUpdateLocalDatabase(whichDatabase, dbChecksum, seniorDoMsg); } } status_t MessageTreeDatabasePeerSession :: JuniorUpdateLocalDatabase(uint32 whichDatabase, uint32 & dbChecksum, const ConstMessageRef & juniorDoMsg) { switch(juniorDoMsg()->what) { case MTDPS_COMMAND_PINGSENIORPEER: HandleSeniorPeerPingMessage(whichDatabase, juniorDoMsg); return B_NO_ERROR; default: return ZGDatabasePeerSession::JuniorUpdateLocalDatabase(whichDatabase, dbChecksum, juniorDoMsg); } } void MessageTreeDatabasePeerSession :: HandleSeniorPeerPingMessage(uint32 whichDatabase, const ConstMessageRef & msg) { const ZGPeerID sourcePeerID = msg()->GetFlat<ZGPeerID>(MTDPS_NAME_SOURCE); TreeGatewayFlags flags = msg()->GetFlat<TreeGatewayFlags>(MTDPS_NAME_FLAGS); if ((flags.IsBitSet(TREE_GATEWAY_FLAG_NOREPLY) == false)&&(sourcePeerID == GetLocalPeerID())) TreeSeniorPeerPonged(msg()->GetStringReference(MTDPS_NAME_TAG), whichDatabase); } status_t MessageTreeDatabasePeerSession :: GetUnusedNodeID(const String & path, uint32 & retID) { const DataNode * node = GetDataNode(path); if (node == NULL) { // If there is no parent node currently, demand-create it MessageRef emptyRef(GetMessageFromPool()); MRETURN_OOM_ON_NULL(emptyRef()); MRETURN_ON_ERROR(SetDataNode(path, emptyRef)); return GetUnusedNodeID(path, retID); } const uint32 NUM_NODE_IDS = 100000; // chosen arbitrarily uint32 nextID = (node->GetMaxKnownChildIDHint()%NUM_NODE_IDS); for (uint32 i=0; i<NUM_NODE_IDS; i++) { char temp[32]; muscleSprintf(temp, "I" UINT32_FORMAT_SPEC, nextID); if ((node->HasChild(&temp[1]))||(node->HasChild(temp))) nextID = (nextID+1)%NUM_NODE_IDS; else { retID = nextID; return B_NO_ERROR; } } LogTime(MUSCLE_LOG_CRITICALERROR, "GetUnusedNodeID(): Could not find available child ID for node path [%s]!\n", path()); return B_ERROR("Node IDs exhausted"); } ServerSideMessageTreeSession * MessageTreeDatabasePeerSession :: GetActiveServerSideMessageTreeSession() const { for (HashtableIterator<const String *, AbstractReflectSessionRef> iter(GetSessions()); iter.HasData(); iter++) { ServerSideMessageTreeSession * ssmts = dynamic_cast<ServerSideMessageTreeSession *>(iter.GetValue()()); if ((ssmts)&&(ssmts->IsInMessageReceivedFromGateway())) return ssmts; } return NULL; } void MessageTreeDatabasePeerSession :: ServerSideMessageTreeSessionIsDetaching(ServerSideMessageTreeSession * clientSession) { const uint32 numDBs = GetPeerSettings().GetNumDatabases(); for (uint32 i=0; i<numDBs; i++) { ClientDataMessageTreeDatabaseObject * clientDB = dynamic_cast<ClientDataMessageTreeDatabaseObject *>(GetDatabaseObject(i)); if (clientDB) clientDB->ServerSideMessageTreeSessionIsDetaching(clientSession); } } const String & MessageTreeDatabasePeerSession :: GetCurrentOpTagForNodePath(const String & nodePath) const { const MessageTreeDatabaseObject * mtDB = GetDatabaseForNodePath(nodePath, NULL); return mtDB ? mtDB->GetCurrentOpTag() : GetEmptyString(); } int MessageTreeDatabasePeerSession :: GetSubscribedSessionsCallback(DataNode & node, void * ud) { Hashtable<ServerSideMessageTreeSession *, Void> & results = *(static_cast<Hashtable<ServerSideMessageTreeSession *, Void> *>(ud)); for (HashtableIterator<uint32, uint32> iter(node.GetSubscribers()); iter.HasData(); iter++) { ServerSideMessageTreeSession * ssmts = dynamic_cast<ServerSideMessageTreeSession *>(GetSession(iter.GetKey())()); if (ssmts) (void) results.PutWithDefault(ssmts); } return node.GetDepth(); } void MessageTreeDatabasePeerSession :: MessageReceivedFromPeer(const ZGPeerID & fromPeerID, const MessageRef & msg) { switch(msg()->what) { case MTDPS_COMMAND_MESSAGETOSENIORPEER: if (IAmTheSeniorPeer()) { MessageRef payload = msg()->GetMessage(MTDPS_NAME_PAYLOAD); const ZGPeerID sourcePeerID = msg()->GetFlat<ZGPeerID>(MTDPS_NAME_SOURCE); const uint32 whichDB = msg()->GetInt32(MTDPS_NAME_WHICHDB); const String & tag = msg()->GetStringReference(MTDPS_NAME_TAG); if (payload()) { MessageReceivedFromTreeGatewaySubscriber(sourcePeerID, payload, whichDB, tag); } else LogTime(MUSCLE_LOG_ERROR, "Peer [%s] Received MTDPS_COMMAND_MESSAGETOSENIORPEER, but it has no payload!\n", GetLocalPeerID().ToString()()); } else LogTime(MUSCLE_LOG_ERROR, "Peer [%s] Received MTDPS_COMMAND_MESSAGETOSENIORPEER, but I am not the senior peer!\n", GetLocalPeerID().ToString()()); break; case MTDPS_COMMAND_MESSAGEFROMSENIORPEER: { MessageRef payload = msg()->GetMessage(MTDPS_NAME_PAYLOAD); //const ZGPeerID sourcePeerID = msg()->GetFlat<ZGPeerID>(MTDPS_NAME_SOURCE); const uint32 whichDB = msg()->GetInt32(MTDPS_NAME_WHICHDB); const String & tag = msg()->GetStringReference(MTDPS_NAME_TAG); if (payload()) { MessageReceivedFromTreeSeniorPeer(whichDB, tag, payload); } else LogTime(MUSCLE_LOG_ERROR, "Peer [%s] Received MTDPS_COMMAND_MESSAGETOSENIORPEER, but it has no payload!\n", GetLocalPeerID().ToString()()); } break; case MTDPS_COMMAND_MESSAGETOSUBSCRIBER: { QueryFilterRef qfRef; { MessageRef qfMsg = msg()->GetMessage(MTDPS_NAME_FILTER); if (qfMsg()) qfRef = GetGlobalQueryFilterFactory()()->CreateQueryFilter(*qfMsg()); } MessageRef payload = msg()->GetMessage(MTDPS_NAME_PAYLOAD); const String & path = msg()->GetStringReference(MTDPS_NAME_PATH); const String & tag = msg()->GetStringReference(MTDPS_NAME_TAG); if (payload()) { String suffix; // will contain everything but the {peerID}: const ZGPeerID targetPeerID = GetPeerIDFromReturnAddress(path, &suffix); if (targetPeerID.IsValid()) { if (targetPeerID == GetLocalPeerID()) { MessageReceivedFromSubscriber(suffix, payload, tag); } else LogTime(MUSCLE_LOG_ERROR, "Peer [%s] Received MTDPS_COMMAND_MESSAGETOSUBSCRIBER addressed to peer [%s]!\n", GetLocalPeerID().ToString()(), targetPeerID.ToString()()); } else { // We want to forward this Message on to any local clients that are subscribed to any nodes matched by (path) const bool isGlobal = path.StartsWith('/'); NodePathMatcher matcher; (void) matcher.PutPathString(isGlobal?path.Substring(1):path, qfRef); Hashtable<ServerSideMessageTreeSession *, Void> subscribedSessions; (void) matcher.DoTraversal((PathMatchCallback) GetSubscribedSessionsCallbackFunc, this, isGlobal?GetGlobalRoot():*GetSessionNode()(), true, &subscribedSessions); for (HashtableIterator<ServerSideMessageTreeSession *, Void> iter(subscribedSessions); iter.HasData(); iter++) iter.GetKey()->MessageReceivedFromSubscriber(path, payload, tag); } } else LogTime(MUSCLE_LOG_ERROR, "Peer [%s] Received MTDPS_COMMAND_MESSAGETOSUBSCRIBER, but it has no payload!\n", GetLocalPeerID().ToString()()); } break; default: ZGDatabasePeerSession::MessageReceivedFromPeer(fromPeerID, msg); break; } } void MessageTreeDatabasePeerSession :: MessageReceivedFromTreeGatewaySubscriber(const ZGPeerID & fromPeerID, const MessageRef & payload, uint32 whichDB, const String & tag) { // Default implementation will try to pass the Message on to one of our Database objects MessageTreeDatabaseObject * db = dynamic_cast<MessageTreeDatabaseObject *>(GetDatabaseObject(whichDB)); if (db) db->MessageReceivedFromTreeGatewaySubscriber(fromPeerID, payload, tag); else LogTime(MUSCLE_LOG_ERROR, "MessageTreeDatabasePeerSession::MessageReceivedFromTreeGatewaySubscriber: Database #" UINT32_FORMAT_SPEC " is not a MessageTreeDatabaseObject!\n"); } status_t MessageTreeDatabasePeerSession :: SendMessageToTreeGatewaySubscriber(const ZGPeerID & toPeerID, const String & tag, const MessageRef & payload, int32 optWhichDB) { MessageRef replyMsg = GetMessageFromPool(MTDPS_COMMAND_MESSAGEFROMSENIORPEER); MRETURN_OOM_ON_NULL(replyMsg()); const status_t ret = replyMsg()->AddMessage(MTDPS_NAME_PAYLOAD, payload) | replyMsg()->CAddFlat( MTDPS_NAME_SOURCE, GetLocalPeerID()) | replyMsg()->CAddInt32( MTDPS_NAME_WHICHDB, optWhichDB) | replyMsg()->CAddString(MTDPS_NAME_TAG, tag); return ret.IsOK() ? SendUnicastUserMessageToPeer(toPeerID, replyMsg) : ret; } ConstMessageRef MessageTreeDatabasePeerSession :: TreeGateway_GetGestaltMessage() const { return _gestaltMessage; } status_t MessageTreeDatabasePeerSession :: ConvertPathToSessionRelative(String & path) const { if (GetPathDepth(path()) >= NODE_DEPTH_USER) { path = GetPathClause(NODE_DEPTH_USER, path()); return B_NO_ERROR; } return B_BAD_ARGUMENT; } void MessageTreeDatabasePeerSession :: MessageReceivedFromSession(AbstractReflectSession & from, const MessageRef & msg, void * userData) { if ((&from == this)&&(_inLocalRequestNestCount.IsInBatch())) { // Gotta handle some replies locally as they need to go back to our MuxTreeGateway for local distribution bool handled = true; switch(msg()->what) { case PR_RESULT_DATATREES: { String opTag; if (msg()->FindString(PR_NAME_TREE_REQUEST_ID, opTag).IsOK()) (void) msg()->RemoveName(PR_NAME_TREE_REQUEST_ID); _muxGateway.SubtreesRequestResultReturned(opTag, msg); } break; case PR_RESULT_DATAITEMS: { // Handle notifications of removed nodes { String nodePath; for (int i=0; msg()->FindString(PR_NAME_REMOVED_DATAITEMS, i, nodePath).IsOK(); i++) if (ConvertPathToSessionRelative(nodePath).IsOK()) _muxGateway.TreeNodeUpdated(nodePath, MessageRef(), GetEmptyString()); } // Handle notifications of added/updated nodes { uint32 currentFieldNameIndex = 0; MessageRef nodeRef; for (MessageFieldNameIterator iter = msg()->GetFieldNameIterator(); iter.HasData(); iter++,currentFieldNameIndex++) { String nodePath = iter.GetFieldName(); if (ConvertPathToSessionRelative(nodePath).IsOK()) for (uint32 i=0; msg()->FindMessage(iter.GetFieldName(), i, nodeRef).IsOK(); i++) _muxGateway.TreeNodeUpdated(nodePath, nodeRef, GetEmptyString()); } } } break; case PR_RESULT_INDEXUPDATED: { // Handle notifications of node-index changes uint32 currentFieldNameIndex = 0; for (MessageFieldNameIterator iter = msg()->GetFieldNameIterator(); iter.HasData(); iter++,currentFieldNameIndex++) { String sessionRelativePath = iter.GetFieldName(); if (ConvertPathToSessionRelative(sessionRelativePath).IsOK()) { const char * indexCmd; for (int i=0; msg()->FindString(iter.GetFieldName(), i, &indexCmd).IsOK(); i++) { const char * colonAt = strchr(indexCmd, ':'); char c = indexCmd[0]; switch(c) { case INDEX_OP_CLEARED: _muxGateway.TreeNodeIndexCleared( sessionRelativePath, GetEmptyString()); break; case INDEX_OP_ENTRYINSERTED: _muxGateway.TreeNodeIndexEntryInserted(sessionRelativePath, atoi(&indexCmd[1]), colonAt?(colonAt+1):"", GetEmptyString()); break; case INDEX_OP_ENTRYREMOVED: _muxGateway.TreeNodeIndexEntryRemoved( sessionRelativePath, atoi(&indexCmd[1]), colonAt?(colonAt+1):"", GetEmptyString()); break; } } } } } break; default: handled = false; break; } if (handled) return; } ZGDatabasePeerSession::MessageReceivedFromSession(from, msg, userData); } }; // end namespace zg
45.639077
263
0.719527
ruurdadema
3e6cc7fe0dc2e221966c3fa05918c02af18568f6
475
hpp
C++
core/src/main/cpp/include/render/copier/ICopierSurface.hpp
caolongcl/OpenImage
d29e0309bc35ff1766e0c81bfba82b185a7aabb6
[ "BSD-3-Clause" ]
2
2021-09-16T15:14:39.000Z
2021-09-17T14:39:52.000Z
core/src/main/cpp/include/render/copier/ICopierSurface.hpp
caolongcl/OpenImage
d29e0309bc35ff1766e0c81bfba82b185a7aabb6
[ "BSD-3-Clause" ]
null
null
null
core/src/main/cpp/include/render/copier/ICopierSurface.hpp
caolongcl/OpenImage
d29e0309bc35ff1766e0c81bfba82b185a7aabb6
[ "BSD-3-Clause" ]
null
null
null
// // Created by caolong on 2020/8/13. // #pragma once namespace clt { /** * 定义 Copier 输出的类型,如输出到 ANativeWindow、Texture、pbbuffer * @tparam Args */ template<typename ...Args> struct ICopierSurface { ICopierSurface() = default; virtual ~ICopierSurface() = default; /** * 注册Copier的输出Target * @param args */ virtual void RegisterSurface(Args ...args) = 0; /** * Copier输出操作 */ virtual void Render() = 0; }; }
15.833333
56
0.589474
caolongcl
3e6cddb7de4b477db55272748f0d3824132ccb20
6,626
cpp
C++
external/Magnum/ArcBall.cpp
LoganBarnes/ltb-gvs
b1178e31c35aece434c7d47af955275fca9bb2a5
[ "MIT" ]
1
2020-04-04T16:57:25.000Z
2020-04-04T16:57:25.000Z
external/Magnum/ArcBall.cpp
LoganBarnes/ltb-gvs
b1178e31c35aece434c7d47af955275fca9bb2a5
[ "MIT" ]
null
null
null
external/Magnum/ArcBall.cpp
LoganBarnes/ltb-gvs
b1178e31c35aece434c7d47af955275fca9bb2a5
[ "MIT" ]
null
null
null
/* This file is part of Magnum. Original authors — credit is appreciated but not required: 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019 — Vladimír Vondruš <mosra@centrum.cz> 2020 — Nghia Truong <nghiatruong.vn@gmail.com> This is free and unencumbered software released into the public domain. Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a compiled binary, for any purpose, commercial or non-commercial, and by any means. In jurisdictions that recognize copyright laws, the author or authors of this software dedicate any and all copyright interest in the software to the public domain. We make this dedication for the benefit of the public at large and to the detriment of our heirs and successors. We intend this dedication to be an overt act of relinquishment in perpetuity of all present and future rights to this software under copyright law. 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 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 "ArcBall.h" #include <Magnum/Math/Matrix3.h> namespace Magnum { namespace { /* Project a point in NDC onto the arcball sphere */ Quaternion ndcToArcBall(const Vector2& p) { const Float dist = Math::dot(p, p); /* Point is on sphere */ if (dist <= 1.0f) return {{p.x(), p.y(), Math::sqrt(1.0f - dist)}, 0.0f}; /* Point is outside sphere */ else { const Vector2 proj = p.normalized(); return {{proj.x(), proj.y(), 0.0f}, 0.0f}; } } } // namespace ArcBall::ArcBall( const Vector3& eye, const Vector3& viewCenter, const Vector3& upDir, Deg fov, const Vector2i& windowSize) : _fov{fov}, _windowSize{windowSize} { setViewParameters(eye, viewCenter, upDir); } void ArcBall::setViewParameters(const Vector3& eye, const Vector3& viewCenter, const Vector3& upDir) { const Vector3 dir = viewCenter - eye; Vector3 zAxis = dir.normalized(); Vector3 xAxis = (Math::cross(zAxis, upDir.normalized())).normalized(); Vector3 yAxis = (Math::cross(xAxis, zAxis)).normalized(); xAxis = (Math::cross(zAxis, yAxis)).normalized(); _targetPosition = -viewCenter; _targetZooming = -dir.length(); _targetQRotation = Quaternion::fromMatrix(Matrix3x3{xAxis, yAxis, -zAxis}.transposed()).normalized(); _positionT0 = _currentPosition = _targetPosition; _zoomingT0 = _currentZooming = _targetZooming; _qRotationT0 = _currentQRotation = _targetQRotation; updateInternalTransformations(); } void ArcBall::reset() { _targetPosition = _positionT0; _targetZooming = _zoomingT0; _targetQRotation = _qRotationT0; } void ArcBall::setLagging(const Float lagging) { CORRADE_INTERNAL_ASSERT(lagging >= 0.0f && lagging < 1.0f); _lagging = lagging; } void ArcBall::initTransformation(const Vector2i& mousePos) { _prevMousePosNDC = screenCoordToNDC(mousePos); } void ArcBall::rotate(const Vector2i& mousePos) { const Vector2 mousePosNDC = screenCoordToNDC(mousePos); const Quaternion currentQRotation = ndcToArcBall(mousePosNDC); const Quaternion prevQRotation = ndcToArcBall(_prevMousePosNDC); _prevMousePosNDC = mousePosNDC; _targetQRotation = (currentQRotation * prevQRotation * _targetQRotation).normalized(); } void ArcBall::translate(const Vector2i& mousePos) { const Vector2 mousePosNDC = screenCoordToNDC(mousePos); const Vector2 translationNDC = mousePosNDC - _prevMousePosNDC; _prevMousePosNDC = mousePosNDC; translateDelta(translationNDC); } void ArcBall::translateDelta(const Vector2& translationNDC) { /* Half size of the screen viewport at the view center and perpendicular with the viewDir */ const Float hh = Math::abs(_targetZooming) * Math::tan(_fov * 0.5f); const Float hw = hh * Vector2{_windowSize}.aspectRatio(); _targetPosition += _inverseView.transformVector({translationNDC.x() * hw, translationNDC.y() * hh, 0.0f}); } void ArcBall::zoom(const Float delta) { _targetZooming += delta; } bool ArcBall::updateTransformation() { const Vector3 diffViewCenter = _targetPosition - _currentPosition; const Quaternion diffRotation = _targetQRotation - _currentQRotation; const Float diffZooming = _targetZooming - _currentZooming; const Float dViewCenter = Math::dot(diffViewCenter, diffViewCenter); const Float dRotation = Math::dot(diffRotation, diffRotation); const Float dZooming = diffZooming * diffZooming; /* Nothing change */ if (dViewCenter < 1.0e-10f && dRotation < 1.0e-10f && dZooming < 1.0e-10f) { return false; } /* Nearly done: just jump directly to the target */ if (dViewCenter < 1.0e-6f && dRotation < 1.0e-6f && dZooming < 1.0e-6f) { _currentPosition = _targetPosition; _currentQRotation = _targetQRotation; _currentZooming = _targetZooming; /* Interpolate between the current transformation and the target transformation */ } else { const Float t = 1 - _lagging; _currentPosition = Math::lerp(_currentPosition, _targetPosition, t); _currentZooming = Math::lerp(_currentZooming, _targetZooming, t); _currentQRotation = Math::slerpShortestPath(_currentQRotation, _targetQRotation, t); } updateInternalTransformations(); return true; } void ArcBall::resetViewCenter(const Vector3& viewCenter) { _targetPosition = -viewCenter; _currentPosition = _targetPosition; _currentZooming = _targetZooming; _currentQRotation = _targetQRotation; updateInternalTransformations(); } void ArcBall::updateInternalTransformations() { _view = DualQuaternion::translation(Vector3::zAxis(_currentZooming)) * DualQuaternion{_currentQRotation} * DualQuaternion::translation(_currentPosition); _inverseView = _view.inverted(); } Vector2 ArcBall::screenCoordToNDC(const Vector2i& mousePos) const { return {mousePos.x() * 2.0f / _windowSize.x() - 1.0f, 1.0f - 2.0f * mousePos.y() / _windowSize.y()}; } } // namespace Magnum
37.435028
110
0.698913
LoganBarnes
3e6d9d4c04c76f80c6642fd7f858b20ad2e1d3bc
6,215
hpp
C++
include/approx_rank.hpp
dominikkempa/psascan
d206aea99e0fe2130fcd0f726f1e0acb7699ebd6
[ "MIT" ]
3
2020-07-27T08:59:16.000Z
2021-05-29T23:42:15.000Z
include/approx_rank.hpp
dominikkempa/psascan
d206aea99e0fe2130fcd0f726f1e0acb7699ebd6
[ "MIT" ]
null
null
null
include/approx_rank.hpp
dominikkempa/psascan
d206aea99e0fe2130fcd0f726f1e0acb7699ebd6
[ "MIT" ]
null
null
null
/** * @file src/psascan_src/approx_rank.hpp * @section DESCRIPTION * * The approximate rank data structure. Based on the 'sparse-LF' * data structure described in: * * Dominik Kempa, Simon J. Puglisi: * Lempel-Ziv Factorization: Simple, Fast, Practical. * In Proc. ALENEX 2013, p. 103-112. * * @section LICENCE * * This file is part of pSAscan v0.1.1 * See: https://github.com/dominikkempa/psascan * * Copyright (C) 2014-2020 * Dominik Kempa <dominik.kempa (at) gmail.com> * Juha Karkkainen <juha.karkkainen (at) cs.helsinki.fi> * * 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 __SRC_PSASCAN_SRC_APPROX_RANK_HPP_INCLUDED #define __SRC_PSASCAN_SRC_APPROX_RANK_HPP_INCLUDED #include <thread> #include <algorithm> namespace psascan_private { template<long k_sampling_rate_log> class approx_rank { private: long *m_list_size; long **m_list; static const long k_sampling_rate; static const long k_sampling_rate_mask; public: long *m_count; private: static void compute_symbol_count_aux(const unsigned char *text, long beg, long end, long *symbol_count) { for (long j = beg; j < end; ++j) ++symbol_count[text[j]]; } static void compute_occ_list_aux(const unsigned char *text, long beg, long end, long *symbol_count, long **list) { // Compute where to start writing positions for each symbol. long *ptr = new long[256]; for (long c = 0; c < 256; ++c) ptr[c] = (symbol_count[c] + k_sampling_rate - 1) / k_sampling_rate; // Add occurrences in the block to the lists. for (long j = beg; j < end; ++j) { unsigned char c = text[j]; if (!((symbol_count[c]++) & k_sampling_rate_mask)) list[c][ptr[c]++] = j; } // Clean up. delete[] ptr; } public: approx_rank(const unsigned char *text, long length, long max_threads) { // Compute symbol counts in each block. long max_block_size = (length + max_threads - 1) / max_threads; long n_threads = (length + max_block_size - 1) / max_block_size; long **symbol_count = new long*[n_threads]; for (long j = 0; j < n_threads; ++j) { symbol_count[j] = new long[256]; std::fill(symbol_count[j], symbol_count[j] + 256, 0L); } std::thread **threads = new std::thread*[n_threads]; for (long t = 0; t < n_threads; ++t) { long block_beg = t * max_block_size; long block_end = std::min(block_beg + max_block_size, length); threads[t] = new std::thread(compute_symbol_count_aux, text, block_beg, block_end, symbol_count[t]); } for (long t = 0; t < n_threads; ++t) threads[t]->join(); for (long t = 0; t < n_threads; ++t) delete threads[t]; // Compute (exclusive) partial sums over symbol counts. m_count = new long[256]; std::fill(m_count, m_count + 256, 0L); long *temp_count = new long[256]; for (long i = 0; i < n_threads; ++i) { std::copy(symbol_count[i], symbol_count[i] + 256, temp_count); std::copy(m_count, m_count + 256, symbol_count[i]); for (long j = 0; j < 256; ++j) m_count[j] += temp_count[j]; } delete[] temp_count; // Compute sizes and allocate occurrences lists. m_list_size = new long[256]; m_list = new long*[256]; for (long i = 0; i < 256; ++i) { m_list_size[i] = (m_count[i] + k_sampling_rate - 1) / k_sampling_rate; if (m_list_size[i]) m_list[i] = new long[m_list_size[i]]; else m_list[i] = NULL; } for (long t = 0; t < n_threads; ++t) { long block_beg = t * max_block_size; long block_end = std::min(block_beg + max_block_size, length); threads[t] = new std::thread(compute_occ_list_aux, text, block_beg, block_end, symbol_count[t], m_list); } for (long t = 0; t < n_threads; ++t) threads[t]->join(); for (long t = 0; t < n_threads; ++t) delete threads[t]; delete[] threads; // Clean up. for (long j = 0; j < n_threads; ++j) delete[] symbol_count[j]; delete[] symbol_count; } inline long rank(long i, unsigned char c) const { if (i <= 0 || (!m_list_size[c]) || m_list[c][0] >= i) return 0L; long left = 0, right = m_list_size[c]; while (left + 1 != right) { // Invariant: the answer is in range [left..right). long mid = (left + right) / 2; if (m_list[c][mid] <= i) left = mid; else right = mid; } return (left << k_sampling_rate_log); } ~approx_rank() { delete[] m_count; delete[] m_list_size; for (long j = 0; j < 256; ++j) { if (m_list[j]) delete[] m_list[j]; } delete[] m_list; } }; template<long k_sampling_rate_log> const long approx_rank<k_sampling_rate_log>::k_sampling_rate = (1L << k_sampling_rate_log); template<long k_sampling_rate_log> const long approx_rank<k_sampling_rate_log>::k_sampling_rate_mask = (1L << k_sampling_rate_log) - 1; } // namespace psascan_private #endif // __PSASCAN_SRC_APPROX_RANK_HPP_INCLUDED
33.413978
100
0.634755
dominikkempa
3e6de2efb02f41b6f73ae733ad579e41df00b706
2,664
cpp
C++
src/qt/config.tests/unix/endian/endiantest.cpp
jefleponot/phantomjs
4333acfa798677ec895d73673898c3ffad36e4c0
[ "BSD-3-Clause" ]
25
2015-07-21T18:14:57.000Z
2021-02-21T10:00:48.000Z
src/qt/config.tests/unix/endian/endiantest.cpp
jefleponot/phantomjs
4333acfa798677ec895d73673898c3ffad36e4c0
[ "BSD-3-Clause" ]
3
2015-01-19T11:31:54.000Z
2015-07-01T13:28:48.000Z
src/qt/config.tests/unix/endian/endiantest.cpp
jefleponot/phantomjs
4333acfa798677ec895d73673898c3ffad36e4c0
[ "BSD-3-Clause" ]
9
2016-03-14T13:25:14.000Z
2021-02-21T10:09:22.000Z
/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of the config.tests of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** 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 Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/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 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ // "MostSignificantByteFirst" short msb_bigendian[] = { 0x0000, 0x4d6f, 0x7374, 0x5369, 0x676e, 0x6966, 0x6963, 0x616e, 0x7442, 0x7974, 0x6546, 0x6972, 0x7374, 0x0000 }; // "LeastSignificantByteFirst" short lsb_littleendian[] = { 0x0000, 0x654c, 0x7361, 0x5374, 0x6769, 0x696e, 0x6966, 0x6163, 0x746e, 0x7942, 0x6574, 0x6946, 0x7372, 0x0074, 0x0000 }; int main(int, char **) { // make sure the linker doesn't throw away the arrays void (*msb_bigendian_string)() = (void (*)())msb_bigendian; void (*lsb_littleendian_string)() = (void (*)())lsb_littleendian; (void)msb_bigendian_string(); (void)lsb_littleendian_string(); return msb_bigendian[1] == lsb_littleendian[1]; }
46.736842
150
0.701201
jefleponot
3e7135bdf8359b90b2f57048a52ce0deee945435
7,283
cpp
C++
src/server/request_handler.cpp
asaveljevs/osrm-backend
15f0ca8ddaa35c5b4d93c25afa72e81e1fb40c3e
[ "BSD-2-Clause" ]
13
2019-02-21T02:02:41.000Z
2021-09-09T13:49:31.000Z
src/server/request_handler.cpp
zhangdida/osrm-backend
1ba8aba4663590c5c53b3b0a9989e4fe605b45b8
[ "BSD-2-Clause" ]
288
2019-02-21T01:34:04.000Z
2021-03-27T12:19:10.000Z
src/server/request_handler.cpp
zhangdida/osrm-backend
1ba8aba4663590c5c53b3b0a9989e4fe605b45b8
[ "BSD-2-Clause" ]
4
2019-06-21T20:51:59.000Z
2021-01-13T09:22:24.000Z
#include "server/request_handler.hpp" #include "server/service_handler.hpp" #include "server/api/url_parser.hpp" #include "server/http/reply.hpp" #include "server/http/request.hpp" #include "util/json_renderer.hpp" #include "util/log.hpp" #include "util/string_util.hpp" #include "util/timing_util.hpp" #include "util/typedefs.hpp" #include "engine/status.hpp" #include "osrm/osrm.hpp" #include "util/json_container.hpp" #include <boost/iostreams/copy.hpp> #include <boost/iostreams/filter/gzip.hpp> #include <boost/iostreams/filtering_streambuf.hpp> #include <ctime> #include <algorithm> #include <iostream> #include <iterator> #include <string> #include <thread> namespace osrm { namespace server { void RequestHandler::RegisterServiceHandler( std::unique_ptr<ServiceHandlerInterface> service_handler_) { service_handler = std::move(service_handler_); } void RequestHandler::HandleRequest(const http::request &current_request, http::reply &current_reply) { if (!service_handler) { current_reply = http::reply::stock_reply(http::reply::internal_server_error); util::Log(logWARNING) << "No service handler registered." << std::endl; return; } const auto tid = std::this_thread::get_id(); // parse command try { TIMER_START(request_duration); std::string request_string; util::URIDecode(current_request.uri, request_string); util::Log(logDEBUG) << "[req][" << tid << "] " << request_string; auto api_iterator = request_string.begin(); auto maybe_parsed_url = api::parseURL(api_iterator, request_string.end()); ServiceHandler::ResultT result; // check if the was an error with the request if (maybe_parsed_url && api_iterator == request_string.end()) { const engine::Status status = service_handler->RunQuery(*std::move(maybe_parsed_url), result); if (status != engine::Status::Ok) { // 4xx bad request return code current_reply.status = http::reply::bad_request; } else { BOOST_ASSERT(status == engine::Status::Ok); } } else { const auto position = std::distance(request_string.begin(), api_iterator); BOOST_ASSERT(position >= 0); const auto context_begin = request_string.begin() + ((position < 3) ? 0 : (position - 3UL)); BOOST_ASSERT(context_begin >= request_string.begin()); const auto context_end = request_string.begin() + std::min<std::size_t>(position + 3UL, request_string.size()); BOOST_ASSERT(context_end <= request_string.end()); std::string context(context_begin, context_end); current_reply.status = http::reply::bad_request; result = util::json::Object(); auto &json_result = result.get<util::json::Object>(); json_result.values["code"] = "InvalidUrl"; json_result.values["message"] = "URL string malformed close to position " + std::to_string(position) + ": \"" + context + "\""; } current_reply.headers.emplace_back("Access-Control-Allow-Origin", "*"); current_reply.headers.emplace_back("Access-Control-Allow-Methods", "GET"); current_reply.headers.emplace_back("Access-Control-Allow-Headers", "X-Requested-With, Content-Type"); if (result.is<util::json::Object>()) { current_reply.headers.emplace_back("Content-Type", "application/json; charset=UTF-8"); current_reply.headers.emplace_back("Content-Disposition", "inline; filename=\"response.json\""); util::json::render(current_reply.content, result.get<util::json::Object>()); } else if (result.is<flatbuffers::FlatBufferBuilder>()) { auto &buffer = result.get<flatbuffers::FlatBufferBuilder>(); current_reply.content.resize(buffer.GetSize()); std::copy(buffer.GetBufferPointer(), buffer.GetBufferPointer() + buffer.GetSize(), current_reply.content.begin()); current_reply.headers.emplace_back( "Content-Type", "application/x-flatbuffers;schema=osrm.engine.api.fbresult"); } else { BOOST_ASSERT(result.is<std::string>()); current_reply.content.resize(result.get<std::string>().size()); std::copy(result.get<std::string>().cbegin(), result.get<std::string>().cend(), current_reply.content.begin()); current_reply.headers.emplace_back("Content-Type", "application/x-protobuf"); } // set headers current_reply.headers.emplace_back("Content-Length", std::to_string(current_reply.content.size())); if (!std::getenv("DISABLE_ACCESS_LOGGING")) { // deactivated as GCC apparently does not implement that, not even in 4.9 // std::time_t t = std::time(nullptr); // util::Log() << std::put_time(std::localtime(&t), "%m-%d-%Y // %H:%M:%S") << // " " << current_request.endpoint.to_string() << " " << // current_request.referrer << ( 0 == current_request.referrer.length() ? "- " :" ") // << // current_request.agent << ( 0 == current_request.agent.length() ? "- " :" ") << // request; time_t ltime; struct tm *time_stamp; TIMER_STOP(request_duration); ltime = time(nullptr); time_stamp = localtime(&ltime); // log timestamp util::Log() << (time_stamp->tm_mday < 10 ? "0" : "") << time_stamp->tm_mday << "-" << (time_stamp->tm_mon + 1 < 10 ? "0" : "") << (time_stamp->tm_mon + 1) << "-" << 1900 + time_stamp->tm_year << " " << (time_stamp->tm_hour < 10 ? "0" : "") << time_stamp->tm_hour << ":" << (time_stamp->tm_min < 10 ? "0" : "") << time_stamp->tm_min << ":" << (time_stamp->tm_sec < 10 ? "0" : "") << time_stamp->tm_sec << " " << TIMER_MSEC(request_duration) << "ms " << current_request.endpoint.to_string() << " " << current_request.referrer << (0 == current_request.referrer.length() ? "- " : " ") << current_request.agent << (0 == current_request.agent.length() ? "- " : " ") << current_reply.status << " " // << request_string; } } catch (const std::exception &e) { current_reply = http::reply::stock_reply(http::reply::internal_server_error); util::Log(logWARNING) << "[server error][" << tid << "] code: " << e.what() << ", uri: " << current_request.uri; } } } }
40.016484
100
0.552931
asaveljevs
3e7850076ab56ccdc70fa909eac1b344907011cc
1,581
hpp
C++
externals/boost/boost/algorithm/cxx17/exclusive_scan.hpp
YuukiTsuchida/v8_embeded
c6e18f4e91fcc50607f8e3edc745a3afa30b2871
[ "MIT" ]
995
2018-06-22T10:39:18.000Z
2022-03-25T01:22:14.000Z
jeff/common/include/boost/algorithm/cxx17/exclusive_scan.hpp
jeffphi/advent-of-code-2018
8e54bd23ebfe42fcbede315f0ab85db903551532
[ "MIT" ]
32
2018-06-23T14:19:37.000Z
2022-03-29T10:20:37.000Z
jeff/common/include/boost/algorithm/cxx17/exclusive_scan.hpp
jeffphi/advent-of-code-2018
8e54bd23ebfe42fcbede315f0ab85db903551532
[ "MIT" ]
172
2018-06-22T11:12:00.000Z
2022-03-29T07:44:33.000Z
/* Copyright (c) Marshall Clow 2017. 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) */ /// \file exclusive_scan.hpp /// \brief ??? /// \author Marshall Clow #ifndef BOOST_ALGORITHM_EXCLUSIVE_SCAN_HPP #define BOOST_ALGORITHM_EXCLUSIVE_SCAN_HPP #include <functional> // for std::plus #include <iterator> // for std::iterator_traits #include <boost/range/begin.hpp> #include <boost/range/end.hpp> #include <boost/range/value_type.hpp> namespace boost { namespace algorithm { template<class InputIterator, class OutputIterator, class T, class BinaryOperation> OutputIterator exclusive_scan(InputIterator first, InputIterator last, OutputIterator result, T init, BinaryOperation bOp) { if (first != last) { T saved = init; do { init = bOp(init, *first); *result = saved; saved = init; ++result; } while (++first != last); } return result; } template<class InputIterator, class OutputIterator, class T> OutputIterator exclusive_scan(InputIterator first, InputIterator last, OutputIterator result, T init) { typedef typename std::iterator_traits<InputIterator>::value_type VT; return boost::algorithm::exclusive_scan(first, last, result, init, std::plus<VT>()); } }} // namespace boost and algorithm #endif // BOOST_ALGORITHM_EXCLUSIVE_SCAN_HPP
29.830189
89
0.653384
YuukiTsuchida
3e7be9597a9a2ee11e5d9036937af8d798a59e1e
415
hpp
C++
Flappy-Bird-SFML-Clone-master/Code/STATE CREATION/9 - Game State/DEFINITIONS.hpp
Moklok/Flappy-Bird-SFML-Clone-master
7a1a0c1193503e899a243992a9a5a8980750f81e
[ "Apache-2.0" ]
43
2017-02-02T17:41:21.000Z
2022-02-21T14:50:02.000Z
Code/STATE CREATION/9 - Game State/DEFINITIONS.hpp
frankie111/Flappy-Bird-SFML-Clone
03b5c04de9b96531683115d61ec90df78d40d8e6
[ "Unlicense" ]
1
2019-10-29T08:26:46.000Z
2019-10-29T08:26:46.000Z
Code/STATE CREATION/9 - Game State/DEFINITIONS.hpp
frankie111/Flappy-Bird-SFML-Clone
03b5c04de9b96531683115d61ec90df78d40d8e6
[ "Unlicense" ]
78
2017-05-24T00:00:32.000Z
2021-11-27T08:59:59.000Z
#pragma once #define SCREEN_WIDTH 768 #define SCREEN_HEIGHT 1024 #define SPLASH_STATE_SHOW_TIME 3.0 #define SPLASH_SCENE_BACKGROUND_FILEPATH "Resources/res/Splash Background.png" #define MAIN_MENU_BACKGROUND_FILEPATH "Resources/res/sky.png" #define GAME_BACKGROUND_FILEPATH "Resources/res/sky.png" #define GAME_TITLE_FILEPATH "Resources/res/title.png" #define PLAY_BUTTON_FILEPATH "Resources/res/PlayButton.png"
31.923077
78
0.843373
Moklok
3e7c6908b4d1373f8c6f9b153c02de7a191d3185
441
cpp
C++
src/lib/zap/zap/layouts/cbuild.cpp
chybz/zap
ccc67d85def09faa962e44b9e36ca414207d4ec3
[ "MIT" ]
null
null
null
src/lib/zap/zap/layouts/cbuild.cpp
chybz/zap
ccc67d85def09faa962e44b9e36ca414207d4ec3
[ "MIT" ]
null
null
null
src/lib/zap/zap/layouts/cbuild.cpp
chybz/zap
ccc67d85def09faa962e44b9e36ca414207d4ec3
[ "MIT" ]
null
null
null
#include <zap/layouts/cbuild.hpp> namespace zap::layouts { static zap::string_map cbuild_sub_dirs = { { "src", "sources" }, // base directory for all sub directories below { "inc", "include" }, { "bin", "binaries" }, { "lib", "libraries" }, { "mod", "plugins" }, { "tst", "tests" } }; cbuild::cbuild(const std::string& project_dir) : app("cbuild project", project_dir, cbuild_sub_dirs) {} cbuild::~cbuild() {} }
20.045455
73
0.609977
chybz
3e8021710a0df38f96ac4e1c0a3ef3ad8723e0f9
4,796
cpp
C++
folly/futures/test/BarrierTest.cpp
agenih/facebook
b3141b5d9af8de15dc2247fda265534183ca5f0d
[ "Apache-2.0" ]
2
2021-06-29T13:42:22.000Z
2021-09-06T10:57:34.000Z
folly/futures/test/BarrierTest.cpp
agenih/facebook
b3141b5d9af8de15dc2247fda265534183ca5f0d
[ "Apache-2.0" ]
null
null
null
folly/futures/test/BarrierTest.cpp
agenih/facebook
b3141b5d9af8de15dc2247fda265534183ca5f0d
[ "Apache-2.0" ]
5
2021-06-29T13:42:26.000Z
2022-02-08T02:41:34.000Z
/* * Copyright 2015-present Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <folly/futures/Barrier.h> #include <atomic> #include <condition_variable> #include <mutex> #include <folly/Random.h> #include <folly/portability/GTest.h> #include <glog/logging.h> namespace folly { namespace futures { namespace test { TEST(BarrierTest, Simple) { constexpr uint32_t numThreads = 10; std::mutex mutex; std::condition_variable b1DoneCond; std::condition_variable b2DoneCond; std::atomic<uint32_t> b1TrueSeen(0); std::atomic<uint32_t> b1Passed(0); std::atomic<uint32_t> b2TrueSeen(0); std::atomic<uint32_t> b2Passed(0); Barrier barrier(numThreads + 1); std::vector<std::thread> threads; threads.reserve(numThreads); for (uint32_t i = 0; i < numThreads; ++i) { threads.emplace_back([&] () { barrier.wait() .then( [&] (bool v) { std::unique_lock<std::mutex> lock(mutex); b1TrueSeen += uint32_t(v); if (++b1Passed == numThreads) { b1DoneCond.notify_one(); } return barrier.wait(); }) .then( [&] (bool v) { std::unique_lock<std::mutex> lock(mutex); b2TrueSeen += uint32_t(v); if (++b2Passed == numThreads) { b2DoneCond.notify_one(); } }) .get(); }); } /* sleep override */ std::this_thread::sleep_for(std::chrono::milliseconds(50)); EXPECT_EQ(0, b1Passed); EXPECT_EQ(0, b1TrueSeen); b1TrueSeen += barrier.wait().get(); { std::unique_lock<std::mutex> lock(mutex); while (b1Passed != numThreads) { b1DoneCond.wait(lock); } EXPECT_EQ(1, b1TrueSeen); } /* sleep override */ std::this_thread::sleep_for(std::chrono::milliseconds(50)); EXPECT_EQ(0, b2Passed); EXPECT_EQ(0, b2TrueSeen); b2TrueSeen += barrier.wait().get(); { std::unique_lock<std::mutex> lock(mutex); while (b2Passed != numThreads) { b2DoneCond.wait(lock); } EXPECT_EQ(1, b2TrueSeen); } for (auto& t : threads) { t.join(); } } TEST(BarrierTest, Random) { // Create numThreads threads. // // Each thread repeats the following numIterations times: // - grab a randomly chosen number of futures from the barrier, waiting // for a short random time between each // - wait for all futures to complete // - record whether the one future returning true was seen among them // // At the end, we verify that exactly one future returning true was seen // for each iteration. static constexpr uint32_t numIterations = 1; auto numThreads = folly::Random::rand32(30, 91); struct ThreadInfo { ThreadInfo() { } std::thread thread; uint32_t iteration = 0; uint32_t numFutures; std::vector<uint32_t> trueSeen; }; std::vector<ThreadInfo> threads; threads.resize(numThreads); uint32_t totalFutures = 0; for (auto& tinfo : threads) { tinfo.numFutures = folly::Random::rand32(100); tinfo.trueSeen.resize(numIterations); totalFutures += tinfo.numFutures; } Barrier barrier(totalFutures); for (auto& tinfo : threads) { auto pinfo = &tinfo; tinfo.thread = std::thread([pinfo, &barrier] { std::vector<folly::Future<bool>> futures; futures.reserve(pinfo->numFutures); for (uint32_t i = 0; i < numIterations; ++i, ++pinfo->iteration) { futures.clear(); for (uint32_t j = 0; j < pinfo->numFutures; ++j) { futures.push_back(barrier.wait()); auto nanos = folly::Random::rand32(10 * 1000 * 1000); /* sleep override */ std::this_thread::sleep_for(std::chrono::nanoseconds(nanos)); } auto results = folly::collect(futures).get(); pinfo->trueSeen[i] = std::count(results.begin(), results.end(), true); } }); } for (auto& tinfo : threads) { tinfo.thread.join(); EXPECT_EQ(numIterations, tinfo.iteration); } for (uint32_t i = 0; i < numIterations; ++i) { uint32_t trueCount = 0; for (auto& tinfo : threads) { trueCount += tinfo.trueSeen[i]; } EXPECT_EQ(1, trueCount); } } } // namespace test } // namespace futures } // namespace folly
27.563218
78
0.626772
agenih
3e8381b3759e54824b6a21c1506a2c0c6f9b3273
1,526
cpp
C++
chapter9/t9.22.cpp
xflcx1991/c_plus_plus_primer_exercise
3904fc936c14c6959968eb6d681f3151a72ccc44
[ "MulanPSL-1.0" ]
1
2020-02-24T07:54:44.000Z
2020-02-24T07:54:44.000Z
chapter9/t9.22.cpp
xflcx1991/c_plus_plus_primer_exercise
3904fc936c14c6959968eb6d681f3151a72ccc44
[ "MulanPSL-1.0" ]
null
null
null
chapter9/t9.22.cpp
xflcx1991/c_plus_plus_primer_exercise
3904fc936c14c6959968eb6d681f3151a72ccc44
[ "MulanPSL-1.0" ]
null
null
null
/************************************************************************************* * Copyright (c) 2019 xffish * c_plus_plus_primer_exercise is licensed under Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * http://license.coscl.org.cn/MulanPSL2 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. *************************************************************************************/ //这是一个死循环,改法见下面。 //另外在循环中向一个vector插入元素会使所有指向容器的迭代器失效 P305 下方 //我假设原题是想在前半段找一个数,如果找到了,就在它前面插入一个两倍大小的数,这个前半段得始终不变,所以引入distance //通过对distance的修改,使得原有的mid一直指向原有的中间的那个数 #include <iostream> #include <vector> using std::vector; using std::cout; using std::endl; int main() { vector<int> iv = { 0, 1, 2, 100, 4, 100, 6, 7, 8, 100, 9, 10, }; vector<int>::iterator iter = iv.begin(), mid = iv.begin() + iv.size() / 2; int distance = mid - iter; //确保mid始终指向原有的元素 int some_val = 100; while (iter != mid) { if (*iter == some_val) { iter = iv.insert(iter, 2 * some_val); ++distance; mid = iv.begin() + distance; ++iter; } ++iter; } for (auto item : iv) { cout << item << " "; } cout << endl; return 0; }
29.921569
86
0.558322
xflcx1991
3e891fd6706112f0bc92fb9de968715f48fe85de
1,922
cpp
C++
src/RcppKyTea.cpp
paithiov909/RcppKyTea
eb3958bea4afd41cffad1003ab5d7c75a23f593e
[ "Apache-2.0" ]
null
null
null
src/RcppKyTea.cpp
paithiov909/RcppKyTea
eb3958bea4afd41cffad1003ab5d7c75a23f593e
[ "Apache-2.0" ]
null
null
null
src/RcppKyTea.cpp
paithiov909/RcppKyTea
eb3958bea4afd41cffad1003ab5d7c75a23f593e
[ "Apache-2.0" ]
null
null
null
// [[Rcpp::plugins(cpp11)]] // [[Rcpp::depends(RcppThread)]] #define R_NO_REMAP #define RCPPTHREAD_OVERRIDE_THREAD 1 #define HAVE_TR1_UNORDERED_MAP #define KYTEA_SAFE #include <Rcpp.h> #include <RcppThread.h> // #include <RcppParallel.h> #include "kytea/kytea.h" #include "kytea/kytea-struct.h" #include "kytea/string-util.h" using namespace Rcpp; using namespace kytea; // [[Rcpp::interfaces(r, cpp)]] // [[Rcpp::export]] List segment( const CharacterVector text, const std::string path ) { KyteaConfig * config = new KyteaConfig; config->setDebug(0); config->setEncoding("utf8"); Kytea kytea(config); /* Load a KyTea model from a model file this can be a binary or text model in any character encoding, it will be detected automatically. */ const char* file = R_ExpandFileName(path.c_str()); if (!file) { Rcerr << "Failed to open the specified file. Check file path." << std::endl; return R_NilValue; } Rcout << "Loading model..." << std::endl; kytea.readModel(file); StringUtilUtf8 util; std::vector< std::vector<std::string> > res; for ( R_len_t i = 0; i < text.size(); i++ ) { // check user interrupt (Ctrl+C). if (i % 1000 == 0) checkUserInterrupt(); const std::string tst = Rcpp::as<std::string>(text[i]); KyteaString surface_string = util.mapString(tst); KyteaSentence sentence(surface_string, util.normalize(surface_string)); kytea.calculateWS(sentence); for( int t = 0; t < config->getNumTags(); t++) { kytea.calculateTags(sentence, t); } const KyteaSentence::Words words = sentence.words; std::vector< std::string > analyzed; for ( int j = 0; j < (int)words.size(); j++ ) { analyzed.push_back(util.showString(words[j].surface)); } res.push_back(analyzed); } return List(wrap(res)); }
30.03125
84
0.631634
paithiov909
3e8e84fc8b2cdc4fac9131b30033694e88c65397
2,361
cpp
C++
test/transport/test-socket.cpp
bitboom/rmi
12e72cfae704780e59214c19fb5c15697f1eda21
[ "Apache-2.0" ]
1
2020-09-16T08:32:21.000Z
2020-09-16T08:32:21.000Z
test/transport/test-socket.cpp
bitboom/rmi
12e72cfae704780e59214c19fb5c15697f1eda21
[ "Apache-2.0" ]
null
null
null
test/transport/test-socket.cpp
bitboom/rmi
12e72cfae704780e59214c19fb5c15697f1eda21
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2018 Samsung Electronics Co., Ltd All Rights Reserved * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License */ /* * @file test-socket.cpp * @author Sangwan Kwon (sangwan.kwon@samsung.com) */ #include "transport/socket.hxx" #include <string> #include <vector> #include <limits> #include <thread> #include <chrono> #include <cstring> #include <gtest/gtest.h> using namespace rmi::transport; TEST(TRANSPORT, SOCKET_READ_WRITE) { std::string sockPath = "./sock"; Socket socket(sockPath); int input = std::numeric_limits<int>::max(); bool input2 = true; int output = 0; bool output2 = false; auto client = std::thread([&]() { std::this_thread::sleep_for(std::chrono::seconds(1)); // Send input to server. Socket connected = Socket::connect(sockPath); connected.send(&input); // Recv input2 from server. connected.recv(&output2); EXPECT_EQ(input2, output2); }); Socket accepted = socket.accept(); // Recv input from client. accepted.recv(&output); EXPECT_EQ(input, output); // Send input2 to client. accepted.send(&input2); if (client.joinable()) client.join(); } TEST(TRANSPORT, SOCKET_ABSTRACT) { std::string sockPath = "@sock"; Socket socket(sockPath); int input = std::numeric_limits<int>::max(); bool input2 = true; int output = 0; bool output2 = false; auto client = std::thread([&]() { std::this_thread::sleep_for(std::chrono::seconds(1)); // Send input to server. Socket connected = Socket::connect(sockPath); connected.send(&input); // Recv input2 from server. connected.recv(&output2); EXPECT_EQ(input2, output2); }); Socket accepted = socket.accept(); // Recv input from client. accepted.recv(&output); EXPECT_EQ(input, output); // Send input2 to client. accepted.send(&input2); if (client.joinable()) client.join(); }
22.065421
76
0.689962
bitboom
3e9073f78243e0da5f70256a9b8bd7bd4df984db
1,041
cpp
C++
labs/memory_bound/swmem_prefetch_1/validate.cpp
dendibakh/perf-ninja
9245372aab96fdc9cfa01b60986b6f806abdc0b2
[ "CC-BY-3.0" ]
472
2021-07-20T07:12:13.000Z
2022-03-31T08:51:32.000Z
labs/memory_bound/swmem_prefetch_1/validate.cpp
dendibakh/perf-ninja
9245372aab96fdc9cfa01b60986b6f806abdc0b2
[ "CC-BY-3.0" ]
24
2021-07-28T22:30:43.000Z
2022-03-30T08:51:14.000Z
labs/memory_bound/swmem_prefetch_1/validate.cpp
dendibakh/perf-ninja
9245372aab96fdc9cfa01b60986b6f806abdc0b2
[ "CC-BY-3.0" ]
45
2021-07-26T00:51:56.000Z
2022-03-28T02:47:16.000Z
#include "solution.hpp" #include <iostream> #include <memory> static int getSumOfDigits(int n) { int sum = 0; while (n != 0) { sum = sum + n % 10; n = n / 10; } return sum; } static int original_solution(const hash_map_t *hash_map, const std::vector<int> &lookups) { int result = 0; for (int val : lookups) { if (hash_map->find(val)) result += getSumOfDigits(val); } return result; } int main() { // Init benchmark data auto hash_map = std::make_unique<hash_map_t>(HASH_MAP_SIZE); std::vector<int> lookups; lookups.reserve(NUMBER_OF_LOOKUPS); init(hash_map.get(), lookups); auto original_result = original_solution(hash_map.get(), lookups); auto result = solution(hash_map.get(), lookups); if (original_result != result) { std::cerr << "Validation Failed. Original result = " << original_result << "; Modified version returned = " << result << "\n"; return 1; } std::cout << "Validation Successful" << std::endl; return 0; }
22.630435
75
0.622478
dendibakh
3e916ab3afa618ad129687af7812dab6dc53b6a4
1,069
cpp
C++
src/ParticleSystem.cpp
Alissa0101/CI628
f3401e9ea6a90d59572c4f079d27461148aab075
[ "MIT" ]
null
null
null
src/ParticleSystem.cpp
Alissa0101/CI628
f3401e9ea6a90d59572c4f079d27461148aab075
[ "MIT" ]
null
null
null
src/ParticleSystem.cpp
Alissa0101/CI628
f3401e9ea6a90d59572c4f079d27461148aab075
[ "MIT" ]
null
null
null
#include "ParticleSystem.h" void ParticleSystem::init(int _amount, float _x, float _y){ amount = _amount; for (int i = 0; i < _amount; i++) { Particle* particle = new Particle(); particle->x = _x + (rand() * 500 / RAND_MAX * 1) / 2; particle->y = _y + (rand() * 500 / RAND_MAX * 1) / 2; particles.push_back(particle); //sstd::cout << "added " << i << std::endl; } } void ParticleSystem::update(SDL_Renderer* renderer, int targetX, int targetY){ for (Particle* particle : particles) { if (particle->color.a == 0) { particle->x = targetX + (rand() % 10 - 1); particle->y = targetY + (rand() % 10 - 1); particle->velX = 0; //particle->velY = 0; particle->velY = -(((double)rand() / (RAND_MAX / 2)) + 1) / 2; particle->color.a = 255; } particle->update(renderer); } } void ParticleSystem::setStartColor(SDL_Color color) { for (Particle* particle : particles) { particle->startColor = color; } } void ParticleSystem::setEndColor(SDL_Color color) { for (Particle* particle : particles) { particle->endColor = color; } }
24.860465
78
0.625819
Alissa0101
3e9258bd253912c043c919417199845b6d819ecc
881
cpp
C++
src/index/tools/forward_to_libsvm.cpp
Lolik111/meta
c7019401185cdfa15e1193aad821894c35a83e3f
[ "MIT" ]
615
2015-01-31T17:14:03.000Z
2022-03-27T03:03:02.000Z
src/index/tools/forward_to_libsvm.cpp
Lolik111/meta
c7019401185cdfa15e1193aad821894c35a83e3f
[ "MIT" ]
167
2015-01-20T17:48:16.000Z
2021-12-20T00:15:29.000Z
src/index/tools/forward_to_libsvm.cpp
Lolik111/meta
c7019401185cdfa15e1193aad821894c35a83e3f
[ "MIT" ]
264
2015-01-30T00:08:01.000Z
2022-03-02T17:19:11.000Z
/** * @file forward_to_libsvm.cpp * @author Chase Geigle */ #include <iostream> #include "meta/index/forward_index.h" #include "meta/logging/logger.h" #include "meta/util/progress.h" using namespace meta; int main(int argc, char** argv) { if (argc != 3) { std::cerr << "Usage:\t" << argv[0] << " config.toml output-file" << std::endl; return 1; } logging::set_cerr_logging(); auto config = cpptoml::parse_file(argv[1]); auto idx = index::make_index<index::forward_index>(*config); { std::ofstream output{argv[2]}; printing::progress progress{" > Converting to libsvm: ", idx->num_docs()}; for (const auto& did : idx->docs()) { progress(did); output << idx->liblinear_data(did) << "\n"; } } return 0; }
22.589744
72
0.54143
Lolik111
3e9331a2953592e38dcd216393251ffc99dd8440
41,407
cpp
C++
compute/test/test_copy_type_mismatch.cpp
atksh/mimalloc-lgb
add692a5ef9a91cad0bc78fa18a051d43a8c930e
[ "MIT" ]
null
null
null
compute/test/test_copy_type_mismatch.cpp
atksh/mimalloc-lgb
add692a5ef9a91cad0bc78fa18a051d43a8c930e
[ "MIT" ]
null
null
null
compute/test/test_copy_type_mismatch.cpp
atksh/mimalloc-lgb
add692a5ef9a91cad0bc78fa18a051d43a8c930e
[ "MIT" ]
null
null
null
//---------------------------------------------------------------------------// // Copyright (c) 2016 Jakub Szuppe <j.szuppe@gmail.com> // // 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 // // See http://boostorg.github.com/compute for more information. //---------------------------------------------------------------------------// // Undefining BOOST_COMPUTE_USE_OFFLINE_CACHE macro as we want to modify cached // parameters for copy algorithm without any undesirable consequences (like // saving modified values of those parameters). #ifdef BOOST_COMPUTE_USE_OFFLINE_CACHE #undef BOOST_COMPUTE_USE_OFFLINE_CACHE #endif #define BOOST_TEST_MODULE TestCopyTypeMismatch #include <boost/test/unit_test.hpp> #include <list> #include <vector> #include <string> #include <sstream> #include <iterator> #include <iostream> #include <boost/compute/svm.hpp> #include <boost/compute/system.hpp> #include <boost/compute/functional.hpp> #include <boost/compute/command_queue.hpp> #include <boost/compute/algorithm/copy.hpp> #include <boost/compute/async/future.hpp> #include <boost/compute/container/vector.hpp> #include <boost/compute/detail/device_ptr.hpp> #include <boost/compute/memory/svm_ptr.hpp> #include <boost/compute/detail/parameter_cache.hpp> #include "quirks.hpp" #include "check_macros.hpp" #include "context_setup.hpp" namespace bc = boost::compute; namespace compute = boost::compute; BOOST_AUTO_TEST_CASE(is_same_ignore_const) { BOOST_STATIC_ASSERT(( boost::compute::detail::is_same_value_type< std::vector<int, mi_stl_allocator<int>>::iterator, compute::buffer_iterator<int>>::value)); BOOST_STATIC_ASSERT(( boost::compute::detail::is_same_value_type< std::vector<int, mi_stl_allocator<int>>::const_iterator, compute::buffer_iterator<int>>::value)); BOOST_STATIC_ASSERT(( boost::compute::detail::is_same_value_type< std::vector<int, mi_stl_allocator<int>>::iterator, compute::buffer_iterator<const int>>::value)); BOOST_STATIC_ASSERT(( boost::compute::detail::is_same_value_type< std::vector<int, mi_stl_allocator<int>>::const_iterator, compute::buffer_iterator<const int>>::value)); } BOOST_AUTO_TEST_CASE(copy_to_device_float_to_double) { if (!device.supports_extension("cl_khr_fp64")) { std::cout << "skipping test: device does not support double" << std::endl; return; } using compute::double_; using compute::float_; float_ host[] = {6.1f, 10.2f, 19.3f, 25.4f}; bc::vector<double_> device_vector(4, context); // copy host float data to double device vector bc::copy(host, host + 4, device_vector.begin(), queue); CHECK_RANGE_EQUAL(double_, 4, device_vector, (6.1f, 10.2f, 19.3f, 25.4f)); } BOOST_AUTO_TEST_CASE(copy_to_device_float_to_int) { using compute::float_; using compute::int_; float_ host[] = {6.1f, -10.2f, 19.3f, 25.4f}; bc::vector<int_> device_vector(4, context); // copy host float data to int device vector bc::copy(host, host + 4, device_vector.begin(), queue); CHECK_RANGE_EQUAL( int_, 4, device_vector, ( static_cast<int_>(6.1f), static_cast<int_>(-10.2f), static_cast<int_>(19.3f), static_cast<int_>(25.4f))); } // HOST -> DEVICE BOOST_AUTO_TEST_CASE(copy_to_device_float_to_int_mapping_device_vector) { using compute::float_; using compute::int_; using compute::uint_; float_ host[] = {6.1f, -10.2f, 19.3f, 25.4f}; bc::vector<int_> device_vector(4, context); std::string cache_key = std::string("__boost_compute_copy_to_device_float_int"); boost::shared_ptr<bc::detail::parameter_cache> parameters = bc::detail::parameter_cache::get_global_cache(device); // save uint_ map_copy_threshold = parameters->get(cache_key, "map_copy_threshold", 0); // force copy_to_device_map (mapping device vector to the host) parameters->set(cache_key, "map_copy_threshold", 1024); // copy host float data to int device vector bc::copy(host, host + 4, device_vector.begin(), queue); CHECK_RANGE_EQUAL( int_, 4, device_vector, ( static_cast<int_>(6.1f), static_cast<int_>(-10.2f), static_cast<int_>(19.3f), static_cast<int_>(25.4f))); // restore parameters->set(cache_key, "map_copy_threshold", map_copy_threshold); } BOOST_AUTO_TEST_CASE(copy_to_device_float_to_int_convert_on_host) { using compute::float_; using compute::int_; using compute::uint_; std::string cache_key = std::string("__boost_compute_copy_to_device_float_int"); boost::shared_ptr<bc::detail::parameter_cache> parameters = bc::detail::parameter_cache::get_global_cache(device); // save uint_ map_copy_threshold = parameters->get(cache_key, "map_copy_threshold", 0); uint_ direct_copy_threshold = parameters->get(cache_key, "direct_copy_threshold", 0); // force copying by casting input data on host and performing // normal copy host->device (since types match now) parameters->set(cache_key, "map_copy_threshold", 0); parameters->set(cache_key, "direct_copy_threshold", 1024); float_ host[] = {6.1f, -10.2f, 19.3f, 25.4f}; bc::vector<int_> device_vector(4, context); // copy host float data to int device vector bc::copy(host, host + 4, device_vector.begin(), queue); CHECK_RANGE_EQUAL( int_, 4, device_vector, ( static_cast<int_>(6.1f), static_cast<int_>(-10.2f), static_cast<int_>(19.3f), static_cast<int_>(25.4f))); // restore parameters->set(cache_key, "map_copy_threshold", map_copy_threshold); parameters->set(cache_key, "direct_copy_threshold", direct_copy_threshold); } BOOST_AUTO_TEST_CASE(copy_to_device_float_to_int_with_transform) { using compute::float_; using compute::int_; using compute::uint_; std::string cache_key = std::string("__boost_compute_copy_to_device_float_int"); boost::shared_ptr<bc::detail::parameter_cache> parameters = bc::detail::parameter_cache::get_global_cache(device); // save uint_ map_copy_threshold = parameters->get(cache_key, "map_copy_threshold", 0); uint_ direct_copy_threshold = parameters->get(cache_key, "direct_copy_threshold", 0); // force copying by mapping input data to the device memory // and using transform operation for casting & copying parameters->set(cache_key, "map_copy_threshold", 0); parameters->set(cache_key, "direct_copy_threshold", 0); float_ host[] = {6.1f, -10.2f, 19.3f, 25.4f}; bc::vector<int_> device_vector(4, context); // copy host float data to int device vector bc::copy(host, host + 4, device_vector.begin(), queue); CHECK_RANGE_EQUAL( int_, 4, device_vector, ( static_cast<int_>(6.1f), static_cast<int_>(-10.2f), static_cast<int_>(19.3f), static_cast<int_>(25.4f))); // restore parameters->set(cache_key, "map_copy_threshold", map_copy_threshold); parameters->set(cache_key, "direct_copy_threshold", direct_copy_threshold); } BOOST_AUTO_TEST_CASE(copy_async_to_device_float_to_int) { using compute::float_; using compute::int_; float_ host[] = {6.1f, -10.2f, 19.3f, 25.4f}; bc::vector<int_> device_vector(4, context); // copy host float data to int device vector compute::future<void> future = bc::copy_async(host, host + 4, device_vector.begin(), queue); future.wait(); CHECK_RANGE_EQUAL( int_, 4, device_vector, ( static_cast<int_>(6.1f), static_cast<int_>(-10.2f), static_cast<int_>(19.3f), static_cast<int_>(25.4f))); } BOOST_AUTO_TEST_CASE(copy_async_to_device_float_to_int_empty) { using compute::float_; using compute::int_; float_ host[] = {6.1f, -10.2f, 19.3f, 25.4f}; bc::vector<int_> device_vector(size_t(4), int_(1), queue); // copy nothing to int device vector compute::future<bc::vector<int_>::iterator> future = bc::copy_async(host, host, device_vector.begin(), queue); if (future.valid()) { future.wait(); } CHECK_RANGE_EQUAL( int_, 4, device_vector, ( int_(1), int_(1), int_(1), int_(1))); } // Test copying from a std::list to a bc::vector. This differs from // the test copying from std::vector because std::list has non-contiguous // storage for its data values. BOOST_AUTO_TEST_CASE(copy_to_device_float_to_int_list_device_map) { using compute::float_; using compute::int_; using compute::uint_; std::string cache_key = std::string("__boost_compute_copy_to_device_float_int"); boost::shared_ptr<bc::detail::parameter_cache> parameters = bc::detail::parameter_cache::get_global_cache(device); // save uint_ map_copy_threshold = parameters->get(cache_key, "map_copy_threshold", 0); // force copy_to_device_map (mapping device vector to the host) parameters->set(cache_key, "map_copy_threshold", 1024); float_ data[] = {6.1f, -10.2f, 19.3f, 25.4f}; std::list<float_> host(data, data + 4); bc::vector<int_> device_vector(4, context); // copy host float data to int device vector bc::copy(host.begin(), host.end(), device_vector.begin(), queue); CHECK_RANGE_EQUAL( int_, 4, device_vector, ( static_cast<int_>(6.1f), static_cast<int_>(-10.2f), static_cast<int_>(19.3f), static_cast<int_>(25.4f))); // restore parameters->set(cache_key, "map_copy_threshold", map_copy_threshold); } // Test copying from a std::list to a bc::vector. This differs from // the test copying from std::vector because std::list has non-contiguous // storage for its data values. BOOST_AUTO_TEST_CASE(copy_to_device_float_to_int_list_convert_on_host) { using compute::float_; using compute::int_; using compute::uint_; std::string cache_key = std::string("__boost_compute_copy_to_device_float_int"); boost::shared_ptr<bc::detail::parameter_cache> parameters = bc::detail::parameter_cache::get_global_cache(device); // save uint_ map_copy_threshold = parameters->get(cache_key, "map_copy_threshold", 0); uint_ direct_copy_threshold = parameters->get(cache_key, "direct_copy_threshold", 0); // force copying by casting input data on host and performing // normal copy host->device (since types match now) parameters->set(cache_key, "map_copy_threshold", 0); parameters->set(cache_key, "direct_copy_threshold", 1024); float_ data[] = {6.1f, -10.2f, 19.3f, 25.4f}; std::list<float_> host(data, data + 4); bc::vector<int_> device_vector(4, context); // copy host float data to int device vector bc::copy(host.begin(), host.end(), device_vector.begin(), queue); CHECK_RANGE_EQUAL( int_, 4, device_vector, ( static_cast<int_>(6.1f), static_cast<int_>(-10.2f), static_cast<int_>(19.3f), static_cast<int_>(25.4f))); // restore parameters->set(cache_key, "map_copy_threshold", map_copy_threshold); parameters->set(cache_key, "direct_copy_threshold", direct_copy_threshold); } // SVM requires OpenCL 2.0 #if defined(BOOST_COMPUTE_CL_VERSION_2_0) || defined(BOOST_COMPUTE_DOXYGEN_INVOKED) BOOST_AUTO_TEST_CASE(copy_to_device_svm_float_to_int_map) { REQUIRES_OPENCL_VERSION(2, 0); using compute::float_; using compute::int_; using compute::uint_; std::string cache_key = std::string("__boost_compute_copy_to_device_float_int"); boost::shared_ptr<bc::detail::parameter_cache> parameters = bc::detail::parameter_cache::get_global_cache(device); // save uint_ map_copy_threshold = parameters->get(cache_key, "map_copy_threshold", 0); // force copy_to_device_map (mapping device vector to the host) parameters->set(cache_key, "map_copy_threshold", 1024); float_ host[] = {5.1f, -10.3f, 19.4f, 26.7f}; compute::svm_ptr<int_> ptr = compute::svm_alloc<int_>(context, 4); // copy host float data to int device vector bc::copy(host, host + 4, ptr, queue); queue.enqueue_svm_map(ptr.get(), 4 * sizeof(cl_int), CL_MAP_READ); CHECK_HOST_RANGE_EQUAL( int_, 4, static_cast<int_ *>(ptr.get()), ( static_cast<int_>(5.1f), static_cast<int_>(-10.3f), static_cast<int_>(19.4f), static_cast<int_>(26.7f))); queue.enqueue_svm_unmap(ptr.get()).wait(); compute::svm_free(context, ptr); // restore parameters->set(cache_key, "map_copy_threshold", map_copy_threshold); } BOOST_AUTO_TEST_CASE(copy_to_device_svm_float_to_int_convert_on_host) { REQUIRES_OPENCL_VERSION(2, 0); if (bug_in_svmmemcpy(device)) { std::cerr << "skipping svmmemcpy test case" << std::endl; return; } using compute::float_; using compute::int_; using compute::uint_; std::string cache_key = std::string("__boost_compute_copy_to_device_float_int"); boost::shared_ptr<bc::detail::parameter_cache> parameters = bc::detail::parameter_cache::get_global_cache(device); // save uint_ map_copy_threshold = parameters->get(cache_key, "map_copy_threshold", 0); uint_ direct_copy_threshold = parameters->get(cache_key, "direct_copy_threshold", 0); // force copying by casting input data on host and performing // normal copy host->device (since types match now) parameters->set(cache_key, "map_copy_threshold", 0); parameters->set(cache_key, "direct_copy_threshold", 1024); float_ host[] = {0.1f, 10.3f, 9.4f, -26.7f}; compute::svm_ptr<int_> ptr = compute::svm_alloc<int_>(context, 4); // copy host float data to int device vector bc::copy(host, host + 4, ptr, queue); queue.enqueue_svm_map(ptr.get(), 4 * sizeof(cl_int), CL_MAP_READ); CHECK_HOST_RANGE_EQUAL( int_, 4, static_cast<int_ *>(ptr.get()), ( static_cast<int_>(0.1f), static_cast<int_>(10.3f), static_cast<int_>(9.4f), static_cast<int_>(-26.7f))); queue.enqueue_svm_unmap(ptr.get()).wait(); compute::svm_free(context, ptr); // restore parameters->set(cache_key, "map_copy_threshold", map_copy_threshold); parameters->set(cache_key, "direct_copy_threshold", direct_copy_threshold); } BOOST_AUTO_TEST_CASE(copy_to_device_svm_float_to_int_with_transform) { REQUIRES_OPENCL_VERSION(2, 0); using compute::float_; using compute::int_; using compute::uint_; std::string cache_key = std::string("__boost_compute_copy_to_device_float_int"); boost::shared_ptr<bc::detail::parameter_cache> parameters = bc::detail::parameter_cache::get_global_cache(device); // save uint_ map_copy_threshold = parameters->get(cache_key, "map_copy_threshold", 0); uint_ direct_copy_threshold = parameters->get(cache_key, "direct_copy_threshold", 0); // force copying by mapping input data to the device memory // and using transform operation (copy kernel) for casting & copying parameters->set(cache_key, "map_copy_threshold", 0); parameters->set(cache_key, "direct_copy_threshold", 0); float_ host[] = {4.1f, -11.3f, 219.4f, -26.7f}; compute::svm_ptr<int_> ptr = compute::svm_alloc<int_>(context, 4); // copy host float data to int device vector bc::copy(host, host + 4, ptr, queue); queue.enqueue_svm_map(ptr.get(), 4 * sizeof(cl_int), CL_MAP_READ); CHECK_HOST_RANGE_EQUAL( int_, 4, static_cast<int_ *>(ptr.get()), ( static_cast<int_>(4.1f), static_cast<int_>(-11.3f), static_cast<int_>(219.4f), static_cast<int_>(-26.7f))); queue.enqueue_svm_unmap(ptr.get()).wait(); compute::svm_free(context, ptr); // restore parameters->set(cache_key, "map_copy_threshold", map_copy_threshold); parameters->set(cache_key, "direct_copy_threshold", direct_copy_threshold); } BOOST_AUTO_TEST_CASE(copy_async_to_device_svm_float_to_int) { REQUIRES_OPENCL_VERSION(2, 0); using compute::float_; using compute::int_; using compute::uint_; float_ host[] = {44.1f, -14.3f, 319.4f, -26.7f}; compute::svm_ptr<int_> ptr = compute::svm_alloc<int_>(context, 4); // copy host float data to int device vector compute::future<void> future = bc::copy_async(host, host + 4, ptr, queue); future.wait(); queue.enqueue_svm_map(ptr.get(), 4 * sizeof(cl_int), CL_MAP_READ); CHECK_HOST_RANGE_EQUAL( int_, 4, static_cast<int_ *>(ptr.get()), ( static_cast<int_>(44.1f), static_cast<int_>(-14.3f), static_cast<int_>(319.4f), static_cast<int_>(-26.7f))); queue.enqueue_svm_unmap(ptr.get()).wait(); compute::svm_free(context, ptr); } #endif // DEVICE -> DEVICE BOOST_AUTO_TEST_CASE(copy_on_device_float_to_int) { using compute::float_; using compute::int_; float_ data[] = {6.1f, -10.2f, 19.3f, 25.4f}; bc::vector<float_> device_fvector(data, data + 4, queue); bc::vector<int_> device_ivector(4, context); // copy device float vector to device int vector bc::copy( device_fvector.begin(), device_fvector.end(), device_ivector.begin(), queue); CHECK_RANGE_EQUAL( int_, 4, device_ivector, ( static_cast<int_>(6.1f), static_cast<int_>(-10.2f), static_cast<int_>(19.3f), static_cast<int_>(25.4f))); } BOOST_AUTO_TEST_CASE(copy_async_on_device_float_to_int) { using compute::float_; using compute::int_; float_ data[] = {6.1f, -10.2f, 19.3f, 25.4f}; bc::vector<float_> device_fvector(data, data + 4, queue); bc::vector<int_> device_ivector(4, context); // copy device float vector to device int vector compute::future<void> future = bc::copy_async( device_fvector.begin(), device_fvector.end(), device_ivector.begin(), queue); future.wait(); CHECK_RANGE_EQUAL( int_, 4, device_ivector, ( static_cast<int_>(6.1f), static_cast<int_>(-10.2f), static_cast<int_>(19.3f), static_cast<int_>(25.4f))); } BOOST_AUTO_TEST_CASE(copy_async_on_device_float_to_int_empty) { using compute::float_; using compute::int_; float_ data[] = {6.1f, -10.2f, 19.3f, 25.4f}; bc::vector<float_> device_fvector(data, data + 4, queue); bc::vector<int_> device_ivector(size_t(4), int_(1), queue); // copy device float vector to device int vector compute::future<void> future = bc::copy_async( device_fvector.begin(), device_fvector.begin(), device_ivector.begin(), queue); if (future.valid()) { future.wait(); } CHECK_RANGE_EQUAL( int_, 4, device_ivector, ( int_(1), int_(1), int_(1), int_(1))); } // SVM requires OpenCL 2.0 #if defined(BOOST_COMPUTE_CL_VERSION_2_0) || defined(BOOST_COMPUTE_DOXYGEN_INVOKED) BOOST_AUTO_TEST_CASE(copy_on_device_buffer_to_svm_float_to_int) { REQUIRES_OPENCL_VERSION(2, 0); using compute::float_; using compute::int_; float_ data[] = {65.1f, -110.2f, -19.3f, 26.7f}; bc::vector<float_> device_vector(data, data + 4, queue); compute::svm_ptr<int_> ptr = compute::svm_alloc<int_>(context, 4); // copy host float data to int svm memory bc::copy(device_vector.begin(), device_vector.end(), ptr, queue); queue.enqueue_svm_map(ptr.get(), 4 * sizeof(cl_int), CL_MAP_READ); CHECK_HOST_RANGE_EQUAL( int_, 4, static_cast<int_ *>(ptr.get()), ( static_cast<int_>(65.1f), static_cast<int_>(-110.2f), static_cast<int_>(-19.3f), static_cast<int_>(26.7f))); queue.enqueue_svm_unmap(ptr.get()).wait(); compute::svm_free(context, ptr); } BOOST_AUTO_TEST_CASE(copy_on_device_svm_to_buffer_float_to_int) { REQUIRES_OPENCL_VERSION(2, 0); using compute::float_; using compute::int_; float_ data[] = {6.1f, 11.2f, 19.3f, 6.7f}; bc::vector<int_> device_vector(4, context); compute::svm_ptr<float_> ptr = compute::svm_alloc<float_>(context, 4); queue.enqueue_svm_map(ptr.get(), 4 * sizeof(cl_int), CL_MAP_WRITE); for (size_t i = 0; i < 4; i++) { static_cast<float_ *>(ptr.get())[i] = data[i]; } queue.enqueue_svm_unmap(ptr.get()).wait(); // copy host float svm data to int device vector bc::copy(ptr, ptr + 4, device_vector.begin(), queue); CHECK_RANGE_EQUAL( int_, 4, device_vector, ( static_cast<int_>(6.1f), static_cast<int_>(11.2f), static_cast<int_>(19.3f), static_cast<int_>(6.7f))); compute::svm_free(context, ptr); } BOOST_AUTO_TEST_CASE(copy_on_device_svm_to_svm_float_to_int) { REQUIRES_OPENCL_VERSION(2, 0); using compute::float_; using compute::int_; float_ data[] = {0.1f, -10.2f, -1.3f, 2.7f}; compute::svm_ptr<float_> ptr = compute::svm_alloc<float_>(context, 4); compute::svm_ptr<int_> ptr2 = compute::svm_alloc<int_>(context, 4); queue.enqueue_svm_map(ptr.get(), 4 * sizeof(cl_int), CL_MAP_WRITE); for (size_t i = 0; i < 4; i++) { static_cast<float_ *>(ptr.get())[i] = data[i]; } queue.enqueue_svm_unmap(ptr.get()).wait(); // copy host float svm to int svm bc::copy(ptr, ptr + 4, ptr2, queue); queue.enqueue_svm_map(ptr2.get(), 4 * sizeof(cl_int), CL_MAP_READ); CHECK_HOST_RANGE_EQUAL( int_, 4, static_cast<int_ *>(ptr2.get()), ( static_cast<int_>(0.1f), static_cast<int_>(-10.2f), static_cast<int_>(-1.3f), static_cast<int_>(2.7f))); queue.enqueue_svm_unmap(ptr2.get()).wait(); compute::svm_free(context, ptr); compute::svm_free(context, ptr2); } BOOST_AUTO_TEST_CASE(copy_async_on_device_buffer_to_svm_float_to_int) { REQUIRES_OPENCL_VERSION(2, 0); using compute::float_; using compute::int_; float_ data[] = {65.1f, -110.2f, -19.3f, 26.7f}; bc::vector<float_> device_vector(data, data + 4, queue); compute::svm_ptr<int_> ptr = compute::svm_alloc<int_>(context, 4); // copy host float data to int svm memory compute::future<bc::svm_ptr<int_>> future = bc::copy_async(device_vector.begin(), device_vector.end(), ptr, queue); future.wait(); queue.enqueue_svm_map(ptr.get(), 4 * sizeof(cl_int), CL_MAP_READ); CHECK_HOST_RANGE_EQUAL( int_, 4, static_cast<int_ *>(ptr.get()), ( static_cast<int_>(65.1f), static_cast<int_>(-110.2f), static_cast<int_>(-19.3f), static_cast<int_>(26.7f))); queue.enqueue_svm_unmap(ptr.get()).wait(); compute::svm_free(context, ptr); } BOOST_AUTO_TEST_CASE(copy_async_on_device_svm_to_buffer_float_to_int) { REQUIRES_OPENCL_VERSION(2, 0); using compute::float_; using compute::int_; float_ data[] = {65.1f, -110.2f, -19.3f, 26.7f}; bc::vector<int_> device_vector(4, context); compute::svm_ptr<float_> ptr = compute::svm_alloc<float_>(context, 4); queue.enqueue_svm_map(ptr.get(), 4 * sizeof(cl_int), CL_MAP_WRITE); for (size_t i = 0; i < 4; i++) { static_cast<float_ *>(ptr.get())[i] = data[i]; } queue.enqueue_svm_unmap(ptr.get()).wait(); // copy host float svm data to int device vector compute::future<bc::vector<int_>::iterator> future = bc::copy_async(ptr, ptr + 4, device_vector.begin(), queue); future.wait(); CHECK_RANGE_EQUAL( int_, 4, device_vector, ( static_cast<int_>(65.1f), static_cast<int_>(-110.2f), static_cast<int_>(-19.3f), static_cast<int_>(26.7f))); compute::svm_free(context, ptr); } BOOST_AUTO_TEST_CASE(copy_async_on_device_svm_to_svm_float_to_int) { REQUIRES_OPENCL_VERSION(2, 0); using compute::float_; using compute::int_; float_ data[] = {0.1f, -10.2f, -1.3f, 2.7f}; compute::svm_ptr<float_> ptr = compute::svm_alloc<float_>(context, 4); compute::svm_ptr<int_> ptr2 = compute::svm_alloc<int_>(context, 4); queue.enqueue_svm_map(ptr.get(), 4 * sizeof(cl_int), CL_MAP_WRITE); for (size_t i = 0; i < 4; i++) { static_cast<float_ *>(ptr.get())[i] = data[i]; } queue.enqueue_svm_unmap(ptr.get()).wait(); // copy host float svm to int svm compute::future<bc::svm_ptr<int_>> future = bc::copy_async(ptr, ptr + 4, ptr2, queue); future.wait(); queue.enqueue_svm_map(ptr2.get(), 4 * sizeof(cl_int), CL_MAP_READ); CHECK_HOST_RANGE_EQUAL( int_, 4, static_cast<int_ *>(ptr2.get()), ( static_cast<int_>(0.1f), static_cast<int_>(-10.2f), static_cast<int_>(-1.3f), static_cast<int_>(2.7f))); queue.enqueue_svm_unmap(ptr2.get()).wait(); compute::svm_free(context, ptr); compute::svm_free(context, ptr2); } #endif // DEVICE -> HOST BOOST_AUTO_TEST_CASE(copy_to_host_float_to_int) { using compute::float_; using compute::int_; float_ data[] = {6.1f, -10.2f, 19.3f, 25.4f}; bc::vector<float_> device_vector(data, data + 4, queue); std::vector<int_, mi_stl_allocator<int_>> host_vector(4); // copy device float vector to int host vector bc::copy(device_vector.begin(), device_vector.end(), host_vector.begin(), queue); CHECK_HOST_RANGE_EQUAL( int_, 4, host_vector.begin(), ( static_cast<int_>(6.1f), static_cast<int_>(-10.2f), static_cast<int_>(19.3f), static_cast<int_>(25.4f))); } BOOST_AUTO_TEST_CASE(copy_to_host_float_to_int_map) { using compute::float_; using compute::int_; using compute::uint_; std::string cache_key = std::string("__boost_compute_copy_to_host_float_int"); boost::shared_ptr<bc::detail::parameter_cache> parameters = bc::detail::parameter_cache::get_global_cache(device); // save uint_ map_copy_threshold = parameters->get(cache_key, "map_copy_threshold", 0); // force copy_to_host_map (mapping device vector to the host) parameters->set(cache_key, "map_copy_threshold", 1024); float_ data[] = {6.1f, -10.2f, 19.3f, 25.4f}; bc::vector<float_> device_vector(data, data + 4, queue); std::vector<int_, mi_stl_allocator<int_>> host_vector(4); // copy device float vector to int host vector bc::copy(device_vector.begin(), device_vector.end(), host_vector.begin(), queue); CHECK_HOST_RANGE_EQUAL( int_, 4, host_vector.begin(), ( static_cast<int_>(6.1f), static_cast<int_>(-10.2f), static_cast<int_>(19.3f), static_cast<int_>(25.4f))); // restore parameters->set(cache_key, "map_copy_threshold", map_copy_threshold); } BOOST_AUTO_TEST_CASE(copy_to_host_float_to_int_convert_on_host) { using compute::float_; using compute::int_; using compute::uint_; std::string cache_key = std::string("__boost_compute_copy_to_host_float_int"); boost::shared_ptr<bc::detail::parameter_cache> parameters = bc::detail::parameter_cache::get_global_cache(device); // save uint_ map_copy_threshold = parameters->get(cache_key, "map_copy_threshold", 0); uint_ direct_copy_threshold = parameters->get(cache_key, "direct_copy_threshold", 0); // force copying by copying input device vector to temporary // host vector of the same type and then copying from that temporary // vector to result using std::copy() parameters->set(cache_key, "map_copy_threshold", 0); parameters->set(cache_key, "direct_copy_threshold", 1024); float_ data[] = {6.1f, -10.2f, 19.3f, 25.4f}; bc::vector<float_> device_vector(data, data + 4, queue); std::vector<int_, mi_stl_allocator<int_>> host_vector(4); // copy device float vector to int host vector bc::copy(device_vector.begin(), device_vector.end(), host_vector.begin(), queue); CHECK_HOST_RANGE_EQUAL( int_, 4, host_vector.begin(), ( static_cast<int_>(6.1f), static_cast<int_>(-10.2f), static_cast<int_>(19.3f), static_cast<int_>(25.4f))); // restore parameters->set(cache_key, "map_copy_threshold", map_copy_threshold); parameters->set(cache_key, "direct_copy_threshold", direct_copy_threshold); } BOOST_AUTO_TEST_CASE(copy_to_host_float_to_int_convert_on_device) { using compute::float_; using compute::int_; using compute::uint_; std::string cache_key = std::string("__boost_compute_copy_to_host_float_int"); boost::shared_ptr<bc::detail::parameter_cache> parameters = bc::detail::parameter_cache::get_global_cache(device); // save uint_ map_copy_threshold = parameters->get(cache_key, "map_copy_threshold", 0); uint_ direct_copy_threshold = parameters->get(cache_key, "direct_copy_threshold", 0); // force copying by mapping output data to the device memory // and using transform operation for casting & copying parameters->set(cache_key, "map_copy_threshold", 0); parameters->set(cache_key, "direct_copy_threshold", 0); float_ data[] = {6.1f, -10.2f, 19.3f, 25.4f}; bc::vector<float_> device_vector(data, data + 4, queue); std::vector<int_, mi_stl_allocator<int_>> host_vector(4); // copy device float vector to int host vector bc::copy(device_vector.begin(), device_vector.end(), host_vector.begin(), queue); CHECK_HOST_RANGE_EQUAL( int_, 4, host_vector.begin(), ( static_cast<int_>(6.1f), static_cast<int_>(-10.2f), static_cast<int_>(19.3f), static_cast<int_>(25.4f))); // restore parameters->set(cache_key, "map_copy_threshold", map_copy_threshold); parameters->set(cache_key, "direct_copy_threshold", direct_copy_threshold); } // Test copying from a bc::vector to a std::list . This differs from // the test copying to std::vector because std::list has non-contiguous // storage for its data values. BOOST_AUTO_TEST_CASE(copy_to_host_list_float_to_int_map) { using compute::float_; using compute::int_; using compute::uint_; std::string cache_key = std::string("__boost_compute_copy_to_host_float_int"); boost::shared_ptr<bc::detail::parameter_cache> parameters = bc::detail::parameter_cache::get_global_cache(device); // save uint_ map_copy_threshold = parameters->get(cache_key, "map_copy_threshold", 0); // force copy_to_host_map (mapping device vector to the host) parameters->set(cache_key, "map_copy_threshold", 1024); float_ data[] = {6.1f, -10.2f, 19.3f, 25.4f}; bc::vector<float_> device_vector(data, data + 4, queue); std::list<int_> host_list(4); // copy device float vector to int host vector bc::copy(device_vector.begin(), device_vector.end(), host_list.begin(), queue); int_ expected[4] = { static_cast<int_>(6.1f), static_cast<int_>(-10.2f), static_cast<int_>(19.3f), static_cast<int_>(25.4f)}; BOOST_CHECK_EQUAL_COLLECTIONS( host_list.begin(), host_list.end(), expected, expected + 4); // restore parameters->set(cache_key, "map_copy_threshold", map_copy_threshold); } // Test copying from a bc::vector to a std::list . This differs from // the test copying to std::vector because std::list has non-contiguous // storage for its data values. BOOST_AUTO_TEST_CASE(copy_to_host_list_float_to_int_covert_on_host) { using compute::float_; using compute::int_; using compute::uint_; std::string cache_key = std::string("__boost_compute_copy_to_host_float_int"); boost::shared_ptr<bc::detail::parameter_cache> parameters = bc::detail::parameter_cache::get_global_cache(device); // save uint_ map_copy_threshold = parameters->get(cache_key, "map_copy_threshold", 0); uint_ direct_copy_threshold = parameters->get(cache_key, "direct_copy_threshold", 0); // force copying by copying input device vector to temporary // host vector of the same type and then copying from that temporary // vector to result using std::copy() parameters->set(cache_key, "map_copy_threshold", 0); parameters->set(cache_key, "direct_copy_threshold", 1024); float_ data[] = {6.1f, -10.2f, 19.3f, 25.4f}; bc::vector<float_> device_vector(data, data + 4, queue); std::list<int_> host_list(4); // copy device float vector to int host vector bc::copy(device_vector.begin(), device_vector.end(), host_list.begin(), queue); int_ expected[4] = { static_cast<int_>(6.1f), static_cast<int_>(-10.2f), static_cast<int_>(19.3f), static_cast<int_>(25.4f)}; BOOST_CHECK_EQUAL_COLLECTIONS( host_list.begin(), host_list.end(), expected, expected + 4); // restore parameters->set(cache_key, "map_copy_threshold", map_copy_threshold); parameters->set(cache_key, "direct_copy_threshold", direct_copy_threshold); } BOOST_AUTO_TEST_CASE(copy_async_to_host_float_to_int) { using compute::float_; using compute::int_; float_ data[] = {6.1f, -10.2f, 19.3f, 25.4f}; bc::vector<float_> device_vector(data, data + 4, queue); std::vector<int_, mi_stl_allocator<int_>> host_vector(device_vector.size()); // copy device float vector to host int vector compute::future<void> future = bc::copy_async( device_vector.begin(), device_vector.end(), host_vector.begin(), queue); future.wait(); CHECK_HOST_RANGE_EQUAL( int_, 4, host_vector.begin(), ( static_cast<int_>(6.1f), static_cast<int_>(-10.2f), static_cast<int_>(19.3f), static_cast<int_>(25.4f))); } BOOST_AUTO_TEST_CASE(copy_async_to_host_float_to_int_empty) { using compute::float_; using compute::int_; float_ data[] = {6.1f, -10.2f, 19.3f, 25.4f}; bc::vector<float_> device_vector(data, data + 4, queue); std::vector<int_, mi_stl_allocator<int_>> host_vector(device_vector.size(), int_(1)); // copy device float vector to host int vector compute::future<void> future = bc::copy_async( device_vector.begin(), device_vector.begin(), host_vector.begin(), queue); if (future.valid()) { future.wait(); } CHECK_HOST_RANGE_EQUAL( int_, 4, host_vector.begin(), ( int_(1), int_(1), int_(1), int_(1))); } // SVM requires OpenCL 2.0 #if defined(BOOST_COMPUTE_CL_VERSION_2_0) || defined(BOOST_COMPUTE_DOXYGEN_INVOKED) BOOST_AUTO_TEST_CASE(copy_to_host_svm_float_to_int_map) { REQUIRES_OPENCL_VERSION(2, 0); using compute::float_; using compute::int_; using compute::uint_; std::string cache_key = std::string("__boost_compute_copy_to_host_float_int"); boost::shared_ptr<bc::detail::parameter_cache> parameters = bc::detail::parameter_cache::get_global_cache(device); // save uint_ map_copy_threshold = parameters->get(cache_key, "map_copy_threshold", 0); // force copy_to_host_map (mapping device vector to the host) parameters->set(cache_key, "map_copy_threshold", 1024); float_ data[] = {6.1f, 1.2f, 1.3f, -66.7f}; std::vector<int_, mi_stl_allocator<int_>> host_vector(4, 0); compute::svm_ptr<float_> ptr = compute::svm_alloc<float_>(context, 4); queue.enqueue_svm_map(ptr.get(), 4 * sizeof(cl_int), CL_MAP_WRITE); for (size_t i = 0; i < 4; i++) { static_cast<float_ *>(ptr.get())[i] = data[i]; } queue.enqueue_svm_unmap(ptr.get()).wait(); // copy host float svm data to int host vector bc::copy(ptr, ptr + 4, host_vector.begin(), queue); CHECK_HOST_RANGE_EQUAL( int_, 4, host_vector.begin(), ( static_cast<int_>(6.1f), static_cast<int_>(1.2f), static_cast<int_>(1.3f), static_cast<int_>(-66.7f))); compute::svm_free(context, ptr); // restore parameters->set(cache_key, "map_copy_threshold", map_copy_threshold); } BOOST_AUTO_TEST_CASE(copy_to_host_svm_float_to_int_convert_on_host) { REQUIRES_OPENCL_VERSION(2, 0); if (bug_in_svmmemcpy(device)) { std::cerr << "skipping svmmemcpy test case" << std::endl; return; } using compute::float_; using compute::int_; using compute::uint_; std::string cache_key = std::string("__boost_compute_copy_to_host_float_int"); boost::shared_ptr<bc::detail::parameter_cache> parameters = bc::detail::parameter_cache::get_global_cache(device); // save uint_ map_copy_threshold = parameters->get(cache_key, "map_copy_threshold", 0); uint_ direct_copy_threshold = parameters->get(cache_key, "direct_copy_threshold", 0); // force copying by copying input device vector to temporary // host vector of the same type and then copying from that temporary // vector to result using std::copy() parameters->set(cache_key, "map_copy_threshold", 0); parameters->set(cache_key, "direct_copy_threshold", 1024); float_ data[] = {6.1f, 1.2f, 1.3f, 766.7f}; std::vector<int_, mi_stl_allocator<int_>> host_vector(4, 0); compute::svm_ptr<float_> ptr = compute::svm_alloc<float_>(context, 4); queue.enqueue_svm_map(ptr.get(), 4 * sizeof(cl_int), CL_MAP_WRITE); for (size_t i = 0; i < 4; i++) { static_cast<float_ *>(ptr.get())[i] = data[i]; } queue.enqueue_svm_unmap(ptr.get()).wait(); // copy host float svm data to int host vector bc::copy(ptr, ptr + 4, host_vector.begin(), queue); CHECK_HOST_RANGE_EQUAL( int_, 4, host_vector.begin(), ( static_cast<int_>(6.1f), static_cast<int_>(1.2f), static_cast<int_>(1.3f), static_cast<int_>(766.7f))); compute::svm_free(context, ptr); // restore parameters->set(cache_key, "map_copy_threshold", map_copy_threshold); parameters->set(cache_key, "direct_copy_threshold", direct_copy_threshold); } BOOST_AUTO_TEST_CASE(copy_to_host_svm_float_to_int_transform) { REQUIRES_OPENCL_VERSION(2, 0); using compute::float_; using compute::int_; using compute::uint_; std::string cache_key = std::string("__boost_compute_copy_to_host_float_int"); boost::shared_ptr<bc::detail::parameter_cache> parameters = bc::detail::parameter_cache::get_global_cache(device); // save uint_ map_copy_threshold = parameters->get(cache_key, "map_copy_threshold", 0); uint_ direct_copy_threshold = parameters->get(cache_key, "direct_copy_threshold", 0); // force copying by copying input device vector to temporary // host vector of the same type and then copying from that temporary // vector to result using std::copy() parameters->set(cache_key, "map_copy_threshold", 0); parameters->set(cache_key, "direct_copy_threshold", 0); float_ data[] = {0.1f, 11.2f, 1.3f, -66.7f}; std::vector<int_, mi_stl_allocator<int_>> host_vector(4, 0); compute::svm_ptr<float_> ptr = compute::svm_alloc<float_>(context, 4); queue.enqueue_svm_map(ptr.get(), 4 * sizeof(cl_int), CL_MAP_WRITE); for (size_t i = 0; i < 4; i++) { static_cast<float_ *>(ptr.get())[i] = data[i]; } queue.enqueue_svm_unmap(ptr.get()).wait(); // copy host float svm data to int host vector bc::copy(ptr, ptr + 4, host_vector.begin(), queue); CHECK_HOST_RANGE_EQUAL( int_, 4, host_vector.begin(), ( static_cast<int_>(0.1f), static_cast<int_>(11.2f), static_cast<int_>(1.3f), static_cast<int_>(-66.7f))); compute::svm_free(context, ptr); // restore parameters->set(cache_key, "map_copy_threshold", map_copy_threshold); parameters->set(cache_key, "direct_copy_threshold", direct_copy_threshold); } #endif BOOST_AUTO_TEST_SUITE_END()
31.440395
89
0.644819
atksh
3e96b77e96f760928f2ca55498f2a970925b1ec8
3,321
hpp
C++
src/renderer/tvg_renderer.hpp
JSUYA/rive-tizen
f62cf0bc8a60bc4293855150e926163d446ac57e
[ "MIT" ]
null
null
null
src/renderer/tvg_renderer.hpp
JSUYA/rive-tizen
f62cf0bc8a60bc4293855150e926163d446ac57e
[ "MIT" ]
null
null
null
src/renderer/tvg_renderer.hpp
JSUYA/rive-tizen
f62cf0bc8a60bc4293855150e926163d446ac57e
[ "MIT" ]
null
null
null
#ifndef _RIVE_THORVG_RENDERER_HPP_ #define _RIVE_THORVG_RENDERER_HPP_ #include <thorvg.h> #include <vector> #include "renderer.hpp" using namespace tvg; using namespace std; namespace rive { struct TvgPaint { uint8_t color[4]; float thickness = 1.0f; tvg::Fill *gradientFill = nullptr; tvg::StrokeJoin join = tvg::StrokeJoin::Bevel; tvg::StrokeCap cap = tvg::StrokeCap::Butt; RenderPaintStyle style = RenderPaintStyle::fill; bool isGradient = false; }; struct TvgRenderPath : public RenderPath { unique_ptr<Shape> tvgShape; TvgRenderPath() : tvgShape(tvg::Shape::gen()) {} void buildShape(); void reset() override; void addRenderPath(RenderPath* path, const Mat2D& transform) override; void fillRule(FillRule value) override; void moveTo(float x, float y) override; void lineTo(float x, float y) override; void cubicTo(float ox, float oy, float ix, float iy, float x, float y) override; void close() override; }; struct GradientStop { unsigned int color; float stop; GradientStop(unsigned int color, float stop) : color(color), stop(stop) { } }; class TvgGradientBuilder { public: std::vector<GradientStop> stops; float sx, sy, ex, ey; virtual ~TvgGradientBuilder() {} TvgGradientBuilder(float sx, float sy, float ex, float ey) : sx(sx), sy(sy), ex(ex), ey(ey) { } virtual void make(TvgPaint* paint) = 0; }; class TvgRadialGradientBuilder : public TvgGradientBuilder { public: TvgRadialGradientBuilder(float sx, float sy, float ex, float ey) : TvgGradientBuilder(sx, sy, ex, ey) { } void make(TvgPaint* paint) override; }; class TvgLinearGradientBuilder : public TvgGradientBuilder { public: TvgLinearGradientBuilder(float sx, float sy, float ex, float ey) : TvgGradientBuilder(sx, sy, ex, ey) { } void make(TvgPaint* paint) override; }; class TvgRenderPaint : public RenderPaint { private: TvgPaint m_Paint; TvgGradientBuilder* m_GradientBuilder = nullptr; public: TvgPaint* paint() { return &m_Paint; } void style(RenderPaintStyle style) override; void color(unsigned int value) override; void thickness(float value) override; void join(StrokeJoin value) override; void cap(StrokeCap value) override; void blendMode(BlendMode value) override; void linearGradient(float sx, float sy, float ex, float ey) override; void radialGradient(float sx, float sy, float ex, float ey) override; void addStop(unsigned int color, float stop) override; void completeGradient() override; }; class TvgRenderer : public Renderer { private: Canvas* m_Canvas; Shape* m_ClipPath = nullptr; Shape* m_BgClipPath = nullptr; Mat2D m_Transform; Mat2D m_SaveTransform; public: TvgRenderer(Canvas* canvas) : m_Canvas(canvas) {} void save() override; void restore() override; void transform(const Mat2D& transform) override; void drawPath(RenderPath* path, RenderPaint* paint) override; void clipPath(RenderPath* path) override; }; } #endif
26.782258
86
0.65131
JSUYA
3e9a7636c39afc564cf8a5c6643edaca026733cb
1,274
cc
C++
thirdparty/aria2/test/GZipDecoderTest.cc
deltegic/deltegic
9b4f3a505a6842db52efbe850150afbab3af5e2f
[ "BSD-3-Clause" ]
null
null
null
thirdparty/aria2/test/GZipDecoderTest.cc
deltegic/deltegic
9b4f3a505a6842db52efbe850150afbab3af5e2f
[ "BSD-3-Clause" ]
2
2021-04-08T08:46:23.000Z
2021-04-08T08:57:58.000Z
thirdparty/aria2/test/GZipDecoderTest.cc
deltegic/deltegic
9b4f3a505a6842db52efbe850150afbab3af5e2f
[ "BSD-3-Clause" ]
null
null
null
#include "GZipDecoder.h" #include <iostream> #include <fstream> #include <cppunit/extensions/HelperMacros.h> #include "TestUtil.h" #include "Exception.h" #include "util.h" #include "MessageDigest.h" namespace aria2 { class GZipDecoderTest : public CppUnit::TestFixture { CPPUNIT_TEST_SUITE(GZipDecoderTest); CPPUNIT_TEST(testDecode); CPPUNIT_TEST_SUITE_END(); public: void setUp() {} void tearDown() {} void testDecode(); }; CPPUNIT_TEST_SUITE_REGISTRATION(GZipDecoderTest); void GZipDecoderTest::testDecode() { GZipDecoder decoder; decoder.init(); std::string outfile(A2_TEST_OUT_DIR "/aria2_GZipDecoderTest_testDecode"); char buf[4_k]; std::ifstream in(A2_TEST_DIR "/gzip_decode_test.gz", std::ios::binary); std::ofstream out(outfile.c_str(), std::ios::binary); while (in) { in.read(buf, sizeof(buf)); std::string r = decoder.decode(reinterpret_cast<const unsigned char*>(buf), in.gcount()); out.write(r.data(), r.size()); } CPPUNIT_ASSERT(decoder.finished()); decoder.release(); out.close(); CPPUNIT_ASSERT_EQUAL(std::string("8b577b33c0411b2be9d4fa74c7402d54a8d21f96"), fileHexDigest(MessageDigest::sha1().get(), outfile)); } } // namespace aria2
21.59322
79
0.690738
deltegic
3e9acc08f3ae771c818b17deb068751f1861ed0a
2,687
cpp
C++
gstreaming/source/rtsp/server/src/rtsp_server.cpp
cbachhuber/telecarla
44546341834ba852073f35ab02ab4ab0b040cb61
[ "MIT" ]
null
null
null
gstreaming/source/rtsp/server/src/rtsp_server.cpp
cbachhuber/telecarla
44546341834ba852073f35ab02ab4ab0b040cb61
[ "MIT" ]
null
null
null
gstreaming/source/rtsp/server/src/rtsp_server.cpp
cbachhuber/telecarla
44546341834ba852073f35ab02ab4ab0b040cb61
[ "MIT" ]
null
null
null
#include "rtsp_server.h" #include "gst_rtsp_server_util.h" using namespace lmt::rtsp::server; using namespace lmt::rtsp::common; RTSPState RTSPServer::start(int serverPort, const std::string& src) { if (state_ == RTSPState::stopped) { state_ = RTSPState::starting; server_.reset(gst_rtsp_server_new()); gst_rtsp_server_set_service(server_.get(), std::to_string(serverPort).c_str()); auto mounts = std::unique_ptr<GstRTSPMountPoints, decltype(&g_object_unref)>( gst_rtsp_server_get_mount_points(server_.get()), g_object_unref); std::stringstream command; command << src << " name=" << context_->app->getName() << " is-live=true ! videorate ! videoconvert ! x264enc tune=zerolatency speed-preset=ultrafast " "sliced-threads=true byte-stream=true threads=1 key-int-max=15 intra-refresh=true name=" << context_->encoder->getName() << " ! h264parse ! rtph264pay pt=96 name=pay0"; GstRTSPMediaFactory* factory = gst_rtsp_media_factory_new(); gst_rtsp_media_factory_set_launch(factory, command.str().c_str()); // gst_rtsp_media_factory_set_protocols(factory, GST_RTSP_LOWER_TRANS_TCP); // gst_rtsp_media_factory_set_protocols(factory, GST_RTSP_LOWER_TRANS_UDP); std::string path = "/" + context_->app->getName(); gst_rtsp_mount_points_add_factory(mounts.get(), path.c_str(), factory); g_signal_connect(factory, "media-configure", (GCallback)mediaConfigure, context_.get()); handle_ = gst_rtsp_server_attach(server_.get(), nullptr); state_ = RTSPState::started; } return state_; } void RTSPServer::stop() { if (state_ == RTSPState::started) { state_ = RTSPState::stopping; if (handle_ != -1) { g_source_remove(handle_); } handle_ = -1; state_ = RTSPState::stopped; } } RTSPServer::RTSPServer(const std::string& mountName) : context_(std::make_unique<RTSPServerContext>(mountName, "x264encoder")) { const auto videoWidthInPixels{640}; const auto videoHeightInPixels{480}; context_->app->setVideoData(getDefaultImage(videoWidthInPixels, videoHeightInPixels, 0)); } RTSPServer::~RTSPServer() { stop(); } void RTSPServer::rateControlCallback(gstreaming::RateControlConfig& config, uint32_t /*level*/) { context_->encoder->updateRateControlParameter(config.bitrate); context_->app->updateSpatioTemporalResolution(config.fps, config.spatial_scale); } void RTSPServer::cameraImageCallback(const sensor_msgs::ImageConstPtr& msg) { context_->app->setVideoData(msg); }
32.768293
113
0.681057
cbachhuber
3e9b90a1836517b688792cf980d70ec16e64defa
1,176
cpp
C++
Desouky/Easy/Treasure hunt.cpp
AhmedMostafa7474/Codingame-Solutions
da696a095c143c5d216bc06f6689ad1c0e25d0e0
[ "MIT" ]
1
2022-03-16T08:56:31.000Z
2022-03-16T08:56:31.000Z
Desouky/Easy/Treasure hunt.cpp
AhmedMostafa7474/Codingame-Solutions
da696a095c143c5d216bc06f6689ad1c0e25d0e0
[ "MIT" ]
2
2022-03-17T11:27:14.000Z
2022-03-18T07:41:00.000Z
Desouky/Easy/Treasure hunt.cpp
AhmedMostafa7474/Codingame-Solutions
da696a095c143c5d216bc06f6689ad1c0e25d0e0
[ "MIT" ]
6
2022-03-13T19:56:11.000Z
2022-03-17T12:08:22.000Z
#include <iostream> #include <string> #include <vector> #include <bits/stdc++.h> using namespace std; int h; int w; string grid[105]; bool vis[105][105]; bool valid(int r, int c){ return r >= 0 and r < h and c >= 0 and c < w and !vis[r][c] and grid[r][c] != '#'; } int ans = 0; void solve(int r, int c, int total){ ans = max(ans, total); if(!valid(r, c))return; int sum = 0; if(grid[r][c] >= '1' and grid[r][c] <= '9') sum += (grid[r][c] -'0'); vis[r][c] = 1; solve(r+1 , c , total + sum); vis[r][c] = 0; vis[r][c] = 1; solve(r-1 , c , total + sum); vis[r][c] = 0; vis[r][c] = 1; solve(r , c+1 , total + sum); vis[r][c] = 0; vis[r][c] = 1; solve(r , c-1 , total + sum); vis[r][c] = 0; } int main() { cin >> h >> w; cin.ignore(); for (int i = 0; i < h; i++) { string row; getline(cin, row); grid[i] = row; } pair<int , int> s; for(int x = 0; x<h; x++){ for(int y =0; y<w; y++){ if(grid[x][y] == 'X') s = {x, y}; } } memset(vis, 0, sizeof vis); solve(s.first, s.second,0); cout<<ans<<endl; return 0; }
19.932203
86
0.456633
AhmedMostafa7474
3e9bfec8dae57e761ce0592af3937e493a5fa433
7,158
cpp
C++
libraries/render/src/render/ResampleTask.cpp
raveenajain/hifi-1
b95586239a08da8b0d61640119aad672099c107c
[ "Apache-2.0" ]
null
null
null
libraries/render/src/render/ResampleTask.cpp
raveenajain/hifi-1
b95586239a08da8b0d61640119aad672099c107c
[ "Apache-2.0" ]
null
null
null
libraries/render/src/render/ResampleTask.cpp
raveenajain/hifi-1
b95586239a08da8b0d61640119aad672099c107c
[ "Apache-2.0" ]
null
null
null
// // ResampleTask.cpp // render/src/render // // Various to upsample or downsample textures into framebuffers. // // Created by Olivier Prat on 10/09/17. // Copyright 2017 High Fidelity, Inc. // // Distributed under the Apache License, Version 2.0. // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include "ResampleTask.h" #include <gpu/Context.h> #include <shaders/Shaders.h> using namespace render; gpu::PipelinePointer HalfDownsample::_pipeline; HalfDownsample::HalfDownsample() { } void HalfDownsample::configure(const Config& config) { } gpu::FramebufferPointer HalfDownsample::getResampledFrameBuffer(const gpu::FramebufferPointer& sourceFramebuffer) { auto resampledFramebufferSize = sourceFramebuffer->getSize(); resampledFramebufferSize.x /= 2U; resampledFramebufferSize.y /= 2U; if (!_destinationFrameBuffer || resampledFramebufferSize != _destinationFrameBuffer->getSize()) { _destinationFrameBuffer = gpu::FramebufferPointer(gpu::Framebuffer::create("HalfOutput")); auto sampler = gpu::Sampler(gpu::Sampler::FILTER_MIN_MAG_LINEAR_MIP_POINT); auto target = gpu::Texture::createRenderBuffer(sourceFramebuffer->getRenderBuffer(0)->getTexelFormat(), resampledFramebufferSize.x, resampledFramebufferSize.y, gpu::Texture::SINGLE_MIP, sampler); _destinationFrameBuffer->setRenderBuffer(0, target); } return _destinationFrameBuffer; } void HalfDownsample::run(const RenderContextPointer& renderContext, const gpu::FramebufferPointer& sourceFramebuffer, gpu::FramebufferPointer& resampledFrameBuffer) { assert(renderContext->args); assert(renderContext->args->hasViewFrustum()); RenderArgs* args = renderContext->args; resampledFrameBuffer = getResampledFrameBuffer(sourceFramebuffer); if (!_pipeline) { gpu::ShaderPointer program = gpu::Shader::createProgram(shader::gpu::program::drawTransformUnitQuadTextureOpaque); gpu::StatePointer state = gpu::StatePointer(new gpu::State()); state->setDepthTest(gpu::State::DepthTest(false, false)); _pipeline = gpu::Pipeline::create(program, state); } const auto bufferSize = resampledFrameBuffer->getSize(); glm::ivec4 viewport{ 0, 0, bufferSize.x, bufferSize.y }; gpu::doInBatch("HalfDownsample::run", args->_context, [&](gpu::Batch& batch) { batch.enableStereo(false); batch.setFramebuffer(resampledFrameBuffer); batch.setViewportTransform(viewport); batch.setProjectionTransform(glm::mat4()); batch.resetViewTransform(); batch.setPipeline(_pipeline); batch.setModelTransform(gpu::Framebuffer::evalSubregionTexcoordTransform(bufferSize, viewport)); batch.setResourceTexture(0, sourceFramebuffer->getRenderBuffer(0)); batch.draw(gpu::TRIANGLE_STRIP, 4); }); } gpu::PipelinePointer Upsample::_pipeline; void Upsample::configure(const Config& config) { _factor = config.factor; } gpu::FramebufferPointer Upsample::getResampledFrameBuffer(const gpu::FramebufferPointer& sourceFramebuffer) { if (_factor == 1.0f) { return sourceFramebuffer; } auto resampledFramebufferSize = glm::uvec2(glm::vec2(sourceFramebuffer->getSize()) * _factor); if (!_destinationFrameBuffer || resampledFramebufferSize != _destinationFrameBuffer->getSize()) { _destinationFrameBuffer = gpu::FramebufferPointer(gpu::Framebuffer::create("UpsampledOutput")); auto sampler = gpu::Sampler(gpu::Sampler::FILTER_MIN_MAG_LINEAR); auto target = gpu::Texture::createRenderBuffer(sourceFramebuffer->getRenderBuffer(0)->getTexelFormat(), resampledFramebufferSize.x, resampledFramebufferSize.y, gpu::Texture::SINGLE_MIP, sampler); _destinationFrameBuffer->setRenderBuffer(0, target); } return _destinationFrameBuffer; } void Upsample::run(const RenderContextPointer& renderContext, const gpu::FramebufferPointer& sourceFramebuffer, gpu::FramebufferPointer& resampledFrameBuffer) { assert(renderContext->args); assert(renderContext->args->hasViewFrustum()); RenderArgs* args = renderContext->args; resampledFrameBuffer = getResampledFrameBuffer(sourceFramebuffer); if (resampledFrameBuffer != sourceFramebuffer) { if (!_pipeline) { gpu::ShaderPointer program = gpu::Shader::createProgram(shader::gpu::program::drawTransformUnitQuadTextureOpaque); gpu::StatePointer state = gpu::StatePointer(new gpu::State()); state->setDepthTest(gpu::State::DepthTest(false, false)); _pipeline = gpu::Pipeline::create(program, state); } const auto bufferSize = resampledFrameBuffer->getSize(); glm::ivec4 viewport{ 0, 0, bufferSize.x, bufferSize.y }; gpu::doInBatch("Upsample::run", args->_context, [&](gpu::Batch& batch) { batch.enableStereo(false); batch.setFramebuffer(resampledFrameBuffer); batch.setViewportTransform(viewport); batch.setProjectionTransform(glm::mat4()); batch.resetViewTransform(); batch.setPipeline(_pipeline); batch.setModelTransform(gpu::Framebuffer::evalSubregionTexcoordTransform(bufferSize, viewport)); batch.setResourceTexture(0, sourceFramebuffer->getRenderBuffer(0)); batch.draw(gpu::TRIANGLE_STRIP, 4); }); // Set full final viewport args->_viewport = viewport; } } gpu::PipelinePointer UpsampleToBlitFramebuffer::_pipeline; void UpsampleToBlitFramebuffer::run(const RenderContextPointer& renderContext, const Input& input, gpu::FramebufferPointer& resampledFrameBuffer) { assert(renderContext->args); assert(renderContext->args->hasViewFrustum()); RenderArgs* args = renderContext->args; auto sourceFramebuffer = input; resampledFrameBuffer = args->_blitFramebuffer; if (resampledFrameBuffer != sourceFramebuffer) { if (!_pipeline) { gpu::ShaderPointer program = gpu::Shader::createProgram(shader::gpu::program::drawTransformUnitQuadTextureOpaque); gpu::StatePointer state = gpu::StatePointer(new gpu::State()); state->setDepthTest(gpu::State::DepthTest(false, false)); _pipeline = gpu::Pipeline::create(program, state); } const auto bufferSize = resampledFrameBuffer->getSize(); glm::ivec4 viewport{ 0, 0, bufferSize.x, bufferSize.y }; gpu::doInBatch("Upsample::run", args->_context, [&](gpu::Batch& batch) { batch.enableStereo(false); batch.setFramebuffer(resampledFrameBuffer); batch.setViewportTransform(viewport); batch.setProjectionTransform(glm::mat4()); batch.resetViewTransform(); batch.setPipeline(_pipeline); batch.setModelTransform(gpu::Framebuffer::evalSubregionTexcoordTransform(bufferSize, viewport)); batch.setResourceTexture(0, sourceFramebuffer->getRenderBuffer(0)); batch.draw(gpu::TRIANGLE_STRIP, 4); }); // Set full final viewport args->_viewport = viewport; } }
40.213483
203
0.706901
raveenajain
3ea1059fd88d76adcc7f047aab2216e59a63c15c
2,575
cpp
C++
shared/liboxide/signalhandler.cpp
Eeems-Org/oxide
d3bfa47e60bf311feb7768234dfe95a15adeb9da
[ "MIT" ]
18
2022-01-11T17:24:50.000Z
2022-03-30T04:35:25.000Z
shared/liboxide/signalhandler.cpp
Eeems-Org/oxide
d3bfa47e60bf311feb7768234dfe95a15adeb9da
[ "MIT" ]
21
2022-01-07T19:20:04.000Z
2022-03-24T14:32:28.000Z
shared/liboxide/signalhandler.cpp
Eeems-Org/oxide
d3bfa47e60bf311feb7768234dfe95a15adeb9da
[ "MIT" ]
2
2022-01-15T16:45:34.000Z
2022-03-01T22:37:48.000Z
#include "signalhandler.h" #include <QCoreApplication> #include <signal.h> #include <sys/socket.h> #include <sys/un.h> #include <unistd.h> static int sigUsr1Fd[2]; static int sigUsr2Fd[2]; namespace Oxide { int SignalHandler::setup_unix_signal_handlers(){ if(!signalHandler){ new SignalHandler(qApp); } struct sigaction usr1, usr2; usr1.sa_handler = SignalHandler::usr1SignalHandler; sigemptyset(&usr1.sa_mask); usr1.sa_flags = 0; usr1.sa_flags |= SA_RESTART; if(sigaction(SIGUSR1, &usr1, 0)){ return 1; } usr2.sa_handler = SignalHandler::usr2SignalHandler; sigemptyset(&usr2.sa_mask); usr2.sa_flags = 0; usr2.sa_flags |= SA_RESTART; if(sigaction(SIGUSR2, &usr2, 0)){ return 2; } return 0; } SignalHandler* SignalHandler::singleton(SignalHandler* self){ static SignalHandler* instance; if(self != nullptr){ instance = self; } return instance; } SignalHandler::SignalHandler(QObject *parent) : QObject(parent){ singleton(this); if(::socketpair(AF_UNIX, SOCK_STREAM, 0, sigUsr1Fd)){ qFatal("Couldn't create USR1 socketpair"); } if(::socketpair(AF_UNIX, SOCK_STREAM, 0, sigUsr2Fd)){ qFatal("Couldn't create USR2 socketpair"); } snUsr1 = new QSocketNotifier(sigUsr1Fd[1], QSocketNotifier::Read, this); connect(snUsr1, &QSocketNotifier::activated, this, &SignalHandler::handleSigUsr1, Qt::QueuedConnection); snUsr2 = new QSocketNotifier(sigUsr2Fd[1], QSocketNotifier::Read, this); connect(snUsr2, &QSocketNotifier::activated, this, &SignalHandler::handleSigUsr2, Qt::QueuedConnection); } SignalHandler::~SignalHandler(){} void SignalHandler::usr1SignalHandler(int unused){ Q_UNUSED(unused) char a = 1; ::write(sigUsr1Fd[0], &a, sizeof(a)); } void SignalHandler::usr2SignalHandler(int unused){ Q_UNUSED(unused) char a = 1; ::write(sigUsr2Fd[0], &a, sizeof(a)); } void SignalHandler::handleSigUsr1(){ snUsr1->setEnabled(false); char tmp; ::read(sigUsr1Fd[1], &tmp, sizeof(tmp)); emit sigUsr1(); snUsr1->setEnabled(true); } void SignalHandler::handleSigUsr2(){ snUsr2->setEnabled(false); char tmp; ::read(sigUsr2Fd[1], &tmp, sizeof(tmp)); emit sigUsr2(); snUsr2->setEnabled(true); } }
30.294118
112
0.607379
Eeems-Org
3ea6455330e40eb7c0d5032535d70791ad72bab9
1,500
hpp
C++
nheqminer/3rdparty/boost/python/detail/destroy.hpp
EuroLine/nheqminer
81c7ef889bb502d16f7d1e7ef020d0592f8af945
[ "MIT" ]
1,210
2020-08-18T07:57:36.000Z
2022-03-31T15:06:05.000Z
ios/Pods/boost-for-react-native/boost/python/detail/destroy.hpp
c7yrus/alyson-v3
5ad95a8f782f5f5d2fd543d44ca6a8b093395965
[ "Apache-2.0" ]
1,074
2015-08-25T15:08:14.000Z
2019-07-22T20:28:39.000Z
ios/Pods/boost-for-react-native/boost/python/detail/destroy.hpp
c7yrus/alyson-v3
5ad95a8f782f5f5d2fd543d44ca6a8b093395965
[ "Apache-2.0" ]
534
2016-10-20T21:00:00.000Z
2022-03-29T10:02:27.000Z
// Copyright David Abrahams 2002. // Distributed under the Boost Software License, Version 1.0. (See // accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef DESTROY_DWA2002221_HPP # define DESTROY_DWA2002221_HPP # include <boost/type_traits/is_array.hpp> # include <boost/detail/workaround.hpp> namespace boost { namespace python { namespace detail { template <bool array> struct value_destroyer; template <> struct value_destroyer<false> { template <class T> static void execute(T const volatile* p) { p->~T(); } }; template <> struct value_destroyer<true> { template <class A, class T> static void execute(A*, T const volatile* const first) { for (T const volatile* p = first; p != first + sizeof(A)/sizeof(T); ++p) { value_destroyer< boost::is_array<T>::value >::execute(p); } } template <class T> static void execute(T const volatile* p) { execute(p, *p); } }; template <class T> inline void destroy_referent_impl(void* p, T& (*)()) { // note: cv-qualification needed for MSVC6 // must come *before* T for metrowerks value_destroyer< (boost::is_array<T>::value) >::execute((const volatile T*)p); } template <class T> inline void destroy_referent(void* p, T(*)() = 0) { destroy_referent_impl(p, (T(*)())0); } }}} // namespace boost::python::detail #endif // DESTROY_DWA2002221_HPP
23.4375
80
0.638
EuroLine
3ea887a30e36ddd4a174db272d16b657c1e7567f
11,856
cpp
C++
src/optimizer/optimizer.cpp
xhad1234/peloton
60dea12ed528bc8873b1c43d1eca841a5d76ee44
[ "Apache-2.0" ]
1
2017-08-08T12:10:07.000Z
2017-08-08T12:10:07.000Z
src/optimizer/optimizer.cpp
xhad1234/peloton
60dea12ed528bc8873b1c43d1eca841a5d76ee44
[ "Apache-2.0" ]
null
null
null
src/optimizer/optimizer.cpp
xhad1234/peloton
60dea12ed528bc8873b1c43d1eca841a5d76ee44
[ "Apache-2.0" ]
null
null
null
//===----------------------------------------------------------------------===// // // Peloton // // optimizer.cpp // // Identification: src/optimizer/optimizer.cpp // // Copyright (c) 2015-16, Carnegie Mellon University Database Group // //===----------------------------------------------------------------------===// #include "optimizer/optimizer.h" #include "optimizer/operator_visitor.h" #include "optimizer/convert_query_to_op.h" #include "optimizer/convert_op_to_plan.h" #include "optimizer/rule_impls.h" #include "planner/projection_plan.h" #include "planner/seq_scan_plan.h" #include "planner/order_by_plan.h" #include "catalog/manager.h" #include <memory> namespace peloton { namespace optimizer { //===--------------------------------------------------------------------===// // Optimizer //===--------------------------------------------------------------------===// Optimizer::Optimizer() { rules.emplace_back(new InnerJoinCommutativity()); rules.emplace_back(new GetToScan()); rules.emplace_back(new SelectToFilter()); rules.emplace_back(new ProjectToComputeExprs()); rules.emplace_back(new InnerJoinToInnerNLJoin()); rules.emplace_back(new LeftJoinToLeftNLJoin()); rules.emplace_back(new RightJoinToRightNLJoin()); rules.emplace_back(new OuterJoinToOuterNLJoin()); // rules.emplace_back(new InnerJoinToInnerHashJoin()); } Optimizer &Optimizer::GetInstance() { thread_local static Optimizer optimizer; return optimizer; } std::shared_ptr<planner::AbstractPlan> Optimizer::GeneratePlan( std::shared_ptr<Select> select_tree) { // Generate initial operator tree from query tree std::shared_ptr<GroupExpression> gexpr = InsertQueryTree(select_tree); GroupID root_id = gexpr->GetGroupID(); // Get the physical properties the final plan must output PropertySet properties = GetQueryTreeRequiredProperties(select_tree); // Find least cost plan for root group OptimizeExpression(gexpr, properties); std::shared_ptr<OpExpression> best_plan = ChooseBestPlan(root_id, properties); if (best_plan == nullptr) return nullptr; planner::AbstractPlan *top_plan = OptimizerPlanToPlannerPlan(best_plan); std::shared_ptr<planner::AbstractPlan> final_plan(top_plan); return final_plan; } std::shared_ptr<GroupExpression> Optimizer::InsertQueryTree( std::shared_ptr<Select> tree) { std::shared_ptr<OpExpression> initial = ConvertQueryToOpExpression(column_manager, tree); std::shared_ptr<GroupExpression> gexpr; assert(RecordTransformedExpression(initial, gexpr)); return gexpr; } PropertySet Optimizer::GetQueryTreeRequiredProperties( std::shared_ptr<Select> tree) { (void)tree; return PropertySet(); } planner::AbstractPlan *Optimizer::OptimizerPlanToPlannerPlan( std::shared_ptr<OpExpression> plan) { return ConvertOpExpressionToPlan(plan); } std::shared_ptr<OpExpression> Optimizer::ChooseBestPlan( GroupID id, PropertySet requirements) { LOG_TRACE("Choosing best plan for group %d", id); Group *group = memo.GetGroupByID(id); std::shared_ptr<GroupExpression> gexpr = group->GetBestExpression(requirements); std::vector<GroupID> child_groups = gexpr->GetChildGroupIDs(); std::vector<PropertySet> required_input_props = gexpr->Op().RequiredInputProperties(); if (required_input_props.empty()) { required_input_props.resize(child_groups.size(), PropertySet()); } std::shared_ptr<OpExpression> op = std::make_shared<OpExpression>(gexpr->Op()); for (size_t i = 0; i < child_groups.size(); ++i) { std::shared_ptr<OpExpression> child_op = ChooseBestPlan(child_groups[i], required_input_props[i]); op->PushChild(child_op); } return op; } void Optimizer::OptimizeGroup(GroupID id, PropertySet requirements) { LOG_TRACE("Optimizing group %d", id); Group *group = memo.GetGroupByID(id); const std::vector<std::shared_ptr<GroupExpression>> exprs = group->GetExpressions(); for (size_t i = 0; i < exprs.size(); ++i) { OptimizeExpression(exprs[i], requirements); } } void Optimizer::OptimizeExpression(std::shared_ptr<GroupExpression> gexpr, PropertySet requirements) { LOG_TRACE("Optimizing expression of group %d with op %s", gexpr->GetGroupID(), gexpr->Op().name().c_str()); // Helper function for costing follow up expressions auto CostCandidate = [this](std::shared_ptr<GroupExpression> candidate, PropertySet requirements) { // Cost the expression this->CostExpression(candidate); // Only include cost if it meets the property requirements if (requirements.IsSubset(candidate->Op().ProvidedOutputProperties())) { // Add to group as potential best cost Group *group = this->memo.GetGroupByID(candidate->GetGroupID()); LOG_TRACE("Adding expression cost on group %d with op %s", candidate->GetGroupID(), candidate->Op().name().c_str()); group->SetExpressionCost(candidate, candidate->GetCost(), requirements); } }; // Cost the root expression if (gexpr->Op().IsPhysical()) { CostCandidate(gexpr, requirements); // Transformation rules shouldn't match on physical operators so don't apply // rules } else { // Apply transformations and cost those which match the requirements for (const std::unique_ptr<Rule> &rule : rules) { // Apply all rules to operator which match. We apply all rules to one // operator before moving on to the next operator in the group because // then we avoid missing the application of a rule e.g. an application // of some rule creates a match for a previously applied rule, but it is // missed because the prev rule was already checked std::vector<std::shared_ptr<GroupExpression>> candidates = TransformExpression(gexpr, *(rule.get())); for (std::shared_ptr<GroupExpression> candidate : candidates) { // If logical... if (candidate->Op().IsLogical()) { // Optimize the expression OptimizeExpression(candidate, requirements); } if (candidate->Op().IsPhysical()) { CostCandidate(candidate, requirements); } } } } } void Optimizer::CostExpression(std::shared_ptr<GroupExpression> gexpr) { LOG_TRACE("Costing expression of group %d with op %s", gexpr->GetGroupID(), gexpr->Op().name().c_str()); // Get required properties of children std::vector<PropertySet> required_child_properties = gexpr->Op().RequiredInputProperties(); std::vector<GroupID> child_group_ids = gexpr->GetChildGroupIDs(); if (required_child_properties.empty()) { required_child_properties.resize(child_group_ids.size(), PropertySet()); } std::vector<std::shared_ptr<GroupExpression>> best_child_expressions; std::vector<std::shared_ptr<Stats>> best_child_stats; std::vector<double> best_child_costs; for (size_t i = 0; i < child_group_ids.size(); ++i) { GroupID child_group_id = child_group_ids[i]; const PropertySet &input_properties = required_child_properties[i]; // Optimize child OptimizeGroup(child_group_id, input_properties); // Find best child expression std::shared_ptr<GroupExpression> best_expression = memo.GetGroupByID(child_group_id)->GetBestExpression(input_properties); // TODO(abpoms): we should allow for failure in the case where no expression // can provide the required properties assert(best_expression != nullptr); best_child_expressions.push_back(best_expression); best_child_stats.push_back(best_expression->GetStats()); best_child_costs.push_back(best_expression->GetCost()); } // Perform costing gexpr->DeriveStatsAndCost(best_child_stats, best_child_costs); } void Optimizer::ExploreGroup(GroupID id) { LOG_TRACE("Exploring group %d", id); for (std::shared_ptr<GroupExpression> gexpr : memo.GetGroupByID(id)->GetExpressions()) { ExploreExpression(gexpr); } } void Optimizer::ExploreExpression(std::shared_ptr<GroupExpression> gexpr) { LOG_TRACE("Exploring expression of group %d with op %s", gexpr->GetGroupID(), gexpr->Op().name().c_str()); for (const std::unique_ptr<Rule> &rule : rules) { // See comment in OptimizeExpression std::vector<std::shared_ptr<GroupExpression>> candidates = TransformExpression(gexpr, *(rule.get())); for (std::shared_ptr<GroupExpression> candidate : candidates) { // If logical... if (candidate->Op().IsLogical()) { // Explore the expression ExploreExpression(candidate); } } } } ////////////////////////////////////////////////////////////////////////////// /// Rule application std::vector<std::shared_ptr<GroupExpression>> Optimizer::TransformExpression( std::shared_ptr<GroupExpression> gexpr, const Rule &rule) { std::shared_ptr<Pattern> pattern = rule.GetMatchPattern(); std::vector<std::shared_ptr<GroupExpression>> output_plans; ItemBindingIterator iterator(*this, gexpr, pattern); while (iterator.HasNext()) { std::shared_ptr<OpExpression> plan = iterator.Next(); // Check rule condition function if (rule.Check(plan)) { LOG_TRACE("Rule matched expression of group %d with op %s", gexpr->GetGroupID(), gexpr->Op().name().c_str()); // Apply rule transformations // We need to be able to analyze the transformations performed by this // rule in order to perform deduplication and launch an exploration of // the newly applied rule std::vector<std::shared_ptr<OpExpression>> transformed_plans; rule.Transform(plan, transformed_plans); // Integrate transformed plans back into groups and explore/cost if new for (std::shared_ptr<OpExpression> plan : transformed_plans) { LOG_TRACE("Trying to integrate expression with op %s", plan->Op().name().c_str()); std::shared_ptr<GroupExpression> new_gexpr; bool new_expression = RecordTransformedExpression(plan, new_gexpr, gexpr->GetGroupID()); if (new_expression) { LOG_TRACE("Expression with op %s was inserted into group %d", plan->Op().name().c_str(), new_gexpr->GetGroupID()); output_plans.push_back(new_gexpr); } } } } return output_plans; } ////////////////////////////////////////////////////////////////////////////// /// Memo insertion std::shared_ptr<GroupExpression> Optimizer::MakeGroupExpression( std::shared_ptr<OpExpression> expr) { std::vector<GroupID> child_groups = MemoTransformedChildren(expr); return std::make_shared<GroupExpression>(expr->Op(), child_groups); } std::vector<GroupID> Optimizer::MemoTransformedChildren( std::shared_ptr<OpExpression> expr) { std::vector<GroupID> child_groups; for (std::shared_ptr<OpExpression> child : expr->Children()) { child_groups.push_back(MemoTransformedExpression(child)); } return child_groups; } GroupID Optimizer::MemoTransformedExpression( std::shared_ptr<OpExpression> expr) { std::shared_ptr<GroupExpression> gexpr = MakeGroupExpression(expr); // Ignore whether this expression is new or not as we only care about that // at the top level (void)memo.InsertExpression(gexpr); return gexpr->GetGroupID(); } bool Optimizer::RecordTransformedExpression( std::shared_ptr<OpExpression> expr, std::shared_ptr<GroupExpression> &gexpr) { return RecordTransformedExpression(expr, gexpr, UNDEFINED_GROUP); } bool Optimizer::RecordTransformedExpression( std::shared_ptr<OpExpression> expr, std::shared_ptr<GroupExpression> &gexpr, GroupID target_group) { gexpr = MakeGroupExpression(expr); return memo.InsertExpression(gexpr, target_group); } } // namespace optimizer } // namespace peloton
36.48
80
0.681765
xhad1234
3ea9a59b3db363f5257de3cff64c3d7210398ad1
14,503
cc
C++
source/blender/blenlib/tests/BLI_set_test.cc
Smittyvb/blender
0e92be7b65a8bb15dd9b07400f250c0958f10589
[ "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
source/blender/blenlib/tests/BLI_set_test.cc
Smittyvb/blender
0e92be7b65a8bb15dd9b07400f250c0958f10589
[ "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
source/blender/blenlib/tests/BLI_set_test.cc
Smittyvb/blender
0e92be7b65a8bb15dd9b07400f250c0958f10589
[ "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
/* Apache License, Version 2.0 */ #include <set> #include <unordered_set> #include "BLI_exception_safety_test_utils.hh" #include "BLI_ghash.h" #include "BLI_rand.h" #include "BLI_set.hh" #include "BLI_strict_flags.h" #include "BLI_timeit.hh" #include "BLI_vector.hh" #include "testing/testing.h" namespace blender { namespace tests { TEST(set, DefaultConstructor) { Set<int> set; EXPECT_EQ(set.size(), 0); EXPECT_TRUE(set.is_empty()); } TEST(set, ContainsNotExistant) { Set<int> set; EXPECT_FALSE(set.contains(3)); } TEST(set, ContainsExistant) { Set<int> set; EXPECT_FALSE(set.contains(5)); EXPECT_TRUE(set.is_empty()); set.add(5); EXPECT_TRUE(set.contains(5)); EXPECT_FALSE(set.is_empty()); } TEST(set, AddMany) { Set<int> set; for (int i = 0; i < 100; i++) { set.add(i); } for (int i = 50; i < 100; i++) { EXPECT_TRUE(set.contains(i)); } for (int i = 100; i < 150; i++) { EXPECT_FALSE(set.contains(i)); } } TEST(set, InitializerListConstructor) { Set<int> set = {4, 5, 6}; EXPECT_EQ(set.size(), 3); EXPECT_TRUE(set.contains(4)); EXPECT_TRUE(set.contains(5)); EXPECT_TRUE(set.contains(6)); EXPECT_FALSE(set.contains(2)); EXPECT_FALSE(set.contains(3)); } TEST(set, CopyConstructor) { Set<int> set = {3}; EXPECT_TRUE(set.contains(3)); EXPECT_FALSE(set.contains(4)); Set<int> set2(set); set2.add(4); EXPECT_TRUE(set2.contains(3)); EXPECT_TRUE(set2.contains(4)); EXPECT_FALSE(set.contains(4)); } TEST(set, MoveConstructor) { Set<int> set = {1, 2, 3}; EXPECT_EQ(set.size(), 3); Set<int> set2(std::move(set)); EXPECT_EQ(set.size(), 0); /* NOLINT: bugprone-use-after-move */ EXPECT_EQ(set2.size(), 3); } TEST(set, CopyAssignment) { Set<int> set = {3}; EXPECT_TRUE(set.contains(3)); EXPECT_FALSE(set.contains(4)); Set<int> set2; set2 = set; set2.add(4); EXPECT_TRUE(set2.contains(3)); EXPECT_TRUE(set2.contains(4)); EXPECT_FALSE(set.contains(4)); } TEST(set, MoveAssignment) { Set<int> set = {1, 2, 3}; EXPECT_EQ(set.size(), 3); Set<int> set2; set2 = std::move(set); EXPECT_EQ(set.size(), 0); /* NOLINT: bugprone-use-after-move */ EXPECT_EQ(set2.size(), 3); } TEST(set, RemoveContained) { Set<int> set = {3, 4, 5}; EXPECT_TRUE(set.contains(3)); EXPECT_TRUE(set.contains(4)); EXPECT_TRUE(set.contains(5)); set.remove_contained(4); EXPECT_TRUE(set.contains(3)); EXPECT_FALSE(set.contains(4)); EXPECT_TRUE(set.contains(5)); set.remove_contained(3); EXPECT_FALSE(set.contains(3)); EXPECT_FALSE(set.contains(4)); EXPECT_TRUE(set.contains(5)); set.remove_contained(5); EXPECT_FALSE(set.contains(3)); EXPECT_FALSE(set.contains(4)); EXPECT_FALSE(set.contains(5)); } TEST(set, RemoveContainedMany) { Set<int> set; for (int i = 0; i < 1000; i++) { set.add(i); } for (int i = 100; i < 1000; i++) { set.remove_contained(i); } for (int i = 900; i < 1000; i++) { set.add(i); } for (int i = 0; i < 1000; i++) { if (i < 100 || i >= 900) { EXPECT_TRUE(set.contains(i)); } else { EXPECT_FALSE(set.contains(i)); } } } TEST(set, Intersects) { Set<int> a = {3, 4, 5, 6}; Set<int> b = {1, 2, 5}; EXPECT_TRUE(Set<int>::Intersects(a, b)); EXPECT_FALSE(Set<int>::Disjoint(a, b)); } TEST(set, Disjoint) { Set<int> a = {5, 6, 7, 8}; Set<int> b = {2, 3, 4, 9}; EXPECT_FALSE(Set<int>::Intersects(a, b)); EXPECT_TRUE(Set<int>::Disjoint(a, b)); } TEST(set, AddMultiple) { Set<int> a; a.add_multiple({5, 7}); EXPECT_TRUE(a.contains(5)); EXPECT_TRUE(a.contains(7)); EXPECT_FALSE(a.contains(4)); a.add_multiple({2, 4, 7}); EXPECT_TRUE(a.contains(4)); EXPECT_TRUE(a.contains(2)); EXPECT_EQ(a.size(), 4); } TEST(set, AddMultipleNew) { Set<int> a; a.add_multiple_new({5, 6}); EXPECT_TRUE(a.contains(5)); EXPECT_TRUE(a.contains(6)); } TEST(set, Iterator) { Set<int> set = {1, 3, 2, 5, 4}; blender::Vector<int> vec; for (int value : set) { vec.append(value); } EXPECT_EQ(vec.size(), 5); EXPECT_TRUE(vec.contains(1)); EXPECT_TRUE(vec.contains(3)); EXPECT_TRUE(vec.contains(2)); EXPECT_TRUE(vec.contains(5)); EXPECT_TRUE(vec.contains(4)); } TEST(set, OftenAddRemoveContained) { Set<int> set; for (int i = 0; i < 100; i++) { set.add(42); EXPECT_EQ(set.size(), 1); set.remove_contained(42); EXPECT_EQ(set.size(), 0); } } TEST(set, UniquePtrValues) { Set<std::unique_ptr<int>> set; set.add_new(std::unique_ptr<int>(new int())); auto value1 = std::unique_ptr<int>(new int()); set.add_new(std::move(value1)); set.add(std::unique_ptr<int>(new int())); EXPECT_EQ(set.size(), 3); } TEST(set, Clear) { Set<int> set = {3, 4, 6, 7}; EXPECT_EQ(set.size(), 4); set.clear(); EXPECT_EQ(set.size(), 0); } TEST(set, StringSet) { Set<std::string> set; set.add("hello"); set.add("world"); EXPECT_EQ(set.size(), 2); EXPECT_TRUE(set.contains("hello")); EXPECT_TRUE(set.contains("world")); EXPECT_FALSE(set.contains("world2")); } TEST(set, PointerSet) { int a, b, c; Set<int *> set; set.add(&a); set.add(&b); EXPECT_EQ(set.size(), 2); EXPECT_TRUE(set.contains(&a)); EXPECT_TRUE(set.contains(&b)); EXPECT_FALSE(set.contains(&c)); } TEST(set, Remove) { Set<int> set = {1, 2, 3, 4, 5, 6}; EXPECT_EQ(set.size(), 6); EXPECT_TRUE(set.remove(2)); EXPECT_EQ(set.size(), 5); EXPECT_FALSE(set.contains(2)); EXPECT_FALSE(set.remove(2)); EXPECT_EQ(set.size(), 5); EXPECT_TRUE(set.remove(5)); EXPECT_EQ(set.size(), 4); } struct Type1 { uint32_t value; }; struct Type2 { uint32_t value; }; static bool operator==(const Type1 &a, const Type1 &b) { return a.value == b.value; } static bool operator==(const Type2 &a, const Type1 &b) { return a.value == b.value; } } // namespace tests /* This has to be defined in ::blender namespace. */ template<> struct DefaultHash<tests::Type1> { uint32_t operator()(const tests::Type1 &value) const { return value.value; } uint32_t operator()(const tests::Type2 &value) const { return value.value; } }; namespace tests { TEST(set, ContainsAs) { Set<Type1> set; set.add(Type1{5}); EXPECT_TRUE(set.contains_as(Type1{5})); EXPECT_TRUE(set.contains_as(Type2{5})); EXPECT_FALSE(set.contains_as(Type1{6})); EXPECT_FALSE(set.contains_as(Type2{6})); } TEST(set, ContainsAsString) { Set<std::string> set; set.add("test"); EXPECT_TRUE(set.contains_as("test")); EXPECT_TRUE(set.contains_as(StringRef("test"))); EXPECT_FALSE(set.contains_as("string")); EXPECT_FALSE(set.contains_as(StringRef("string"))); } TEST(set, RemoveContainedAs) { Set<Type1> set; set.add(Type1{5}); EXPECT_TRUE(set.contains_as(Type2{5})); set.remove_contained_as(Type2{5}); EXPECT_FALSE(set.contains_as(Type2{5})); } TEST(set, RemoveAs) { Set<Type1> set; set.add(Type1{5}); EXPECT_TRUE(set.contains_as(Type2{5})); set.remove_as(Type2{6}); EXPECT_TRUE(set.contains_as(Type2{5})); set.remove_as(Type2{5}); EXPECT_FALSE(set.contains_as(Type2{5})); set.remove_as(Type2{5}); EXPECT_FALSE(set.contains_as(Type2{5})); } TEST(set, AddAs) { Set<std::string> set; EXPECT_TRUE(set.add_as("test")); EXPECT_TRUE(set.add_as(StringRef("qwe"))); EXPECT_FALSE(set.add_as(StringRef("test"))); EXPECT_FALSE(set.add_as("qwe")); } template<uint N> struct EqualityIntModN { bool operator()(uint a, uint b) const { return (a % N) == (b % N); } }; template<uint N> struct HashIntModN { uint64_t operator()(uint value) const { return value % N; } }; TEST(set, CustomizeHashAndEquality) { Set<uint, 0, DefaultProbingStrategy, HashIntModN<10>, EqualityIntModN<10>> set; set.add(4); EXPECT_TRUE(set.contains(4)); EXPECT_TRUE(set.contains(14)); EXPECT_TRUE(set.contains(104)); EXPECT_FALSE(set.contains(5)); set.add(55); EXPECT_TRUE(set.contains(5)); EXPECT_TRUE(set.contains(14)); set.remove(1004); EXPECT_FALSE(set.contains(14)); } TEST(set, IntrusiveIntKey) { Set<int, 2, DefaultProbingStrategy, DefaultHash<int>, DefaultEquality, IntegerSetSlot<int, 100, 200>> set; EXPECT_TRUE(set.add(4)); EXPECT_TRUE(set.add(3)); EXPECT_TRUE(set.add(11)); EXPECT_TRUE(set.add(8)); EXPECT_FALSE(set.add(3)); EXPECT_FALSE(set.add(4)); EXPECT_TRUE(set.remove(4)); EXPECT_FALSE(set.remove(7)); EXPECT_TRUE(set.add(4)); EXPECT_TRUE(set.remove(4)); } struct MyKeyType { uint32_t key; int32_t attached_data; uint64_t hash() const { return key; } friend bool operator==(const MyKeyType &a, const MyKeyType &b) { return a.key == b.key; } }; TEST(set, LookupKey) { Set<MyKeyType> set; set.add({1, 10}); set.add({2, 20}); EXPECT_EQ(set.lookup_key({1, 30}).attached_data, 10); EXPECT_EQ(set.lookup_key({2, 0}).attached_data, 20); } TEST(set, LookupKeyDefault) { Set<MyKeyType> set; set.add({1, 10}); set.add({2, 20}); MyKeyType fallback{5, 50}; EXPECT_EQ(set.lookup_key_default({1, 66}, fallback).attached_data, 10); EXPECT_EQ(set.lookup_key_default({4, 40}, fallback).attached_data, 50); } TEST(set, LookupKeyPtr) { Set<MyKeyType> set; set.add({1, 10}); set.add({2, 20}); EXPECT_EQ(set.lookup_key_ptr({1, 50})->attached_data, 10); EXPECT_EQ(set.lookup_key_ptr({2, 50})->attached_data, 20); EXPECT_EQ(set.lookup_key_ptr({3, 50}), nullptr); } TEST(set, StringViewKeys) { Set<std::string_view> set; set.add("hello"); set.add("world"); EXPECT_FALSE(set.contains("worlds")); EXPECT_TRUE(set.contains("world")); EXPECT_TRUE(set.contains("hello")); } TEST(set, SpanConstructorExceptions) { std::array<ExceptionThrower, 5> array = {1, 2, 3, 4, 5}; array[3].throw_during_copy = true; Span<ExceptionThrower> span = array; EXPECT_ANY_THROW({ Set<ExceptionThrower> set(span); }); } TEST(set, CopyConstructorExceptions) { Set<ExceptionThrower> set = {1, 2, 3, 4, 5}; set.lookup_key(3).throw_during_copy = true; EXPECT_ANY_THROW({ Set<ExceptionThrower> set_copy(set); }); } TEST(set, MoveConstructorExceptions) { using SetType = Set<ExceptionThrower, 4>; SetType set = {1, 2, 3}; set.lookup_key(2).throw_during_move = true; EXPECT_ANY_THROW({ SetType set_moved(std::move(set)); }); EXPECT_EQ(set.size(), 0); set.add_multiple({3, 6, 7}); EXPECT_EQ(set.size(), 3); } TEST(set, AddNewExceptions) { Set<ExceptionThrower> set; ExceptionThrower value; value.throw_during_copy = true; EXPECT_ANY_THROW({ set.add_new(value); }); EXPECT_EQ(set.size(), 0); EXPECT_ANY_THROW({ set.add_new(value); }); EXPECT_EQ(set.size(), 0); } TEST(set, AddExceptions) { Set<ExceptionThrower> set; ExceptionThrower value; value.throw_during_copy = true; EXPECT_ANY_THROW({ set.add(value); }); EXPECT_EQ(set.size(), 0); EXPECT_ANY_THROW({ set.add(value); }); EXPECT_EQ(set.size(), 0); } /** * Set this to 1 to activate the benchmark. It is disabled by default, because it prints a lot. */ #if 0 template<typename SetT> BLI_NOINLINE void benchmark_random_ints(StringRef name, int amount, int factor) { RNG *rng = BLI_rng_new(0); Vector<int> values; for (int i = 0; i < amount; i++) { values.append(BLI_rng_get_int(rng) * factor); } BLI_rng_free(rng); SetT set; { SCOPED_TIMER(name + " Add"); for (int value : values) { set.add(value); } } int count = 0; { SCOPED_TIMER(name + " Contains"); for (int value : values) { count += set.contains(value); } } { SCOPED_TIMER(name + " Remove"); for (int value : values) { count += set.remove(value); } } /* Print the value for simple error checking and to avoid some compiler optimizations. */ std::cout << "Count: " << count << "\n"; } TEST(set, Benchmark) { for (int i = 0; i < 3; i++) { benchmark_random_ints<blender::Set<int>>("blender::Set ", 100000, 1); benchmark_random_ints<blender::StdUnorderedSetWrapper<int>>("std::unordered_set", 100000, 1); } std::cout << "\n"; for (int i = 0; i < 3; i++) { uint32_t factor = (3 << 10); benchmark_random_ints<blender::Set<int>>("blender::Set ", 100000, factor); benchmark_random_ints<blender::StdUnorderedSetWrapper<int>>("std::unordered_set", 100000, factor); } } /** * Output of the rudimentary benchmark above on my hardware. * * Timer 'blender::Set Add' took 5.5573 ms * Timer 'blender::Set Contains' took 0.807384 ms * Timer 'blender::Set Remove' took 0.953436 ms * Count: 199998 * Timer 'std::unordered_set Add' took 12.551 ms * Timer 'std::unordered_set Contains' took 2.3323 ms * Timer 'std::unordered_set Remove' took 5.07082 ms * Count: 199998 * Timer 'blender::Set Add' took 2.62526 ms * Timer 'blender::Set Contains' took 0.407499 ms * Timer 'blender::Set Remove' took 0.472981 ms * Count: 199998 * Timer 'std::unordered_set Add' took 6.26945 ms * Timer 'std::unordered_set Contains' took 1.17236 ms * Timer 'std::unordered_set Remove' took 3.77402 ms * Count: 199998 * Timer 'blender::Set Add' took 2.59152 ms * Timer 'blender::Set Contains' took 0.415254 ms * Timer 'blender::Set Remove' took 0.477559 ms * Count: 199998 * Timer 'std::unordered_set Add' took 6.28129 ms * Timer 'std::unordered_set Contains' took 1.17562 ms * Timer 'std::unordered_set Remove' took 3.77811 ms * Count: 199998 * * Timer 'blender::Set Add' took 3.16514 ms * Timer 'blender::Set Contains' took 0.732895 ms * Timer 'blender::Set Remove' took 1.08171 ms * Count: 198790 * Timer 'std::unordered_set Add' took 6.57377 ms * Timer 'std::unordered_set Contains' took 1.17008 ms * Timer 'std::unordered_set Remove' took 3.7946 ms * Count: 198790 * Timer 'blender::Set Add' took 3.11439 ms * Timer 'blender::Set Contains' took 0.740159 ms * Timer 'blender::Set Remove' took 1.06749 ms * Count: 198790 * Timer 'std::unordered_set Add' took 6.35597 ms * Timer 'std::unordered_set Contains' took 1.17713 ms * Timer 'std::unordered_set Remove' took 3.77826 ms * Count: 198790 * Timer 'blender::Set Add' took 3.09876 ms * Timer 'blender::Set Contains' took 0.742072 ms * Timer 'blender::Set Remove' took 1.06622 ms * Count: 198790 * Timer 'std::unordered_set Add' took 6.4469 ms * Timer 'std::unordered_set Contains' took 1.16515 ms * Timer 'std::unordered_set Remove' took 3.80639 ms * Count: 198790 */ #endif /* Benchmark */ } // namespace tests } // namespace blender
23.167732
102
0.65283
Smittyvb
3eab1d54b1b7739bdcbb0ddb5c1a87a3520d412a
2,692
cpp
C++
raftcore/raftlog.cpp
loading86/dugong
3779d73c2ca881eb16a54c9eb00b0ef0456c36ca
[ "BSD-2-Clause" ]
null
null
null
raftcore/raftlog.cpp
loading86/dugong
3779d73c2ca881eb16a54c9eb00b0ef0456c36ca
[ "BSD-2-Clause" ]
null
null
null
raftcore/raftlog.cpp
loading86/dugong
3779d73c2ca881eb16a54c9eb00b0ef0456c36ca
[ "BSD-2-Clause" ]
null
null
null
#include "raftlog.h" namespace raftcore { RaftLog::RaftLog(std::shared_ptr<MemoryStorage> storage, std::shared_ptr<Logger> logger) { m_storage = storage; m_logger = logger; m_volatile_state = std::shared_ptr<VolatileState>(new VolatileState(logger)); uint64_t first_index = storage->FirstIndex(); uint64_t last_index = storage->LastIndex(); m_volatile_state->SetOffset(last_index + 1); m_commit = first_index - 1; m_applied = first_index - 1; } bool RaftLog::Match(uint64_t index, uint64_t term) { uint64_t term_of_index; bool ret = TermOf(index, term_of_index); if(!ret) { return false; } return term == term_of_index; } bool RaftLog::TermOf(uint64_t index, uint64_t& term) { bool ret = m_volatile_state->TermOf(index, term); if(ret) { return true; } ret = m_storage->TermOf(index, term); return ret; } uint64_t RaftLog::FirstIndex() { uint64_t index; bool ret = m_volatile_state->FirstUnstableIndex(index); if(ret) { return index; } return m_storage->FirstIndex(); } uint64_t RaftLog::LastIndex() { uint64_t index; bool ret = m_volatile_state->LastIndex(index); if(ret) { return index; } return m_storage->LastIndex(); } uint64_t RaftLog::FindConflict(const std::deque<Entry>& ents) { for(auto ent: ents) { if(Match(ent.m_index, ent.m_term)) { continue; } return ent.m_index; } return 0; } bool RaftLog::AppendToVolatileState(const std::deque<Entry>& ents, int offset) { if(offset >= ents.size()) { return true; } uint64_t offset_index = ents[0].m_index; assert(offset_index > m_commit); m_volatile_state->Append(ents, offset); return true; } bool RaftLog::Append(uint64_t last_index, uint64_t last_term, uint64_t commit, const std::deque<Entry>& ents) { bool ret = Match(last_index, last_term); if(!ret) { return false; } uint64_t conflict_index = FindConflict(ents); assert(conflict_index > m_commit); AppendToVolatileState(ents, conflict_index - ents[0].m_index); m_commit = std::min(commit, last_index + ents.size()); return true; } }
27.469388
114
0.540862
loading86
3eabfd55021d73c85406dcf55d4406631ecf981f
3,550
cpp
C++
libhttpserver/HttpServer.cpp
c3358/httpsys
e063d575aae56b07de68f5c9b36b535e9cbb5ede
[ "Apache-2.0" ]
1
2021-01-27T16:27:51.000Z
2021-01-27T16:27:51.000Z
libhttpserver/HttpServer.cpp
c3358/httpsys
e063d575aae56b07de68f5c9b36b535e9cbb5ede
[ "Apache-2.0" ]
null
null
null
libhttpserver/HttpServer.cpp
c3358/httpsys
e063d575aae56b07de68f5c9b36b535e9cbb5ede
[ "Apache-2.0" ]
null
null
null
#include "HttpServer.h" #include "ThreadContext.h" #include <iostream> #include <functional> #include <memory> #include <Utils.h> HttpServer::HttpServer( uint32_t numThreads ) : m_hReqQueue(NULL), m_pThreadPool(std::make_unique<httpsys::ThreadPool<ThreadContext>>(numThreads)) { std::cout << "Initialized HttpServer" << std::endl; HTTPAPI_VERSION apiVersion = HTTPAPI_VERSION_1; ULONG ret = HttpInitialize( apiVersion, HTTP_INITIALIZE_SERVER, NULL ); if (ret != NO_ERROR) { std::cout << "Error: " << ret << std::endl; throw std::runtime_error("Error in HttpInitialize"); } ret = HttpCreateHttpHandle( &m_hReqQueue, 0 ); if (ret != NO_ERROR) { std::cout << "Error: " << ret << std::endl; throw std::runtime_error("Error in HttpInitialize"); } } void HttpServer::AddUrl( const std::wstring& url ) { ULONG ret = HttpAddUrl( m_hReqQueue, url.c_str(), NULL ); if (ret != NO_ERROR) { std::cout << "Error: " << ret << std::endl; throw std::runtime_error("Error in HttpAddUrl"); } std::wcout << L"Added url : " << url << L"\n"; m_urls.emplace_back(url); } void HttpServer::HandleRequests( unsigned long payloadSize ) { ULONG requestBufLen = sizeof(HTTP_REQUEST) + payloadSize; HTTP_REQUEST_ID requestId; HTTP_SET_NULL_ID(&requestId); std::vector<char> requestBuf(requestBufLen, 0x00); bool receivedMoreData = false; do { ULONG result = 0; ULONG bytesRead = 0; PHTTP_REQUEST pHttpRequest = reinterpret_cast<PHTTP_REQUEST>(requestBuf.data()); receivedMoreData = false; RtlZeroMemory(pHttpRequest, requestBufLen); result = HttpReceiveHttpRequest( m_hReqQueue, requestId, 0, pHttpRequest, requestBufLen, &bytesRead, NULL ); if (NO_ERROR == result) { if (NO_ERROR != (result = DispatchRequest(requestBuf))) { std::cout << " Error: " << result << std::endl; break; } } else if (ERROR_MORE_DATA == result) { // input buffer too small to handle incoming data ErrorUtils::PrintCSBackupAPIErrorMessage(result); requestBuf.resize(bytesRead, 0x0); receivedMoreData = true; } else if (ERROR_CONNECTION_INVALID == result && !HTTP_IS_NULL_ID(&requestId)) { // TCP connection corrupted by peer ErrorUtils::PrintCSBackupAPIErrorMessage(result); HTTP_SET_NULL_ID(&requestId); } else { ErrorUtils::PrintCSBackupAPIErrorMessage(result); break; } } while (receivedMoreData); } ULONG HttpServer::DispatchRequest( std::vector<char>& buf, ULONG bytesRead ) { ULONG result = 0; PHTTP_REQUEST pHttpRequest = reinterpret_cast<PHTTP_REQUEST>(buf.data()); switch (pHttpRequest->Verb) { case HttpVerbGET: { std::wcout << L"Got http GET for " << pHttpRequest->CookedUrl.pFullUrl << std::endl; HttpSendResponseCallback cb(m_hReqQueue, buf, 200, "OK", "Server Hello!"); ThreadContext thCtx{ HttpRequestType::HTTP_GET, cb }; m_pThreadPool->AddJob(thCtx); break; } case HttpVerbPOST: { std::wcout << L"Got http POST for " << pHttpRequest->CookedUrl.pFullUrl << std::endl; break; } default: { break; } } return result; } void HttpServer::Cleanup() { m_pThreadPool->KillThreads(); for (auto const& url : m_urls) { HttpRemoveUrl(m_hReqQueue, url.c_str()); } if (m_hReqQueue) { CloseHandle(m_hReqQueue); } HttpTerminate(HTTP_INITIALIZE_SERVER, NULL); std::cout << "Cleanup finished!" << std::endl; }
22.327044
89
0.655775
c3358
3eb18f68f3900d6ffdaf1e4abc02b4281582b149
647
cpp
C++
mesh/plan.cpp
Baloululu/ParticulesSystem
c91b7733ce3eeb3e1078de190ec1124a56582f9f
[ "MIT" ]
null
null
null
mesh/plan.cpp
Baloululu/ParticulesSystem
c91b7733ce3eeb3e1078de190ec1124a56582f9f
[ "MIT" ]
null
null
null
mesh/plan.cpp
Baloululu/ParticulesSystem
c91b7733ce3eeb3e1078de190ec1124a56582f9f
[ "MIT" ]
null
null
null
#include "plan.h" Plan::Plan() : Mesh() { nbVertices = 4; nbIndices = 6; vertices.push_back(VertexData {QVector3D(-1.0f, -1.0f, 0.0f), QVector4D(0.0f, 0.0f, 0.0f, 1.0f)} ); vertices.push_back(VertexData {QVector3D(1.0f, -1.0f, 0.0f), QVector4D(0.0f, 0.0f, 0.0f, 1.0f)} ); vertices.push_back(VertexData {QVector3D(-1.0f, 1.0f, 0.0f), QVector4D(0.0f, 0.0f, 0.0f, 1.0f)} ); vertices.push_back(VertexData {QVector3D(1.0f, 1.0f, 0.0f), QVector4D(0.0f, 0.0f, 0.0f, 1.0f)} ); indices.push_back(0); indices.push_back(1); indices.push_back(2); indices.push_back(3); indices.push_back(2); indices.push_back(1); allocate(); } Plan::~Plan() { }
29.409091
100
0.659969
Baloululu
3eb20711b5a82b30e5555bc17e0ea226c4f9158f
166
cc
C++
src/TMPL/test/tstDemo.cc
wawiesel/BOTG-SkeletonRepo
27b99d7456fba1f23d91fab84762f5227f86131e
[ "MIT" ]
1
2017-03-20T02:56:41.000Z
2017-03-20T02:56:41.000Z
src/TMPL/test/tstDemo.cc
wawiesel/BOTG-SkeletonRepo
27b99d7456fba1f23d91fab84762f5227f86131e
[ "MIT" ]
null
null
null
src/TMPL/test/tstDemo.cc
wawiesel/BOTG-SkeletonRepo
27b99d7456fba1f23d91fab84762f5227f86131e
[ "MIT" ]
null
null
null
#include "TMPL/Demo.hh" #include "t123/TestFile.hh" namespace TMPL { namespace test { TEST( Demo, Basic ) { EXPECT_EQ( 10, cxx_function(5) ); } }//test }//TMPL
11.066667
37
0.656627
wawiesel
3eb2ae07475bd19b3d8dcb9057246a43f85a1c7d
1,261
cpp
C++
t1_math/program.cpp
depthBuffer/T1-
9fdebf931e8dd5edaa7613cc0dd435f8f00106e4
[ "Apache-2.0" ]
null
null
null
t1_math/program.cpp
depthBuffer/T1-
9fdebf931e8dd5edaa7613cc0dd435f8f00106e4
[ "Apache-2.0" ]
null
null
null
t1_math/program.cpp
depthBuffer/T1-
9fdebf931e8dd5edaa7613cc0dd435f8f00106e4
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include "test/test_vector.h" #include "test/test_matrix.h" #include "test/test_operations.h" #include "test/test_common.h" #include "test/test_transformations.h" // todo: check googletest for testing. bool TEST_SUCCESS = true; #define TEST(name) \ if (name()) { std::cout << "|O| SUCCESS: "#name << std::endl; } \ else { std::cout << "|X| FAILED: "#name << std::endl; TEST_SUCCESS = false; } \ int main(int argc, char *argv[]) // arguments int to char { // run vector math tests TEST(VectorConstruct); TEST(VectorIndexing); // run matrix math tests TEST(MatrixConstruct); TEST(MatrixIndexing); // run matrix/vector operations math tests TEST(VectorOperation); TEST(MatrixOperation); TEST(VectorMatrixOperation); // run common math tests TEST(LerpFunctions); TEST(ClampFunctions); TEST(RangeFunctions); TEST(StepFunctions); // run transformations matrix/vector math tests TEST(MatrixTransformation); std::cout << std::endl; if (TEST_SUCCESS) std::cout << "|O| Tests succesfully completed." << std::endl; else std::cout << "|X| Tests did not all complete succesfully, re-validate code." << std::endl; int c; std::cin >> c; return 1; }
25.734694
92
0.66138
depthBuffer
3eb88a500b37d6d747004620ef22a76de60007fd
307,527
cpp
C++
RSDKv4/Drawing.cpp
0xR00KIE/Decomp-for-S1F
c8ffedd211f25bb46803f9d637baf1b1fc635db0
[ "Unlicense" ]
2
2022-01-15T05:05:39.000Z
2022-03-19T07:36:31.000Z
RSDKv4/Drawing.cpp
LittlePlanetCD/Decomp-for-S1F
c8ffedd211f25bb46803f9d637baf1b1fc635db0
[ "Unlicense" ]
null
null
null
RSDKv4/Drawing.cpp
LittlePlanetCD/Decomp-for-S1F
c8ffedd211f25bb46803f9d637baf1b1fc635db0
[ "Unlicense" ]
null
null
null
#include "RetroEngine.hpp" ushort blendLookupTable[BLENDTABLE_SIZE]; ushort subtractLookupTable[BLENDTABLE_SIZE]; ushort tintLookupTable[TINTTABLE_SIZE]; int SCREEN_XSIZE = 426; int SCREEN_CENTERX = 426 / 2; int touchWidth = SCREEN_XSIZE; int touchHeight = SCREEN_YSIZE; DrawListEntry drawListEntries[DRAWLAYER_COUNT]; int gfxDataPosition = 0; GFXSurface gfxSurface[SURFACE_MAX]; byte graphicData[GFXDATA_MAX]; #if RETRO_HARDWARE_RENDER DrawVertex gfxPolyList[VERTEX_LIMIT]; short gfxPolyListIndex[INDEX_LIMIT]; ushort gfxVertexSize = 0; ushort gfxVertexSizeOpaque = 0; ushort gfxIndexSize = 0; ushort gfxIndexSizeOpaque = 0; DrawVertex3D polyList3D[VERTEX3D_LIMIT]; ushort vertexSize3D = 0; ushort indexSize3D = 0; float tileUVArray[TILEUV_SIZE]; float floor3DXPos = 0.0f; float floor3DYPos = 0.0f; float floor3DZPos = 0.0f; float floor3DAngle = 0; bool render3DEnabled = false; bool hq3DFloorEnabled = false; ushort texBuffer[TEXBUFFER_SIZE]; byte texBufferMode = 0; int orthWidth = 0; int viewWidth = 0; int viewHeight = 0; float viewAspect = 0; int bufferWidth = 0; int bufferHeight = 0; int virtualX = 0; int virtualY = 0; int virtualWidth = 0; int virtualHeight = 0; #if RETRO_USING_OPENGL GLuint gfxTextureID[TEXTURE_LIMIT]; GLuint framebufferId = 0; GLuint fbTextureId = 0; short screenVerts[] = { 0, 0, 6400, 0, 0, SCREEN_YSIZE << 4, 6400, 0, 0, SCREEN_YSIZE << 4, 6400, SCREEN_YSIZE << 4 }; float fbTexVerts[] = { -TEXTURE_SIZE, TEXTURE_SIZE, 0, TEXTURE_SIZE, -TEXTURE_SIZE, 0, 0, TEXTURE_SIZE, -TEXTURE_SIZE, 0, 0, 0, }; float pureLight[] = { 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0 }; #endif #endif #if !RETRO_USE_ORIGINAL_CODE // enable integer scaling, which is a modification of enhanced scaling bool integerScaling = false; // allows me to disable it to prevent blur on resolutions that match only on 1 axis bool disableEnhancedScaling = false; // enable bilinear scaling, which just disables the fancy upscaling that enhanced scaling does. bool bilinearScaling = false; #endif int InitRenderDevice() { char gameTitle[0x40]; sprintf(gameTitle, "%s%s", Engine.gameWindowText, Engine.usingDataFile ? "" : ""); #if !RETRO_USE_ORIGINAL_CODE #if RETRO_USING_SDL2 SDL_Init(SDL_INIT_EVERYTHING); SDL_DisableScreenSaver(); SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "nearest"); SDL_SetHint(SDL_HINT_RENDER_VSYNC, Engine.vsync ? "1" : "0"); byte flags = 0; #if RETRO_USING_OPENGL flags |= SDL_WINDOW_OPENGL; #endif #if RETRO_DEVICETYPE == RETRO_STANDARD flags |= SDL_WINDOW_HIDDEN; #else Engine.startFullScreen = true; SDL_DisplayMode dm; SDL_GetDesktopDisplayMode(0, &dm); bool landscape = dm.h < dm.w; int h = landscape ? dm.w : dm.h; int w = landscape ? dm.h : dm.w; SCREEN_XSIZE = ((float)SCREEN_YSIZE * h / w); if (SCREEN_XSIZE % 2) ++SCREEN_XSIZE; #endif SCREEN_CENTERX = SCREEN_XSIZE / 2; Engine.window = SDL_CreateWindow(gameTitle, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, SCREEN_XSIZE * Engine.windowScale, SCREEN_YSIZE * Engine.windowScale, SDL_WINDOW_ALLOW_HIGHDPI | flags); Engine.renderer = SDL_CreateRenderer(Engine.window, -1, SDL_RENDERER_ACCELERATED); if (!Engine.window) { printLog("ERROR: failed to create window!"); return 0; } if (!Engine.renderer) { printLog("ERROR: failed to create renderer!"); return 0; } SDL_RenderSetLogicalSize(Engine.renderer, SCREEN_XSIZE, SCREEN_YSIZE); SDL_SetRenderDrawBlendMode(Engine.renderer, SDL_BLENDMODE_BLEND); #if RETRO_SOFTWARE_RENDER Engine.screenBuffer = SDL_CreateTexture(Engine.renderer, SDL_PIXELFORMAT_RGB565, SDL_TEXTUREACCESS_STREAMING, SCREEN_XSIZE, SCREEN_YSIZE); if (!Engine.screenBuffer) { printLog("ERROR: failed to create screen buffer!\nerror msg: %s", SDL_GetError()); return 0; } Engine.screenBuffer2x = SDL_CreateTexture(Engine.renderer, SDL_PIXELFORMAT_RGB565, SDL_TEXTUREACCESS_STREAMING, SCREEN_XSIZE * 2, SCREEN_YSIZE * 2); if (!Engine.screenBuffer2x) { printLog("ERROR: failed to create screen buffer HQ!\nerror msg: %s", SDL_GetError()); return 0; } #endif if (Engine.startFullScreen) { SDL_RestoreWindow(Engine.window); SDL_SetWindowFullscreen(Engine.window, SDL_WINDOW_FULLSCREEN_DESKTOP); SDL_ShowCursor(SDL_FALSE); Engine.isFullScreen = true; } if (Engine.borderless) { SDL_RestoreWindow(Engine.window); SDL_SetWindowBordered(Engine.window, SDL_FALSE); } SDL_DisplayMode disp; if (SDL_GetDisplayMode(0, 0, &disp) == 0) { Engine.screenRefreshRate = disp.refresh_rate; } #endif #if RETRO_USING_SDL1 SDL_Init(SDL_INIT_EVERYTHING); Engine.windowSurface = SDL_SetVideoMode(SCREEN_XSIZE * Engine.windowScale, SCREEN_YSIZE * Engine.windowScale, 32, SDL_SWSURFACE); if (!Engine.windowSurface) { printLog("ERROR: failed to create window!\nerror msg: %s", SDL_GetError()); return 0; } // Set the window caption SDL_WM_SetCaption(gameTitle, NULL); Engine.screenBuffer = SDL_CreateRGBSurface(0, SCREEN_XSIZE * Engine.windowScale, SCREEN_YSIZE * Engine.windowScale, 16, 0xF800, 0x7E0, 0x1F, 0x00); if (!Engine.screenBuffer) { printLog("ERROR: failed to create screen buffer!\nerror msg: %s", SDL_GetError()); return 0; } /*Engine.screenBuffer2x = SDL_SetVideoMode(SCREEN_XSIZE * 2, SCREEN_YSIZE * 2, 16, SDL_SWSURFACE); if (!Engine.screenBuffer2x) { printLog("ERROR: failed to create screen buffer HQ!\nerror msg: %s", SDL_GetError()); return 0; }*/ if (Engine.startFullScreen) { Engine.windowSurface = SDL_SetVideoMode(SCREEN_XSIZE * Engine.windowScale, SCREEN_YSIZE * Engine.windowScale, 16, SDL_SWSURFACE | SDL_FULLSCREEN); SDL_ShowCursor(SDL_FALSE); Engine.isFullScreen = true; } // TODO: not supported in 1.2? if (Engine.borderless) { // SDL_RestoreWindow(Engine.window); // SDL_SetWindowBordered(Engine.window, SDL_FALSE); } // SDL_SetWindowPosition(Engine.window, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED); Engine.useHQModes = false; // disabled Engine.borderless = false; // disabled #endif #if RETRO_USING_OPENGL // Init GL Engine.m_glContext = SDL_GL_CreateContext(Engine.window); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2); SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 16); // glew Setup GLenum err = glewInit(); if (err != GLEW_OK) { printLog("glew init error:"); printLog((const char *)glewGetErrorString(err)); return false; } glViewport(0, 0, SCREEN_XSIZE * Engine.windowScale, SCREEN_YSIZE * Engine.windowScale); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(-2.0, 2.0, -2.0, 2.0, -20.0, 20.0); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LESS); glShadeModel(GL_SMOOTH); glClearColor(0.0, 0.0, 0.0, 1.0); glDisable(GL_LIGHTING); glDisable(GL_DITHER); glEnable(GL_TEXTURE_2D); glDisable(GL_DEPTH_TEST); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); SetupPolygonLists(); for (int i = 0; i < TEXTURE_LIMIT; i++) { glGenTextures(1, &gfxTextureID[i]); glBindTexture(GL_TEXTURE_2D, gfxTextureID[i]); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, TEXTURE_SIZE, TEXTURE_SIZE, 0, GL_RGBA, GL_UNSIGNED_SHORT_5_5_5_1, texBuffer); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); } glMatrixMode(GL_TEXTURE); glLoadIdentity(); // Allows for texture locations in pixels instead of from 0.0 to 1.0, saves us having to do this every time we set UVs glScalef(1.0 / TEXTURE_SIZE, 1.0 / TEXTURE_SIZE, 1.0f); glMatrixMode(GL_PROJECTION); glClear(GL_COLOR_BUFFER_BIT); glEnableClientState(GL_VERTEX_ARRAY); glEnableClientState(GL_TEXTURE_COORD_ARRAY); glClear(GL_COLOR_BUFFER_BIT); framebufferId = 0; fbTextureId = 0; SetScreenDimensions(SCREEN_XSIZE, SCREEN_YSIZE, Engine.windowScale); #endif #if RETRO_SOFTWARE_RENDER Engine.frameBuffer = new ushort[SCREEN_XSIZE * SCREEN_YSIZE]; Engine.frameBuffer2x = new ushort[(SCREEN_XSIZE * 2) * (SCREEN_YSIZE * 2)]; memset(Engine.frameBuffer, 0, (SCREEN_XSIZE * SCREEN_YSIZE) * sizeof(ushort)); memset(Engine.frameBuffer2x, 0, (SCREEN_XSIZE * 2) * (SCREEN_YSIZE * 2) * sizeof(ushort)); #endif #endif OBJECT_BORDER_X2 = SCREEN_XSIZE + 0x80; // OBJECT_BORDER_Y2 = SCREEN_YSIZE + 0x100; OBJECT_BORDER_X4 = SCREEN_XSIZE + 0x20; // OBJECT_BORDER_Y4 = SCREEN_YSIZE + 0x80; return 1; } void FlipScreen() { #if !RETRO_USE_ORIGINAL_CODE if (Engine.dimTimer < Engine.dimLimit) { if (Engine.dimPercent < 1.0) { Engine.dimPercent += 0.05; if (Engine.dimPercent > 1.0) Engine.dimPercent = 1.0; } } else if (Engine.dimPercent > 0.25 && Engine.dimLimit >= 0) { Engine.dimPercent *= 0.9; } float dimAmount = Engine.dimMax * Engine.dimPercent; #if RETRO_SOFTWARE_RENDER #if RETRO_USING_SDL2 SDL_Rect destScreenPos_scaled; SDL_Texture *texTarget = NULL; switch (Engine.scalingMode) { // reset to default if value is invalid. default: Engine.scalingMode = RETRO_DEFAULTSCALINGMODE; break; case 0: break; // nearest case 1: integerScaling = true; break; // integer scaling case 2: break; // sharp bilinear case 3: bilinearScaling = true; break; // regular old bilinear } SDL_GetWindowSize(Engine.window, &Engine.windowXSize, &Engine.windowYSize); float screenxsize = SCREEN_XSIZE; float screenysize = SCREEN_YSIZE; // check if enhanced scaling is even necessary to be calculated by checking if the screen size is close enough on one axis // unfortunately it has to be "close enough" because of floating point precision errors. dang it if (Engine.scalingMode == 2) { bool cond1 = std::round((Engine.windowXSize / screenxsize) * 24) / 24 == std::floor(Engine.windowXSize / screenxsize); bool cond2 = std::round((Engine.windowYSize / screenysize) * 24) / 24 == std::floor(Engine.windowYSize / screenysize); if (cond1 || cond2) disableEnhancedScaling = true; } // get 2x resolution if HQ is enabled. if (drawStageGFXHQ) { screenxsize *= 2; screenysize *= 2; } if (Engine.scalingMode != 0 && !disableEnhancedScaling) { // set up integer scaled texture, which is scaled to the largest integer scale of the screen buffer // before you make a texture that's larger than the window itself. This texture will then be scaled // up to the actual screen size using linear interpolation. This makes even window/screen scales // nice and sharp, and uneven scales as sharp as possible without creating wonky pixel scales, // creating a nice image. // get integer scale float scale = 1; if (!bilinearScaling) { scale = std::fminf(std::floor((float)Engine.windowXSize / (float)SCREEN_XSIZE), std::floor((float)Engine.windowYSize / (float)SCREEN_YSIZE)); } SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "linear"); // set interpolation to linear // create texture that's integer scaled. texTarget = SDL_CreateTexture(Engine.renderer, SDL_PIXELFORMAT_RGB565, SDL_TEXTUREACCESS_TARGET, SCREEN_XSIZE * scale, SCREEN_YSIZE * scale); // keep aspect float aspectScale = std::fminf(Engine.windowYSize / screenysize, Engine.windowXSize / screenxsize); if (integerScaling) { aspectScale = std::floor(aspectScale); } float xoffset = (Engine.windowXSize - (screenxsize * aspectScale)) / 2; float yoffset = (Engine.windowYSize - (screenysize * aspectScale)) / 2; destScreenPos_scaled.x = std::round(xoffset); destScreenPos_scaled.y = std::round(yoffset); destScreenPos_scaled.w = std::round(screenxsize * aspectScale); destScreenPos_scaled.h = std::round(screenysize * aspectScale); // fill the screen with the texture, making lerp work. SDL_RenderSetLogicalSize(Engine.renderer, Engine.windowXSize, Engine.windowYSize); } int pitch = 0; SDL_SetRenderTarget(Engine.renderer, texTarget); // Clear the screen. This is needed to keep the // pillarboxes in fullscreen from displaying garbage data. SDL_RenderClear(Engine.renderer); ushort *pixels = NULL; if (!drawStageGFXHQ) { SDL_LockTexture(Engine.screenBuffer, NULL, (void **)&pixels, &pitch); memcpy(pixels, Engine.frameBuffer, pitch * SCREEN_YSIZE); SDL_UnlockTexture(Engine.screenBuffer); SDL_RenderCopy(Engine.renderer, Engine.screenBuffer, NULL, NULL); } else { int w = 0, h = 0; SDL_QueryTexture(Engine.screenBuffer2x, NULL, NULL, &w, &h); SDL_LockTexture(Engine.screenBuffer2x, NULL, (void **)&pixels, &pitch); ushort *framebufferPtr = Engine.frameBuffer; for (int y = 0; y < (SCREEN_YSIZE / 2) + 12; ++y) { for (int x = 0; x < SCREEN_XSIZE; ++x) { *pixels = *framebufferPtr; pixels++; *pixels = *framebufferPtr; pixels++; framebufferPtr++; } framebufferPtr -= SCREEN_XSIZE; for (int x = 0; x < SCREEN_XSIZE; ++x) { *pixels = *framebufferPtr; pixels++; *pixels = *framebufferPtr; pixels++; framebufferPtr++; } } framebufferPtr = Engine.frameBuffer2x; for (int y = 0; y < ((SCREEN_YSIZE / 2) - 12) * 2; ++y) { for (int x = 0; x < SCREEN_XSIZE; ++x) { *pixels = *framebufferPtr; framebufferPtr++; pixels++; *pixels = *framebufferPtr; framebufferPtr++; pixels++; } } SDL_UnlockTexture(Engine.screenBuffer2x); SDL_RenderCopy(Engine.renderer, Engine.screenBuffer2x, NULL, NULL); } if (Engine.scalingMode != 0 && !disableEnhancedScaling) { // set render target back to the screen. SDL_SetRenderTarget(Engine.renderer, NULL); // clear the screen itself now, for same reason as above SDL_RenderClear(Engine.renderer); // copy texture to screen with lerp SDL_RenderCopy(Engine.renderer, texTarget, NULL, &destScreenPos_scaled); // Apply dimming SDL_SetRenderDrawColor(Engine.renderer, 0, 0, 0, 0xFF - (dimAmount * 0xFF)); if (dimAmount < 1.0) SDL_RenderFillRect(Engine.renderer, NULL); // finally present it SDL_RenderPresent(Engine.renderer); // reset everything just in case SDL_RenderSetLogicalSize(Engine.renderer, SCREEN_XSIZE, SCREEN_YSIZE); SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "nearest"); // putting some FLEX TAPE� on that memory leak SDL_DestroyTexture(texTarget); } else { // Apply dimming SDL_SetRenderDrawColor(Engine.renderer, 0, 0, 0, 0xFF - (dimAmount * 0xFF)); if (dimAmount < 1.0) SDL_RenderFillRect(Engine.renderer, NULL); // no change here SDL_RenderPresent(Engine.renderer); } SDL_ShowWindow(Engine.window); #endif #if RETRO_USING_SDL1 ushort *px = (ushort *)Engine.screenBuffer->pixels; int w = SCREEN_XSIZE * Engine.windowScale; int h = SCREEN_YSIZE * Engine.windowScale; if (Engine.windowScale == 1) { memcpy(Engine.screenBuffer->pixels, Engine.frameBuffer, Engine.screenBuffer->pitch * SCREEN_YSIZE); } else { // TODO: this better, I really dont know how to use SDL1.2 well lol int dx = 0, dy = 0; do { do { int x = (int)(dx * (1.0f / Engine.windowScale)); int y = (int)(dy * (1.0f / Engine.windowScale)); px[dx + (dy * w)] = Engine.frameBuffer[x + (y * SCREEN_XSIZE)]; dx++; } while (dx < w); dy++; dx = 0; } while (dy < h); } // Apply image to screen SDL_BlitSurface(Engine.screenBuffer, NULL, Engine.windowSurface, NULL); // Update Screen SDL_Flip(Engine.windowSurface); #endif #endif // !RETRO_SOFTWARE_RENDER #if RETRO_HARDWARE_RENDER glBindFramebuffer(GL_FRAMEBUFFER, framebufferId); glLoadIdentity(); glOrtho(0, orthWidth, SCREEN_YSIZE << 4, 0.0, 0.0f, 100.0f); if (texPaletteNum >= TEXTURE_LIMIT) { glBindTexture(GL_TEXTURE_2D, gfxTextureID[texPaletteNum % TEXTURE_LIMIT]); } else { glBindTexture(GL_TEXTURE_2D, gfxTextureID[texPaletteNum]); } glEnableClientState(GL_COLOR_ARRAY); if (render3DEnabled) { // Non Blended rendering glVertexPointer(2, GL_SHORT, sizeof(DrawVertex), &gfxPolyList[0].x); glTexCoordPointer(2, GL_SHORT, sizeof(DrawVertex), &gfxPolyList[0].u); glColorPointer(4, GL_UNSIGNED_BYTE, sizeof(DrawVertex), &gfxPolyList[0].colour); glDrawElements(GL_TRIANGLES, gfxIndexSizeOpaque, GL_UNSIGNED_SHORT, gfxPolyListIndex); glEnable(GL_BLEND); // Init 3D Plane glViewport(0, 0, viewWidth, viewHeight); glPushMatrix(); glLoadIdentity(); CalcPerspective(1.8326f, viewAspect, 0.1f, 1000.0f); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glScalef(1.0f, -1.0f, -1.0f); glRotatef(180.0f + floor3DAngle, 0, 1.0f, 0); glTranslatef(floor3DXPos, floor3DYPos, floor3DZPos); glVertexPointer(3, GL_FLOAT, sizeof(DrawVertex3D), &polyList3D[0].x); glTexCoordPointer(2, GL_SHORT, sizeof(DrawVertex3D), &polyList3D[0].u); glColorPointer(4, GL_UNSIGNED_BYTE, sizeof(DrawVertex3D), &polyList3D[0].colour); glDrawElements(GL_TRIANGLES, indexSize3D, GL_UNSIGNED_SHORT, gfxPolyListIndex); glLoadIdentity(); glMatrixMode(GL_PROJECTION); // Return for blended rendering glViewport(0, 0, bufferWidth, bufferHeight); glPopMatrix(); int numBlendedGfx = (int)(gfxIndexSize - gfxIndexSizeOpaque); glVertexPointer(2, GL_SHORT, sizeof(DrawVertex), &gfxPolyList[0].x); glTexCoordPointer(2, GL_SHORT, sizeof(DrawVertex), &gfxPolyList[0].u); glColorPointer(4, GL_UNSIGNED_BYTE, sizeof(DrawVertex), &gfxPolyList[0].colour); glDrawElements(GL_TRIANGLES, numBlendedGfx, GL_UNSIGNED_SHORT, &gfxPolyListIndex[gfxIndexSizeOpaque]); } else { glVertexPointer(2, GL_SHORT, sizeof(DrawVertex), &gfxPolyList[0].x); glTexCoordPointer(2, GL_SHORT, sizeof(DrawVertex), &gfxPolyList[0].u); glColorPointer(4, GL_UNSIGNED_BYTE, sizeof(DrawVertex), &gfxPolyList[0].colour); glDrawElements(GL_TRIANGLES, gfxIndexSizeOpaque, GL_UNSIGNED_SHORT, gfxPolyListIndex); int blendedGfxCount = gfxIndexSize - gfxIndexSizeOpaque; glEnable(GL_BLEND); glEnable(GL_TEXTURE_2D); glVertexPointer(2, GL_SHORT, sizeof(DrawVertex), &gfxPolyList[0].x); glTexCoordPointer(2, GL_SHORT, sizeof(DrawVertex), &gfxPolyList[0].u); glColorPointer(4, GL_UNSIGNED_BYTE, sizeof(DrawVertex), &gfxPolyList[0].colour); glDrawElements(GL_TRIANGLES, blendedGfxCount, GL_UNSIGNED_SHORT, &gfxPolyListIndex[gfxIndexSizeOpaque]); } glDisableClientState(GL_COLOR_ARRAY); // Render the framebuffer now glBindFramebuffer(GL_FRAMEBUFFER, 0); glClearColor(0.0f, 0.0f, 0.0f, 1.0f); glClear(GL_COLOR_BUFFER_BIT); glViewport(virtualX, virtualY, virtualWidth, virtualHeight); glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, fbTextureId); glVertexPointer(2, GL_SHORT, 0, &screenVerts); glTexCoordPointer(2, GL_FLOAT, 0, &fbTexVerts); glColorPointer(4, GL_FLOAT, 0, &pureLight); glDrawArrays(GL_TRIANGLES, 0, 6); glViewport(0, 0, bufferWidth, bufferHeight); #endif #endif } void ReleaseRenderDevice() { #if !RETRO_USE_ORIGINAL_CODE #if RETRO_SOFTWARE_RENDER if (Engine.frameBuffer) delete[] Engine.frameBuffer; #if RETRO_USING_SDL2 SDL_DestroyTexture(Engine.screenBuffer); Engine.screenBuffer = NULL; #endif #if RETRO_USING_SDL1 SDL_FreeSurface(Engine.screenBuffer); #endif #endif #if RETRO_USING_OPENGL if (Engine.m_glContext) SDL_GL_DeleteContext(Engine.m_glContext); #endif #if RETRO_USING_SDL2 SDL_DestroyRenderer(Engine.renderer); SDL_DestroyWindow(Engine.window); #endif #endif } void GenerateBlendLookupTable(void) { int blendTableID = 0; for (int y = 0; y < BLENDTABLE_YSIZE; y++) { for (int x = 0; x < BLENDTABLE_XSIZE; x++) { blendLookupTable[blendTableID] = y * x >> 8; subtractLookupTable[blendTableID++] = y * ((BLENDTABLE_XSIZE - 1) - x) >> 8; } } for (int i = 0; i < TINTTABLE_SIZE; i++) { int tintValue = ((i & 0x1F) + ((i & 0x7E0) >> 6) + ((i & 0xF800) >> 11)) / 3 + 6; if (tintValue > 31) tintValue = 31; tintLookupTable[i] = 0x841 * tintValue; } } void ClearScreen(byte index) { #if RETRO_SOFTWARE_RENDER ushort colour = activePalette[index]; ushort *framebuffer = Engine.frameBuffer; int cnt = SCREEN_XSIZE * SCREEN_YSIZE; while (cnt--) { *framebuffer = colour; ++framebuffer; } #endif #if RETRO_HARDWARE_RENDER gfxPolyList[gfxVertexSize].x = 0.0f; gfxPolyList[gfxVertexSize].y = 0.0f; gfxPolyList[gfxVertexSize].colour.r = activePalette32[index].r; gfxPolyList[gfxVertexSize].colour.g = activePalette32[index].g; gfxPolyList[gfxVertexSize].colour.b = activePalette32[index].b; gfxPolyList[gfxVertexSize].colour.a = 0xFF; gfxPolyList[gfxVertexSize].u = 0.0f; gfxPolyList[gfxVertexSize].v = 0.0f; gfxVertexSize++; gfxPolyList[gfxVertexSize].x = SCREEN_XSIZE << 4; gfxPolyList[gfxVertexSize].y = 0.0f; gfxPolyList[gfxVertexSize].colour.r = activePalette32[index].r; gfxPolyList[gfxVertexSize].colour.g = activePalette32[index].g; gfxPolyList[gfxVertexSize].colour.b = activePalette32[index].b; gfxPolyList[gfxVertexSize].colour.a = 0xFF; gfxPolyList[gfxVertexSize].u = 0.0f; gfxPolyList[gfxVertexSize].v = 0.0f; gfxVertexSize++; gfxPolyList[gfxVertexSize].x = 0.0f; gfxPolyList[gfxVertexSize].y = SCREEN_YSIZE << 4; gfxPolyList[gfxVertexSize].colour.r = activePalette32[index].r; gfxPolyList[gfxVertexSize].colour.g = activePalette32[index].g; gfxPolyList[gfxVertexSize].colour.b = activePalette32[index].b; gfxPolyList[gfxVertexSize].colour.a = 0xFF; gfxPolyList[gfxVertexSize].u = 0.0f; gfxPolyList[gfxVertexSize].v = 0.0f; gfxVertexSize++; gfxPolyList[gfxVertexSize].x = SCREEN_XSIZE << 4; gfxPolyList[gfxVertexSize].y = SCREEN_YSIZE << 4; gfxPolyList[gfxVertexSize].colour.r = activePalette32[index].r; gfxPolyList[gfxVertexSize].colour.g = activePalette32[index].g; gfxPolyList[gfxVertexSize].colour.b = activePalette32[index].b; gfxPolyList[gfxVertexSize].colour.a = 0xFF; gfxPolyList[gfxVertexSize].u = 0.0f; gfxPolyList[gfxVertexSize].v = 0.0f; gfxVertexSize++; gfxIndexSize += 6; #endif } void SetScreenSize(int width, int height) { SCREEN_XSIZE = width; SCREEN_CENTERX = width / 2; SCREEN_SCROLL_LEFT = SCREEN_CENTERX - 8; SCREEN_SCROLL_RIGHT = SCREEN_CENTERX + 8; OBJECT_BORDER_X2 = width + 0x80; OBJECT_BORDER_X4 = width + 0x20; // SCREEN_YSIZE = height; // SCREEN_CENTERY = (height / 2); // SCREEN_SCROLL_UP = (height / 2) - 8; // SCREEN_SCROLL_DOWN = (height / 2) + 8; // OBJECT_BORDER_Y2 = height + 0x100; // OBJECT_BORDER_Y4 = height + 0x80; } #if RETRO_SOFTWARE_RENDER void CopyFrameOverlay2x() { ushort *frameBuffer = &Engine.frameBuffer[((SCREEN_YSIZE / 2) + 12) * SCREEN_XSIZE]; ushort *frameBuffer2x = Engine.frameBuffer2x; for (int y = 0; y < (SCREEN_YSIZE / 2) - 12; ++y) { for (int x = 0; x < SCREEN_XSIZE; ++x) { if (*frameBuffer == 0xF81F) { // magenta frameBuffer2x += 2; } else { *frameBuffer2x = *frameBuffer; frameBuffer2x++; *frameBuffer2x = *frameBuffer; frameBuffer2x++; } ++frameBuffer; } frameBuffer -= SCREEN_XSIZE; for (int x = 0; x < SCREEN_XSIZE; ++x) { if (*frameBuffer == 0xF81F) { // magenta frameBuffer2x += 2; } else { *frameBuffer2x = *frameBuffer; frameBuffer2x++; *frameBuffer2x = *frameBuffer; frameBuffer2x++; } ++frameBuffer; } } } #endif #if RETRO_HARDWARE_RENDER void UpdateHardwareTextures() { SetActivePalette(0, 0, SCREEN_YSIZE); UpdateTextureBufferWithTiles(); UpdateTextureBufferWithSortedSprites(); glBindTexture(GL_TEXTURE_2D, gfxTextureID[0]); glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, TEXTURE_SIZE, TEXTURE_SIZE, GL_RGBA, GL_UNSIGNED_SHORT_5_5_5_1, texBuffer); for (byte b = 1; b < TEXTURE_LIMIT; ++b) { SetActivePalette(b, 0, SCREEN_YSIZE); UpdateTextureBufferWithTiles(); UpdateTextureBufferWithSprites(); glBindTexture(GL_TEXTURE_2D, gfxTextureID[b]); glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, TEXTURE_SIZE, TEXTURE_SIZE, GL_RGBA, GL_UNSIGNED_SHORT_5_5_5_1, texBuffer); } SetActivePalette(0, 0, SCREEN_YSIZE); } void SetScreenDimensions(int width, int height, int scale) { viewWidth = touchWidth = width * scale; viewHeight = touchHeight = height * scale; // float widthBuf = (float)viewWidth / (float)viewHeight; // widthBuf *= (float)SCREEN_YSIZE; bufferWidth = width; // bufferWidth += 8; // bufferWidth = bufferWidth >> 4 << 4; width *= scale; height *= scale; viewAspect = 0.75f; if (viewHeight >= SCREEN_YSIZE * 2) hq3DFloorEnabled = true; else hq3DFloorEnabled = false; SetScreenSize(bufferWidth, bufferWidth); if (viewHeight >= SCREEN_YSIZE * 2) { bufferWidth *= 2; bufferHeight = SCREEN_YSIZE * 2; } else { bufferHeight = SCREEN_YSIZE; } orthWidth = SCREEN_XSIZE * 16; if (framebufferId > 0) { glDeleteFramebuffers(1, &framebufferId); } if (fbTextureId > 0) { glDeleteTextures(1, &fbTextureId); } // Setup framebuffer texture glGenFramebuffers(1, &framebufferId); glBindFramebuffer(GL_FRAMEBUFFER, framebufferId); glGenTextures(1, &fbTextureId); glBindTexture(GL_TEXTURE_2D, fbTextureId); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, viewWidth, viewHeight, 0, GL_RGB, GL_UNSIGNED_BYTE, NULL); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glBindTexture(GL_TEXTURE_2D, 0); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, fbTextureId, 0); glBindFramebuffer(GL_FRAMEBUFFER, 0); int newWidth = width * 8; int newHeight = (height * 8) + 4; screenVerts[2] = newWidth; screenVerts[6] = newWidth; screenVerts[10] = newWidth; screenVerts[5] = newHeight; screenVerts[9] = newHeight; screenVerts[11] = newHeight; ScaleViewport(width, height); } void ScaleViewport(int width, int height) { virtualWidth = width; virtualHeight = height; virtualX = 0; virtualY = 0; float virtualAspect = (float)width / height; float realAspect = (float)viewWidth / viewHeight; if (virtualAspect < realAspect) { virtualHeight = viewHeight * ((float)width / viewWidth); virtualY = (height - virtualHeight) >> 1; } else { virtualWidth = viewWidth * ((float)height / viewHeight); virtualX = (width - virtualWidth) >> 1; } } void CalcPerspective(float fov, float aspectRatio, float nearPlane, float farPlane) { float matrix[16]; float w = 1.0 / tanf(fov * 0.5f); float h = 1.0 / (w * aspectRatio); float q = (nearPlane + farPlane) / (farPlane - nearPlane); matrix[0] = w; matrix[1] = 0; matrix[2] = 0; matrix[3] = 0; matrix[4] = 0; matrix[5] = h / 2; matrix[6] = 0; matrix[7] = 0; matrix[8] = 0; matrix[9] = 0; matrix[10] = q; matrix[11] = 1.0; matrix[12] = 0; matrix[13] = 0; matrix[14] = (((farPlane * -2.0f) * nearPlane) / (farPlane - nearPlane)); matrix[15] = 0; #if RETRO_USING_OPENGL glMultMatrixf(matrix); #endif } void SetupPolygonLists() { int vID = 0; for (int i = 0; i < VERTEX_LIMIT; i++) { gfxPolyListIndex[vID++] = (i << 2) + 0; gfxPolyListIndex[vID++] = (i << 2) + 1; gfxPolyListIndex[vID++] = (i << 2) + 2; gfxPolyListIndex[vID++] = (i << 2) + 1; gfxPolyListIndex[vID++] = (i << 2) + 3; gfxPolyListIndex[vID++] = (i << 2) + 2; gfxPolyList[i].colour.r = 0xFF; gfxPolyList[i].colour.g = 0xFF; gfxPolyList[i].colour.b = 0xFF; gfxPolyList[i].colour.a = 0xFF; } for (int i = 0; i < VERTEX3D_LIMIT; i++) { polyList3D[i].colour.r = 0xFF; polyList3D[i].colour.g = 0xFF; polyList3D[i].colour.b = 0xFF; polyList3D[i].colour.a = 0xFF; } } void UpdateTextureBufferWithTiles() { int cnt = 0; if (texBufferMode == 0) { for (int h = 0; h < 512; h += 16) { for (int w = 0; w < 512; w += 16) { int dataPos = cnt << 8; cnt++; int bufPos = w + (h << 10); for (int y = 0; y < TILE_SIZE; y++) { for (int x = 0; x < TILE_SIZE; x++) { if (tilesetGFXData[dataPos] > 0) { texBuffer[bufPos] = fullPalette[texPaletteNum][tilesetGFXData[dataPos]]; } else { texBuffer[bufPos] = 0; } bufPos++; dataPos++; } bufPos += 1008; } } } } else { for (int h = 0; h < 504; h += 18) { for (int w = 0; w < 504; w += 18) { int dataPos = cnt << 8; cnt++; if (cnt == 783) cnt = 1023; int bufPos = w + (h << 10); if (tilesetGFXData[dataPos] > 0) { texBuffer[bufPos] = fullPalette[texPaletteNum][tilesetGFXData[dataPos]]; } else { texBuffer[bufPos] = 0; } bufPos++; for (int l = 0; l < 15; l++) { if (tilesetGFXData[dataPos] > 0) { texBuffer[bufPos] = fullPalette[texPaletteNum][tilesetGFXData[dataPos]]; } else { texBuffer[bufPos] = 0; } bufPos++; dataPos++; } if (tilesetGFXData[dataPos] > 0) { texBuffer[bufPos] = fullPalette[texPaletteNum][tilesetGFXData[dataPos]]; bufPos++; texBuffer[bufPos] = fullPalette[texPaletteNum][tilesetGFXData[dataPos]]; } else { texBuffer[bufPos] = 0; bufPos++; texBuffer[bufPos] = 0; } bufPos++; dataPos -= 15; bufPos += 1006; for (int k = 0; k < 16; k++) { if (tilesetGFXData[dataPos] > 0) { texBuffer[bufPos] = fullPalette[texPaletteNum][tilesetGFXData[dataPos]]; } else { texBuffer[bufPos] = 0; } bufPos++; for (int l = 0; l < 15; l++) { if (tilesetGFXData[dataPos] > 0) { texBuffer[bufPos] = fullPalette[texPaletteNum][tilesetGFXData[dataPos]]; } else { texBuffer[bufPos] = 0; } bufPos++; dataPos++; } if (tilesetGFXData[dataPos] > 0) { texBuffer[bufPos] = fullPalette[texPaletteNum][tilesetGFXData[dataPos]]; bufPos++; texBuffer[bufPos] = fullPalette[texPaletteNum][tilesetGFXData[dataPos]]; } else { texBuffer[bufPos] = 0; bufPos++; texBuffer[bufPos] = 0; } bufPos++; dataPos++; bufPos += 1006; } dataPos -= 16; if (tilesetGFXData[dataPos] > 0) { texBuffer[bufPos] = fullPalette[texPaletteNum][tilesetGFXData[dataPos]]; } else { texBuffer[bufPos] = 0; } bufPos++; for (int l = 0; l < 15; l++) { if (tilesetGFXData[dataPos] > 0) { texBuffer[bufPos] = fullPalette[texPaletteNum][tilesetGFXData[dataPos]]; } else { texBuffer[bufPos] = 0; } bufPos++; dataPos++; } if (tilesetGFXData[dataPos] > 0) { texBuffer[bufPos] = fullPalette[texPaletteNum][tilesetGFXData[dataPos]]; bufPos++; texBuffer[bufPos] = fullPalette[texPaletteNum][tilesetGFXData[dataPos]]; } else { texBuffer[bufPos] = 0; bufPos++; texBuffer[bufPos] = 0; } bufPos++; bufPos += 1006; } } } int bufPos = 0; for (int k = 0; k < TILE_SIZE; k++) { for (int l = 0; l < TILE_SIZE; l++) { texBuffer[bufPos] = PACK_RGB888(0xFF, 0xFF, 0xFF); texBuffer[bufPos] |= 1; bufPos++; } bufPos += 1008; } } void UpdateTextureBufferWithSortedSprites() { byte surfCnt = 0; byte surfList[SURFACE_MAX]; bool flag = true; for (int i = 0; i < SURFACE_MAX; i++) gfxSurface[i].texStartX = -1; for (int i = 0; i < SURFACE_MAX; i++) { int gfxSize = 0; sbyte surfID = -1; for (int s = 0; s < SURFACE_MAX; s++) { GFXSurface *surface = &gfxSurface[s]; if (StrLength(surface->fileName) && surface->texStartX == -1) { if (CheckSurfaceSize(surface->width) && CheckSurfaceSize(surface->height)) { if (surface->width + surface->height > gfxSize) { gfxSize = surface->width + surface->height; surfID = s; } } else { surface->texStartX = 0; } } } if (surfID == -1) { i = SURFACE_MAX; } else { gfxSurface[surfID].texStartX = 0; surfList[surfCnt++] = surfID; } } for (int i = 0; i < SURFACE_MAX; i++) gfxSurface[i].texStartX = -1; for (int i = 0; i < surfCnt; i++) { GFXSurface *curSurface = &gfxSurface[surfList[i]]; curSurface->texStartX = 0; curSurface->texStartY = 0; bool loopFlag = true; while (loopFlag) { loopFlag = false; if (curSurface->height == TEXTURE_SIZE) flag = false; if (flag) { if (curSurface->texStartX < 512 && curSurface->texStartY < 512) { loopFlag = true; curSurface->texStartX += curSurface->width; if (curSurface->texStartX + curSurface->width > TEXTURE_SIZE) { curSurface->texStartX = 0; curSurface->texStartY += curSurface->height; } } else { for (int s = 0; s < SURFACE_MAX; s++) { GFXSurface *surface = &gfxSurface[s]; if (surface->texStartX > -1 && s != surfList[i] && curSurface->texStartX < surface->texStartX + surface->width && curSurface->texStartX >= surface->texStartX && curSurface->texStartY < surface->texStartY + surface->height) { loopFlag = true; curSurface->texStartX += curSurface->width; if (curSurface->texStartX + curSurface->width > TEXTURE_SIZE) { curSurface->texStartX = 0; curSurface->texStartY += curSurface->height; } s = SURFACE_MAX; } } } } else { if (curSurface->width < TEXTURE_SIZE) { if (curSurface->texStartX < 16 && curSurface->texStartY < 16) { loopFlag = true; curSurface->texStartX += curSurface->width; if (curSurface->texStartX + curSurface->width > TEXTURE_SIZE) { curSurface->texStartX = 0; curSurface->texStartY += curSurface->height; } } else { for (int s = 0; s < SURFACE_MAX; s++) { GFXSurface *surface = &gfxSurface[s]; if (surface->texStartX > -1 && s != surfList[i] && curSurface->texStartX < surface->texStartX + surface->width && curSurface->texStartX >= surface->texStartX && curSurface->texStartY < surface->texStartY + surface->height) { loopFlag = true; curSurface->texStartX += curSurface->width; if (curSurface->texStartX + curSurface->width > TEXTURE_SIZE) { curSurface->texStartX = 0; curSurface->texStartY += curSurface->height; } s = SURFACE_MAX; } } } } } } if (curSurface->texStartY + curSurface->height <= TEXTURE_SIZE) { int gfXPos = curSurface->dataPosition; int dataPos = curSurface->texStartX + (curSurface->texStartY << 10); for (int h = 0; h < curSurface->height; h++) { for (int w = 0; w < curSurface->width; w++) { if (graphicData[gfXPos] > 0) { texBuffer[dataPos] = fullPalette[texPaletteNum][graphicData[gfXPos]]; } else { texBuffer[dataPos] = 0; } dataPos++; gfXPos++; } dataPos += TEXTURE_SIZE - curSurface->width; } } } } void UpdateTextureBufferWithSprites() { for (int i = 0; i < SURFACE_MAX; ++i) { if (gfxSurface[i].texStartY + gfxSurface[i].height <= TEXTURE_SIZE && gfxSurface[i].texStartX > -1) { int pos = gfxSurface[i].dataPosition; int teXPos = gfxSurface[i].texStartX + (gfxSurface[i].texStartY << 10); for (int j = 0; j < gfxSurface[i].height; j++) { for (int k = 0; k < gfxSurface[i].width; k++) { if (graphicData[pos] > 0) texBuffer[teXPos] = fullPalette[texPaletteNum][graphicData[pos]]; else texBuffer[teXPos] = 0; teXPos++; pos++; } teXPos += TEXTURE_SIZE - gfxSurface[i].width; } } } } #endif void DrawObjectList(int Layer) { int size = drawListEntries[Layer].listSize; for (int i = 0; i < size; ++i) { objectEntityPos = drawListEntries[Layer].entityRefs[i]; int type = objectEntityList[objectEntityPos].type; if (type) { if (scriptData[objectScriptList[type].eventDraw.scriptCodePtr] > 0) ProcessScript(objectScriptList[type].eventDraw.scriptCodePtr, objectScriptList[type].eventDraw.jumpTablePtr, EVENT_DRAW); } } } void DrawStageGFX() { waterDrawPos = waterLevel - yScrollOffset; #if RETRO_HARDWARE_RENDER gfxVertexSize = 0; gfxIndexSize = 0; if (waterDrawPos < -TILE_SIZE) waterDrawPos = -TILE_SIZE; if (waterDrawPos >= SCREEN_YSIZE) waterDrawPos = SCREEN_YSIZE + TILE_SIZE; #endif #if RETRO_SOFTWARE_RENDER if (waterDrawPos < 0) waterDrawPos = 0; if (waterDrawPos > SCREEN_YSIZE) waterDrawPos = SCREEN_YSIZE; #endif if (tLayerMidPoint < 3) { DrawObjectList(0); if (activeTileLayers[0] < LAYER_COUNT) { switch (stageLayouts[activeTileLayers[0]].type) { case LAYER_HSCROLL: DrawHLineScrollLayer(0); break; case LAYER_VSCROLL: DrawVLineScrollLayer(0); break; case LAYER_3DFLOOR: #if RETRO_SOFTWARE_RENDER drawStageGFXHQ = false; #endif Draw3DFloorLayer(0); break; case LAYER_3DSKY: #if RETRO_SOFTWARE_RENDER #if !RETRO_USE_ORIGINAL_CODE if (Engine.useHQModes) #endif drawStageGFXHQ = true; Draw3DSkyLayer(0); #endif #if RETRO_HARDWARE_RENDER Draw3DFloorLayer(0); #endif break; default: break; } } #if RETRO_HARDWARE_RENDER gfxIndexSizeOpaque = gfxIndexSize; gfxVertexSizeOpaque = gfxVertexSize; #endif DrawObjectList(1); if (activeTileLayers[1] < LAYER_COUNT) { switch (stageLayouts[activeTileLayers[1]].type) { case LAYER_HSCROLL: DrawHLineScrollLayer(1); break; case LAYER_VSCROLL: DrawVLineScrollLayer(1); break; case LAYER_3DFLOOR: #if RETRO_SOFTWARE_RENDER drawStageGFXHQ = false; #endif Draw3DFloorLayer(1); break; case LAYER_3DSKY: #if RETRO_SOFTWARE_RENDER #if !RETRO_USE_ORIGINAL_CODE if (Engine.useHQModes) #endif drawStageGFXHQ = true; Draw3DSkyLayer(1); #endif #if RETRO_HARDWARE_RENDER Draw3DFloorLayer(1); #endif break; default: break; } } DrawObjectList(2); DrawObjectList(3); DrawObjectList(4); if (activeTileLayers[2] < LAYER_COUNT) { switch (stageLayouts[activeTileLayers[2]].type) { case LAYER_HSCROLL: DrawHLineScrollLayer(2); break; case LAYER_VSCROLL: DrawVLineScrollLayer(2); break; case LAYER_3DFLOOR: #if RETRO_SOFTWARE_RENDER drawStageGFXHQ = false; #endif Draw3DFloorLayer(2); break; case LAYER_3DSKY: #if RETRO_SOFTWARE_RENDER #if !RETRO_USE_ORIGINAL_CODE if (Engine.useHQModes) #endif drawStageGFXHQ = true; Draw3DSkyLayer(2); #endif #if RETRO_HARDWARE_RENDER Draw3DFloorLayer(2); #endif break; default: break; } } } else if (tLayerMidPoint < 6) { DrawObjectList(0); if (activeTileLayers[0] < LAYER_COUNT) { switch (stageLayouts[activeTileLayers[0]].type) { case LAYER_HSCROLL: DrawHLineScrollLayer(0); break; case LAYER_VSCROLL: DrawVLineScrollLayer(0); break; case LAYER_3DFLOOR: #if RETRO_SOFTWARE_RENDER drawStageGFXHQ = false; #endif Draw3DFloorLayer(0); break; case LAYER_3DSKY: #if RETRO_SOFTWARE_RENDER #if !RETRO_USE_ORIGINAL_CODE if (Engine.useHQModes) #endif drawStageGFXHQ = true; Draw3DSkyLayer(0); #endif #if RETRO_HARDWARE_RENDER Draw3DFloorLayer(0); #endif break; default: break; } } #if RETRO_HARDWARE_RENDER gfxIndexSizeOpaque = gfxIndexSize; gfxVertexSizeOpaque = gfxVertexSize; #endif DrawObjectList(1); if (activeTileLayers[1] < LAYER_COUNT) { switch (stageLayouts[activeTileLayers[1]].type) { case LAYER_HSCROLL: DrawHLineScrollLayer(1); break; case LAYER_VSCROLL: DrawVLineScrollLayer(1); break; case LAYER_3DFLOOR: #if RETRO_SOFTWARE_RENDER drawStageGFXHQ = false; #endif Draw3DFloorLayer(1); break; case LAYER_3DSKY: #if RETRO_SOFTWARE_RENDER #if !RETRO_USE_ORIGINAL_CODE if (Engine.useHQModes) #endif drawStageGFXHQ = true; Draw3DSkyLayer(1); #endif #if RETRO_HARDWARE_RENDER Draw3DFloorLayer(1); #endif break; default: break; } } DrawObjectList(2); if (activeTileLayers[2] < LAYER_COUNT) { switch (stageLayouts[activeTileLayers[2]].type) { case LAYER_HSCROLL: DrawHLineScrollLayer(2); break; case LAYER_VSCROLL: DrawVLineScrollLayer(2); break; case LAYER_3DFLOOR: #if RETRO_SOFTWARE_RENDER drawStageGFXHQ = false; #endif Draw3DFloorLayer(2); break; case LAYER_3DSKY: #if RETRO_SOFTWARE_RENDER #if !RETRO_USE_ORIGINAL_CODE if (Engine.useHQModes) #endif drawStageGFXHQ = true; Draw3DSkyLayer(2); #endif #if RETRO_HARDWARE_RENDER Draw3DFloorLayer(2); #endif break; default: break; } } DrawObjectList(3); DrawObjectList(4); } if (tLayerMidPoint < 6) { if (activeTileLayers[3] < LAYER_COUNT) { switch (stageLayouts[activeTileLayers[3]].type) { case LAYER_HSCROLL: DrawHLineScrollLayer(3); break; case LAYER_VSCROLL: DrawVLineScrollLayer(3); break; case LAYER_3DFLOOR: #if RETRO_SOFTWARE_RENDER drawStageGFXHQ = false; #endif Draw3DFloorLayer(3); break; case LAYER_3DSKY: #if RETRO_SOFTWARE_RENDER #if !RETRO_USE_ORIGINAL_CODE if (Engine.useHQModes) #endif drawStageGFXHQ = true; Draw3DSkyLayer(3); #endif #if RETRO_HARDWARE_RENDER Draw3DFloorLayer(3); #endif break; default: break; } } DrawObjectList(5); DrawObjectList(6); } #if RETRO_SOFTWARE_RENDER if (drawStageGFXHQ) { CopyFrameOverlay2x(); if (fadeMode > 0) { DrawRectangle(0, 0, SCREEN_XSIZE, SCREEN_YSIZE, fadeR, fadeG, fadeB, fadeA); SetFadeHQ(fadeR, fadeG, fadeB, fadeA); } } else { if (fadeMode > 0) { DrawRectangle(0, 0, SCREEN_XSIZE, SCREEN_YSIZE, fadeR, fadeG, fadeB, fadeA); } } #endif #if RETRO_HARDWARE_RENDER if (fadeMode > 0) { DrawRectangle(0, 0, SCREEN_XSIZE, SCREEN_YSIZE, fadeR, fadeG, fadeB, fadeA); } #endif #if !RETRO_USE_ORIGINAL_CODE if (Engine.showPaletteOverlay) { for (int p = 0; p < PALETTE_COUNT; ++p) { int x = (SCREEN_XSIZE - (0xF << 3)); int y = (SCREEN_YSIZE - (0xF << 2)); for (int c = 0; c < PALETTE_SIZE; ++c) { DrawRectangle(x + ((c & 0xF) << 1) + ((p % (PALETTE_COUNT / 2)) * (2 * 16)), y + ((c >> 4) << 1) + ((p / (PALETTE_COUNT / 2)) * (2 * 16)), 2, 2, fullPalette32[p][c].r, fullPalette32[p][c].g, fullPalette32[p][c].b, 0xFF); } } } #endif } void DrawHLineScrollLayer(int layerID) { #if RETRO_SOFTWARE_RENDER TileLayer *layer = &stageLayouts[activeTileLayers[layerID]]; int screenwidth16 = (SCREEN_XSIZE >> 4) - 1; int layerwidth = layer->width; int layerheight = layer->height; bool aboveMidPoint = layerID >= tLayerMidPoint; byte *lineScroll; int *deformationData; int *deformationDataW; int yscrollOffset = 0; if (activeTileLayers[layerID]) { // BG Layer int yScroll = yScrollOffset * layer->parallaxFactor >> 8; int fullheight = layerheight << 7; layer->scrollPos += layer->scrollSpeed; if (layer->scrollPos > fullheight << 16) layer->scrollPos -= fullheight << 16; yscrollOffset = (yScroll + (layer->scrollPos >> 16)) % fullheight; layerheight = fullheight >> 7; lineScroll = layer->lineScroll; deformationData = &bgDeformationData2[(byte)(yscrollOffset + layer->deformationOffset)]; deformationDataW = &bgDeformationData3[(byte)(yscrollOffset + waterDrawPos + layer->deformationOffsetW)]; } else { // FG Layer lastXSize = layer->width; yscrollOffset = yScrollOffset; lineScroll = layer->lineScroll; for (int i = 0; i < PARALLAX_COUNT; ++i) hParallax.linePos[i] = xScrollOffset; deformationData = &bgDeformationData0[(byte)(yscrollOffset + layer->deformationOffset)]; deformationDataW = &bgDeformationData1[(byte)(yscrollOffset + waterDrawPos + layer->deformationOffsetW)]; } if (layer->type == LAYER_HSCROLL) { if (lastXSize != layerwidth) { int fullLayerwidth = layerwidth << 7; for (int i = 0; i < hParallax.entryCount; ++i) { hParallax.linePos[i] = xScrollOffset * hParallax.parallaxFactor[i] >> 8; if (hParallax.scrollPos[i] > fullLayerwidth << 16) hParallax.scrollPos[i] -= fullLayerwidth << 16; if (hParallax.scrollPos[i] < 0) hParallax.scrollPos[i] += fullLayerwidth << 16; hParallax.linePos[i] += hParallax.scrollPos[i] >> 16; hParallax.linePos[i] %= fullLayerwidth; } } int w = -1; if (activeTileLayers[layerID]) w = layerwidth; lastXSize = w; } ushort *frameBufferPtr = Engine.frameBuffer; byte *lineBuffer = gfxLineBuffer; int tileYPos = yscrollOffset % (layerheight << 7); if (tileYPos < 0) tileYPos += layerheight << 7; byte *scrollIndex = &lineScroll[tileYPos]; int tileY16 = tileYPos & 0xF; int chunkY = tileYPos >> 7; int tileY = (tileYPos & 0x7F) >> 4; // Draw Above Water (if applicable) int drawableLines[2] = { waterDrawPos, SCREEN_YSIZE - waterDrawPos }; for (int i = 0; i < 2; ++i) { while (drawableLines[i]--) { activePalette = fullPalette[*lineBuffer]; activePalette32 = fullPalette32[*lineBuffer]; lineBuffer++; int chunkX = hParallax.linePos[*scrollIndex]; if (i == 0) { if (hParallax.deform[*scrollIndex]) chunkX += *deformationData; ++deformationData; } else { if (hParallax.deform[*scrollIndex]) chunkX += *deformationDataW; ++deformationDataW; } ++scrollIndex; int fullLayerwidth = layerwidth << 7; if (chunkX < 0) chunkX += fullLayerwidth; if (chunkX >= fullLayerwidth) chunkX -= fullLayerwidth; int chunkXPos = chunkX >> 7; int tilePxXPos = chunkX & 0xF; int tileXPxRemain = TILE_SIZE - tilePxXPos; int chunk = (layer->tiles[(chunkX >> 7) + (chunkY << 8)] << 6) + ((chunkX & 0x7F) >> 4) + 8 * tileY; int tileOffsetY = TILE_SIZE * tileY16; int tileOffsetYFlipX = TILE_SIZE * tileY16 + 0xF; int tileOffsetYFlipY = TILE_SIZE * (0xF - tileY16); int tileOffsetYFlipXY = TILE_SIZE * (0xF - tileY16) + 0xF; int lineRemain = SCREEN_XSIZE; byte *gfxDataPtr = NULL; int tilePxLineCnt = 0; // Draw the first tile to the left if (tiles128x128.visualPlane[chunk] == (byte)aboveMidPoint) { tilePxLineCnt = TILE_SIZE - tilePxXPos; lineRemain -= tilePxLineCnt; switch (tiles128x128.direction[chunk]) { case FLIP_NONE: gfxDataPtr = &tilesetGFXData[tileOffsetY + tiles128x128.gfxDataPos[chunk] + tilePxXPos]; while (tilePxLineCnt--) { if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; ++frameBufferPtr; ++gfxDataPtr; } break; case FLIP_X: gfxDataPtr = &tilesetGFXData[tileOffsetYFlipX + tiles128x128.gfxDataPos[chunk] - tilePxXPos]; while (tilePxLineCnt--) { if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; ++frameBufferPtr; --gfxDataPtr; } break; case FLIP_Y: gfxDataPtr = &tilesetGFXData[tileOffsetYFlipY + tiles128x128.gfxDataPos[chunk] + tilePxXPos]; while (tilePxLineCnt--) { if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; ++frameBufferPtr; ++gfxDataPtr; } break; case FLIP_XY: gfxDataPtr = &tilesetGFXData[tileOffsetYFlipXY + tiles128x128.gfxDataPos[chunk] - tilePxXPos]; while (tilePxLineCnt--) { if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; ++frameBufferPtr; --gfxDataPtr; } break; default: break; } } else { frameBufferPtr += tileXPxRemain; lineRemain -= tileXPxRemain; } // Draw the bulk of the tiles int chunkTileX = ((chunkX & 0x7F) >> 4) + 1; int tilesPerLine = screenwidth16; while (tilesPerLine--) { if (chunkTileX <= 7) { ++chunk; } else { if (++chunkXPos == layerwidth) chunkXPos = 0; chunkTileX = 0; chunk = (layer->tiles[chunkXPos + (chunkY << 8)] << 6) + 8 * tileY; } lineRemain -= TILE_SIZE; // Loop Unrolling (faster but messier code) if (tiles128x128.visualPlane[chunk] == (byte)aboveMidPoint) { switch (tiles128x128.direction[chunk]) { case FLIP_NONE: gfxDataPtr = &tilesetGFXData[tiles128x128.gfxDataPos[chunk] + tileOffsetY]; if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; ++frameBufferPtr; ++gfxDataPtr; if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; ++frameBufferPtr; ++gfxDataPtr; if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; ++frameBufferPtr; ++gfxDataPtr; if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; ++frameBufferPtr; ++gfxDataPtr; if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; ++frameBufferPtr; ++gfxDataPtr; if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; ++frameBufferPtr; ++gfxDataPtr; if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; ++frameBufferPtr; ++gfxDataPtr; if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; ++frameBufferPtr; ++gfxDataPtr; if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; ++frameBufferPtr; ++gfxDataPtr; if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; ++frameBufferPtr; ++gfxDataPtr; if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; ++frameBufferPtr; ++gfxDataPtr; if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; ++frameBufferPtr; ++gfxDataPtr; if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; ++frameBufferPtr; ++gfxDataPtr; if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; ++frameBufferPtr; ++gfxDataPtr; if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; ++frameBufferPtr; ++gfxDataPtr; if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; ++frameBufferPtr; ++gfxDataPtr; break; case FLIP_X: gfxDataPtr = &tilesetGFXData[tiles128x128.gfxDataPos[chunk] + tileOffsetYFlipX]; if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; ++frameBufferPtr; --gfxDataPtr; if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; ++frameBufferPtr; --gfxDataPtr; if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; ++frameBufferPtr; --gfxDataPtr; if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; ++frameBufferPtr; --gfxDataPtr; if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; ++frameBufferPtr; --gfxDataPtr; if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; ++frameBufferPtr; --gfxDataPtr; if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; ++frameBufferPtr; --gfxDataPtr; if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; ++frameBufferPtr; --gfxDataPtr; if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; ++frameBufferPtr; --gfxDataPtr; if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; ++frameBufferPtr; --gfxDataPtr; if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; ++frameBufferPtr; --gfxDataPtr; if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; ++frameBufferPtr; --gfxDataPtr; if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; ++frameBufferPtr; --gfxDataPtr; if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; ++frameBufferPtr; --gfxDataPtr; if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; ++frameBufferPtr; --gfxDataPtr; if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; ++frameBufferPtr; --gfxDataPtr; break; case FLIP_Y: gfxDataPtr = &tilesetGFXData[tiles128x128.gfxDataPos[chunk] + tileOffsetYFlipY]; if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; ++frameBufferPtr; ++gfxDataPtr; if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; ++frameBufferPtr; ++gfxDataPtr; if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; ++frameBufferPtr; ++gfxDataPtr; if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; ++frameBufferPtr; ++gfxDataPtr; if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; ++frameBufferPtr; ++gfxDataPtr; if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; ++frameBufferPtr; ++gfxDataPtr; if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; ++frameBufferPtr; ++gfxDataPtr; if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; ++frameBufferPtr; ++gfxDataPtr; if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; ++frameBufferPtr; ++gfxDataPtr; if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; ++frameBufferPtr; ++gfxDataPtr; if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; ++frameBufferPtr; ++gfxDataPtr; if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; ++frameBufferPtr; ++gfxDataPtr; if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; ++frameBufferPtr; ++gfxDataPtr; if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; ++frameBufferPtr; ++gfxDataPtr; if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; ++frameBufferPtr; ++gfxDataPtr; if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; ++frameBufferPtr; ++gfxDataPtr; break; case FLIP_XY: gfxDataPtr = &tilesetGFXData[tiles128x128.gfxDataPos[chunk] + tileOffsetYFlipXY]; if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; ++frameBufferPtr; --gfxDataPtr; if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; ++frameBufferPtr; --gfxDataPtr; if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; ++frameBufferPtr; --gfxDataPtr; if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; ++frameBufferPtr; --gfxDataPtr; if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; ++frameBufferPtr; --gfxDataPtr; if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; ++frameBufferPtr; --gfxDataPtr; if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; ++frameBufferPtr; --gfxDataPtr; if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; ++frameBufferPtr; --gfxDataPtr; if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; ++frameBufferPtr; --gfxDataPtr; if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; ++frameBufferPtr; --gfxDataPtr; if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; ++frameBufferPtr; --gfxDataPtr; if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; ++frameBufferPtr; --gfxDataPtr; if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; ++frameBufferPtr; --gfxDataPtr; if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; ++frameBufferPtr; --gfxDataPtr; if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; ++frameBufferPtr; --gfxDataPtr; if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; ++frameBufferPtr; --gfxDataPtr; break; } } else { frameBufferPtr += 0x10; } ++chunkTileX; } // Draw any remaining tiles while (lineRemain > 0) { if (chunkTileX++ <= 7) { ++chunk; } else { chunkTileX = 0; if (++chunkXPos == layerwidth) chunkXPos = 0; chunk = (layer->tiles[chunkXPos + (chunkY << 8)] << 6) + 8 * tileY; } tilePxLineCnt = lineRemain >= TILE_SIZE ? TILE_SIZE : lineRemain; lineRemain -= tilePxLineCnt; if (tiles128x128.visualPlane[chunk] == (byte)aboveMidPoint) { switch (tiles128x128.direction[chunk]) { case FLIP_NONE: gfxDataPtr = &tilesetGFXData[tiles128x128.gfxDataPos[chunk] + tileOffsetY]; while (tilePxLineCnt--) { if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; ++frameBufferPtr; ++gfxDataPtr; } break; case FLIP_X: gfxDataPtr = &tilesetGFXData[tiles128x128.gfxDataPos[chunk] + tileOffsetYFlipX]; while (tilePxLineCnt--) { if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; ++frameBufferPtr; --gfxDataPtr; } break; case FLIP_Y: gfxDataPtr = &tilesetGFXData[tiles128x128.gfxDataPos[chunk] + tileOffsetYFlipY]; while (tilePxLineCnt--) { if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; ++frameBufferPtr; ++gfxDataPtr; } break; case FLIP_XY: gfxDataPtr = &tilesetGFXData[tiles128x128.gfxDataPos[chunk] + tileOffsetYFlipXY]; while (tilePxLineCnt--) { if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; ++frameBufferPtr; --gfxDataPtr; } break; default: break; } } else { frameBufferPtr += tilePxLineCnt; } } if (++tileY16 > TILE_SIZE - 1) { tileY16 = 0; ++tileY; } if (tileY > 7) { if (++chunkY == layerheight) { chunkY = 0; scrollIndex -= 0x80 * layerheight; } tileY = 0; } } } #endif #if RETRO_HARDWARE_RENDER TileLayer *layer = &stageLayouts[activeTileLayers[layerID]]; byte *lineScrollPtr = NULL; int chunkPosX = 0; int chunkTileX = 0; int gfxIndex = 0; int yscrollOffset = 0; int tileGFXPos = 0; int deformX1 = 0; int deformX2 = 0; byte highPlane = layerID >= tLayerMidPoint; int *deformationData = NULL; int *deformationDataW = NULL; int deformOffset = 0; int deformOffsetW = 0; int lineID = 0; int layerWidth = layer->width; int layerHeight = layer->height; int renderWidth = (SCREEN_XSIZE >> 4) + 3; bool flag = false; if (activeTileLayers[layerID]) { layer = &stageLayouts[activeTileLayers[layerID]]; yscrollOffset = layer->parallaxFactor * yScrollOffset >> 8; layerHeight = layerHeight << 7; layer->scrollPos = layer->scrollPos + layer->scrollSpeed; if (layer->scrollPos > layerHeight << 16) { layer->scrollPos -= (layerHeight << 16); } yscrollOffset += (layer->scrollPos >> 16); yscrollOffset %= layerHeight; layerHeight = layerHeight >> 7; lineScrollPtr = layer->lineScroll; deformOffset = (byte)(layer->deformationOffset + yscrollOffset); deformOffsetW = (byte)(layer->deformationOffsetW + yscrollOffset); deformationData = bgDeformationData2; deformationDataW = bgDeformationData3; } else { layer = &stageLayouts[0]; lastXSize = layerWidth; yscrollOffset = yScrollOffset; lineScrollPtr = layer->lineScroll; hParallax.linePos[0] = xScrollOffset; deformOffset = (byte)(stageLayouts[0].deformationOffset + yscrollOffset); deformOffsetW = (byte)(stageLayouts[0].deformationOffsetW + yscrollOffset); deformationData = bgDeformationData0; deformationDataW = bgDeformationData1; yscrollOffset %= (layerHeight << 7); } if (layer->type == LAYER_HSCROLL) { if (lastXSize != layerWidth) { layerWidth = layerWidth << 7; for (int i = 0; i < hParallax.entryCount; i++) { hParallax.linePos[i] = hParallax.parallaxFactor[i] * xScrollOffset >> 8; hParallax.scrollPos[i] = hParallax.scrollPos[i] + hParallax.scrollSpeed[i]; if (hParallax.scrollPos[i] > layerWidth << 16) { hParallax.scrollPos[i] = hParallax.scrollPos[i] - (layerWidth << 16); } hParallax.linePos[i] = hParallax.linePos[i] + (hParallax.scrollPos[i] >> 16); hParallax.linePos[i] = hParallax.linePos[i] % layerWidth; } layerWidth = layerWidth >> 7; } lastXSize = layerWidth; } if (yscrollOffset < 0) yscrollOffset += (layerHeight << 7); int deformY = yscrollOffset >> 4 << 4; lineID += deformY; deformOffset += (deformY - yscrollOffset); deformOffsetW += (deformY - yscrollOffset); if (deformOffset < 0) deformOffset += 0x100; if (deformOffsetW < 0) deformOffsetW += 0x100; deformY = -(yscrollOffset & 15); int chunkPosY = yscrollOffset >> 7; int chunkTileY = (yscrollOffset & 127) >> 4; waterDrawPos <<= 4; deformY <<= 4; for (int j = (deformY ? 0x110 : 0x100); j > 0; j -= 16) { int parallaxLinePos = hParallax.linePos[lineScrollPtr[lineID]] - 16; lineID += 8; if (parallaxLinePos == hParallax.linePos[lineScrollPtr[lineID]] - 16) { if (hParallax.deform[lineScrollPtr[lineID]]) { deformX1 = deformY < waterDrawPos ? deformationData[deformOffset] : deformationDataW[deformOffsetW]; deformX2 = (deformY + 64) <= waterDrawPos ? deformationData[deformOffset + 8] : deformationDataW[deformOffsetW + 8]; flag = deformX1 != deformX2; } else { flag = false; } } else { flag = true; } lineID -= 8; if (flag) { if (parallaxLinePos < 0) parallaxLinePos += layerWidth << 7; if (parallaxLinePos >= layerWidth << 7) parallaxLinePos -= layerWidth << 7; chunkPosX = parallaxLinePos >> 7; chunkTileX = (parallaxLinePos & 0x7F) >> 4; deformX1 = -((parallaxLinePos & 0xF) << 4); deformX1 -= 0x100; deformX2 = deformX1; if (hParallax.deform[lineScrollPtr[lineID]]) { deformX1 -= deformY < waterDrawPos ? deformationData[deformOffset] : deformationDataW[deformOffsetW]; deformOffset += 8; deformOffsetW += 8; deformX2 -= (deformY + 64) <= waterDrawPos ? deformationData[deformOffset] : deformationDataW[deformOffsetW]; } else { deformOffset += 8; deformOffsetW += 8; } lineID += 8; gfxIndex = (chunkPosX > -1 && chunkPosY > -1) ? (layer->tiles[chunkPosX + (chunkPosY << 8)] << 6) : 0; gfxIndex += chunkTileX + (chunkTileY << 3); for (int i = renderWidth; i > 0; i--) { if (tiles128x128.visualPlane[gfxIndex] == highPlane && tiles128x128.gfxDataPos[gfxIndex] > 0) { tileGFXPos = 0; switch (tiles128x128.direction[gfxIndex]) { case FLIP_NONE: { gfxPolyList[gfxVertexSize].x = deformX1; gfxPolyList[gfxVertexSize].y = deformY; gfxPolyList[gfxVertexSize].u = tileUVArray[tiles128x128.gfxDataPos[gfxIndex] + tileGFXPos]; tileGFXPos++; gfxPolyList[gfxVertexSize].v = tileUVArray[tiles128x128.gfxDataPos[gfxIndex] + tileGFXPos]; tileGFXPos++; gfxPolyList[gfxVertexSize].colour.r = 0xFF; gfxPolyList[gfxVertexSize].colour.g = 0xFF; gfxPolyList[gfxVertexSize].colour.b = 0xFF; gfxPolyList[gfxVertexSize].colour.a = 0xFF; gfxVertexSize++; gfxPolyList[gfxVertexSize].x = deformX1 + (CHUNK_SIZE * 2); gfxPolyList[gfxVertexSize].y = deformY; gfxPolyList[gfxVertexSize].u = tileUVArray[tiles128x128.gfxDataPos[gfxIndex] + tileGFXPos]; tileGFXPos++; gfxPolyList[gfxVertexSize].v = gfxPolyList[gfxVertexSize - 1].v; gfxPolyList[gfxVertexSize].colour.r = 0xFF; gfxPolyList[gfxVertexSize].colour.g = 0xFF; gfxPolyList[gfxVertexSize].colour.b = 0xFF; gfxPolyList[gfxVertexSize].colour.a = 0xFF; gfxVertexSize++; gfxPolyList[gfxVertexSize].x = deformX2; gfxPolyList[gfxVertexSize].y = deformY + CHUNK_SIZE; gfxPolyList[gfxVertexSize].u = gfxPolyList[gfxVertexSize - 2].u; gfxPolyList[gfxVertexSize].v = tileUVArray[tiles128x128.gfxDataPos[gfxIndex] + tileGFXPos] - 8; gfxPolyList[gfxVertexSize].colour.r = 0xFF; gfxPolyList[gfxVertexSize].colour.g = 0xFF; gfxPolyList[gfxVertexSize].colour.b = 0xFF; gfxPolyList[gfxVertexSize].colour.a = 0xFF; gfxVertexSize++; gfxPolyList[gfxVertexSize].x = deformX2 + (CHUNK_SIZE * 2); gfxPolyList[gfxVertexSize].y = gfxPolyList[gfxVertexSize - 1].y; gfxPolyList[gfxVertexSize].u = gfxPolyList[gfxVertexSize - 2].u; gfxPolyList[gfxVertexSize].v = gfxPolyList[gfxVertexSize - 1].v; gfxPolyList[gfxVertexSize].colour.r = 0xFF; gfxPolyList[gfxVertexSize].colour.g = 0xFF; gfxPolyList[gfxVertexSize].colour.b = 0xFF; gfxPolyList[gfxVertexSize].colour.a = 0xFF; gfxVertexSize++; gfxIndexSize += 6; break; } case FLIP_X: { gfxPolyList[gfxVertexSize].x = deformX1 + (CHUNK_SIZE * 2); gfxPolyList[gfxVertexSize].y = deformY; gfxPolyList[gfxVertexSize].u = tileUVArray[tiles128x128.gfxDataPos[gfxIndex] + tileGFXPos]; tileGFXPos++; gfxPolyList[gfxVertexSize].v = tileUVArray[tiles128x128.gfxDataPos[gfxIndex] + tileGFXPos]; tileGFXPos++; gfxPolyList[gfxVertexSize].colour.r = 0xFF; gfxPolyList[gfxVertexSize].colour.g = 0xFF; gfxPolyList[gfxVertexSize].colour.b = 0xFF; gfxPolyList[gfxVertexSize].colour.a = 0xFF; gfxVertexSize++; gfxPolyList[gfxVertexSize].x = deformX1; gfxPolyList[gfxVertexSize].y = deformY; gfxPolyList[gfxVertexSize].u = tileUVArray[tiles128x128.gfxDataPos[gfxIndex] + tileGFXPos]; tileGFXPos++; gfxPolyList[gfxVertexSize].v = gfxPolyList[gfxVertexSize - 1].v; gfxPolyList[gfxVertexSize].colour.r = 0xFF; gfxPolyList[gfxVertexSize].colour.g = 0xFF; gfxPolyList[gfxVertexSize].colour.b = 0xFF; gfxPolyList[gfxVertexSize].colour.a = 0xFF; gfxVertexSize++; gfxPolyList[gfxVertexSize].x = deformX2 + (CHUNK_SIZE * 2); gfxPolyList[gfxVertexSize].y = deformY + CHUNK_SIZE; gfxPolyList[gfxVertexSize].u = gfxPolyList[gfxVertexSize - 2].u; gfxPolyList[gfxVertexSize].v = tileUVArray[tiles128x128.gfxDataPos[gfxIndex] + tileGFXPos] - 8; gfxPolyList[gfxVertexSize].colour.r = 0xFF; gfxPolyList[gfxVertexSize].colour.g = 0xFF; gfxPolyList[gfxVertexSize].colour.b = 0xFF; gfxPolyList[gfxVertexSize].colour.a = 0xFF; gfxVertexSize++; gfxPolyList[gfxVertexSize].x = deformX2; gfxPolyList[gfxVertexSize].y = gfxPolyList[gfxVertexSize - 1].y; gfxPolyList[gfxVertexSize].u = gfxPolyList[gfxVertexSize - 2].u; gfxPolyList[gfxVertexSize].v = gfxPolyList[gfxVertexSize - 1].v; gfxPolyList[gfxVertexSize].colour.r = 0xFF; gfxPolyList[gfxVertexSize].colour.g = 0xFF; gfxPolyList[gfxVertexSize].colour.b = 0xFF; gfxPolyList[gfxVertexSize].colour.a = 0xFF; gfxVertexSize++; gfxIndexSize += 6; break; } case FLIP_Y: { gfxPolyList[gfxVertexSize].x = deformX2; gfxPolyList[gfxVertexSize].y = deformY + CHUNK_SIZE; gfxPolyList[gfxVertexSize].u = tileUVArray[tiles128x128.gfxDataPos[gfxIndex] + tileGFXPos]; tileGFXPos++; gfxPolyList[gfxVertexSize].v = tileUVArray[tiles128x128.gfxDataPos[gfxIndex] + tileGFXPos] + 8; tileGFXPos++; gfxPolyList[gfxVertexSize].colour.r = 0xFF; gfxPolyList[gfxVertexSize].colour.g = 0xFF; gfxPolyList[gfxVertexSize].colour.b = 0xFF; gfxPolyList[gfxVertexSize].colour.a = 0xFF; gfxVertexSize++; gfxPolyList[gfxVertexSize].x = deformX2 + (CHUNK_SIZE * 2); gfxPolyList[gfxVertexSize].y = deformY + CHUNK_SIZE; gfxPolyList[gfxVertexSize].u = tileUVArray[tiles128x128.gfxDataPos[gfxIndex] + tileGFXPos]; tileGFXPos++; gfxPolyList[gfxVertexSize].v = gfxPolyList[gfxVertexSize - 1].v; gfxPolyList[gfxVertexSize].colour.r = 0xFF; gfxPolyList[gfxVertexSize].colour.g = 0xFF; gfxPolyList[gfxVertexSize].colour.b = 0xFF; gfxPolyList[gfxVertexSize].colour.a = 0xFF; gfxVertexSize++; gfxPolyList[gfxVertexSize].x = deformX1; gfxPolyList[gfxVertexSize].y = deformY; gfxPolyList[gfxVertexSize].u = gfxPolyList[gfxVertexSize - 2].u; gfxPolyList[gfxVertexSize].v = tileUVArray[tiles128x128.gfxDataPos[gfxIndex] + tileGFXPos]; gfxPolyList[gfxVertexSize].colour.r = 0xFF; gfxPolyList[gfxVertexSize].colour.g = 0xFF; gfxPolyList[gfxVertexSize].colour.b = 0xFF; gfxPolyList[gfxVertexSize].colour.a = 0xFF; gfxVertexSize++; gfxPolyList[gfxVertexSize].x = deformX1 + (CHUNK_SIZE * 2); gfxPolyList[gfxVertexSize].y = gfxPolyList[gfxVertexSize - 1].y; gfxPolyList[gfxVertexSize].u = gfxPolyList[gfxVertexSize - 2].u; gfxPolyList[gfxVertexSize].v = gfxPolyList[gfxVertexSize - 1].v; gfxPolyList[gfxVertexSize].colour.r = 0xFF; gfxPolyList[gfxVertexSize].colour.g = 0xFF; gfxPolyList[gfxVertexSize].colour.b = 0xFF; gfxPolyList[gfxVertexSize].colour.a = 0xFF; gfxVertexSize++; gfxIndexSize += 6; break; } case FLIP_XY: { gfxPolyList[gfxVertexSize].x = deformX2 + (CHUNK_SIZE * 2); gfxPolyList[gfxVertexSize].y = deformY + CHUNK_SIZE; gfxPolyList[gfxVertexSize].u = tileUVArray[tiles128x128.gfxDataPos[gfxIndex] + tileGFXPos]; tileGFXPos++; gfxPolyList[gfxVertexSize].v = tileUVArray[tiles128x128.gfxDataPos[gfxIndex] + tileGFXPos] + 8; tileGFXPos++; gfxPolyList[gfxVertexSize].colour.r = 0xFF; gfxPolyList[gfxVertexSize].colour.g = 0xFF; gfxPolyList[gfxVertexSize].colour.b = 0xFF; gfxPolyList[gfxVertexSize].colour.a = 0xFF; gfxVertexSize++; gfxPolyList[gfxVertexSize].x = deformX2; gfxPolyList[gfxVertexSize].y = deformY + CHUNK_SIZE; gfxPolyList[gfxVertexSize].u = tileUVArray[tiles128x128.gfxDataPos[gfxIndex] + tileGFXPos]; tileGFXPos++; gfxPolyList[gfxVertexSize].v = gfxPolyList[gfxVertexSize - 1].v; gfxPolyList[gfxVertexSize].colour.r = 0xFF; gfxPolyList[gfxVertexSize].colour.g = 0xFF; gfxPolyList[gfxVertexSize].colour.b = 0xFF; gfxPolyList[gfxVertexSize].colour.a = 0xFF; gfxVertexSize++; gfxPolyList[gfxVertexSize].x = deformX1 + (CHUNK_SIZE * 2); gfxPolyList[gfxVertexSize].y = deformY; gfxPolyList[gfxVertexSize].u = gfxPolyList[gfxVertexSize - 2].u; gfxPolyList[gfxVertexSize].v = tileUVArray[tiles128x128.gfxDataPos[gfxIndex] + tileGFXPos]; gfxPolyList[gfxVertexSize].colour.r = 0xFF; gfxPolyList[gfxVertexSize].colour.g = 0xFF; gfxPolyList[gfxVertexSize].colour.b = 0xFF; gfxPolyList[gfxVertexSize].colour.a = 0xFF; gfxVertexSize++; gfxPolyList[gfxVertexSize].x = deformX1; gfxPolyList[gfxVertexSize].y = gfxPolyList[gfxVertexSize - 1].y; gfxPolyList[gfxVertexSize].u = gfxPolyList[gfxVertexSize - 2].u; gfxPolyList[gfxVertexSize].v = gfxPolyList[gfxVertexSize - 1].v; gfxPolyList[gfxVertexSize].colour.r = 0xFF; gfxPolyList[gfxVertexSize].colour.g = 0xFF; gfxPolyList[gfxVertexSize].colour.b = 0xFF; gfxPolyList[gfxVertexSize].colour.a = 0xFF; gfxVertexSize++; gfxIndexSize += 6; break; } } } deformX1 += (CHUNK_SIZE * 2); deformX2 += (CHUNK_SIZE * 2); if (++chunkTileX < 8) { gfxIndex++; } else { if (++chunkPosX == layerWidth) chunkPosX = 0; chunkTileX = 0; gfxIndex = layer->tiles[chunkPosX + (chunkPosY << 8)] << 6; gfxIndex += chunkTileX + (chunkTileY << 3); } } deformY += CHUNK_SIZE; parallaxLinePos = hParallax.linePos[lineScrollPtr[lineID]] - 16; if (parallaxLinePos < 0) parallaxLinePos += layerWidth << 7; if (parallaxLinePos >= layerWidth << 7) parallaxLinePos -= layerWidth << 7; chunkPosX = parallaxLinePos >> 7; chunkTileX = (parallaxLinePos & 127) >> 4; deformX1 = -((parallaxLinePos & 15) << 4); deformX1 -= 0x100; deformX2 = deformX1; if (!hParallax.deform[lineScrollPtr[lineID]]) { deformOffset += 8; deformOffsetW += 8; } else { deformX1 -= deformY < waterDrawPos ? deformationData[deformOffset] : deformationDataW[deformOffsetW]; deformOffset += 8; deformOffsetW += 8; deformX2 -= (deformY + 64) <= waterDrawPos ? deformationData[deformOffset] : deformationDataW[deformOffsetW]; } lineID += 8; gfxIndex = (chunkPosX > -1 && chunkPosY > -1) ? (layer->tiles[chunkPosX + (chunkPosY << 8)] << 6) : 0; gfxIndex += chunkTileX + (chunkTileY << 3); for (int i = renderWidth; i > 0; i--) { if (tiles128x128.visualPlane[gfxIndex] == highPlane && tiles128x128.gfxDataPos[gfxIndex] > 0) { tileGFXPos = 0; switch (tiles128x128.direction[gfxIndex]) { case FLIP_NONE: { gfxPolyList[gfxVertexSize].x = deformX1; gfxPolyList[gfxVertexSize].y = deformY; gfxPolyList[gfxVertexSize].u = tileUVArray[tiles128x128.gfxDataPos[gfxIndex] + tileGFXPos]; tileGFXPos++; gfxPolyList[gfxVertexSize].v = tileUVArray[tiles128x128.gfxDataPos[gfxIndex] + tileGFXPos] + 8; tileGFXPos++; gfxPolyList[gfxVertexSize].colour.r = 0xFF; gfxPolyList[gfxVertexSize].colour.g = 0xFF; gfxPolyList[gfxVertexSize].colour.b = 0xFF; gfxPolyList[gfxVertexSize].colour.a = 0xFF; gfxVertexSize++; gfxPolyList[gfxVertexSize].x = deformX1 + (CHUNK_SIZE * 2); gfxPolyList[gfxVertexSize].y = deformY; gfxPolyList[gfxVertexSize].u = tileUVArray[tiles128x128.gfxDataPos[gfxIndex] + tileGFXPos]; tileGFXPos++; gfxPolyList[gfxVertexSize].v = gfxPolyList[gfxVertexSize - 1].v; gfxPolyList[gfxVertexSize].colour.r = 0xFF; gfxPolyList[gfxVertexSize].colour.g = 0xFF; gfxPolyList[gfxVertexSize].colour.b = 0xFF; gfxPolyList[gfxVertexSize].colour.a = 0xFF; gfxVertexSize++; gfxPolyList[gfxVertexSize].x = deformX2; gfxPolyList[gfxVertexSize].y = deformY + CHUNK_SIZE; gfxPolyList[gfxVertexSize].u = gfxPolyList[gfxVertexSize - 2].u; gfxPolyList[gfxVertexSize].v = tileUVArray[tiles128x128.gfxDataPos[gfxIndex] + tileGFXPos]; gfxPolyList[gfxVertexSize].colour.r = 0xFF; gfxPolyList[gfxVertexSize].colour.g = 0xFF; gfxPolyList[gfxVertexSize].colour.b = 0xFF; gfxPolyList[gfxVertexSize].colour.a = 0xFF; gfxVertexSize++; gfxPolyList[gfxVertexSize].x = deformX2 + (CHUNK_SIZE * 2); gfxPolyList[gfxVertexSize].y = gfxPolyList[gfxVertexSize - 1].y; gfxPolyList[gfxVertexSize].u = gfxPolyList[gfxVertexSize - 2].u; gfxPolyList[gfxVertexSize].v = gfxPolyList[gfxVertexSize - 1].v; gfxPolyList[gfxVertexSize].colour.r = 0xFF; gfxPolyList[gfxVertexSize].colour.g = 0xFF; gfxPolyList[gfxVertexSize].colour.b = 0xFF; gfxPolyList[gfxVertexSize].colour.a = 0xFF; gfxVertexSize++; gfxIndexSize += 6; break; } case FLIP_X: { gfxPolyList[gfxVertexSize].x = deformX1 + (CHUNK_SIZE * 2); gfxPolyList[gfxVertexSize].y = deformY; gfxPolyList[gfxVertexSize].u = tileUVArray[tiles128x128.gfxDataPos[gfxIndex] + tileGFXPos]; tileGFXPos++; gfxPolyList[gfxVertexSize].v = tileUVArray[tiles128x128.gfxDataPos[gfxIndex] + tileGFXPos] + 8; tileGFXPos++; gfxPolyList[gfxVertexSize].colour.r = 0xFF; gfxPolyList[gfxVertexSize].colour.g = 0xFF; gfxPolyList[gfxVertexSize].colour.b = 0xFF; gfxPolyList[gfxVertexSize].colour.a = 0xFF; gfxVertexSize++; gfxPolyList[gfxVertexSize].x = deformX1; gfxPolyList[gfxVertexSize].y = deformY; gfxPolyList[gfxVertexSize].u = tileUVArray[tiles128x128.gfxDataPos[gfxIndex] + tileGFXPos]; tileGFXPos++; gfxPolyList[gfxVertexSize].v = gfxPolyList[gfxVertexSize - 1].v; gfxPolyList[gfxVertexSize].colour.r = 0xFF; gfxPolyList[gfxVertexSize].colour.g = 0xFF; gfxPolyList[gfxVertexSize].colour.b = 0xFF; gfxPolyList[gfxVertexSize].colour.a = 0xFF; gfxVertexSize++; gfxPolyList[gfxVertexSize].x = deformX2 + (CHUNK_SIZE * 2); gfxPolyList[gfxVertexSize].y = deformY + CHUNK_SIZE; gfxPolyList[gfxVertexSize].u = gfxPolyList[gfxVertexSize - 2].u; gfxPolyList[gfxVertexSize].v = tileUVArray[tiles128x128.gfxDataPos[gfxIndex] + tileGFXPos]; gfxPolyList[gfxVertexSize].colour.r = 0xFF; gfxPolyList[gfxVertexSize].colour.g = 0xFF; gfxPolyList[gfxVertexSize].colour.b = 0xFF; gfxPolyList[gfxVertexSize].colour.a = 0xFF; gfxVertexSize++; gfxPolyList[gfxVertexSize].x = deformX2; gfxPolyList[gfxVertexSize].y = gfxPolyList[gfxVertexSize - 1].y; gfxPolyList[gfxVertexSize].u = gfxPolyList[gfxVertexSize - 2].u; gfxPolyList[gfxVertexSize].v = gfxPolyList[gfxVertexSize - 1].v; gfxPolyList[gfxVertexSize].colour.r = 0xFF; gfxPolyList[gfxVertexSize].colour.g = 0xFF; gfxPolyList[gfxVertexSize].colour.b = 0xFF; gfxPolyList[gfxVertexSize].colour.a = 0xFF; gfxVertexSize++; gfxIndexSize += 6; break; } case FLIP_Y: { gfxPolyList[gfxVertexSize].x = deformX2; gfxPolyList[gfxVertexSize].y = deformY + CHUNK_SIZE; gfxPolyList[gfxVertexSize].u = tileUVArray[tiles128x128.gfxDataPos[gfxIndex] + tileGFXPos]; tileGFXPos++; gfxPolyList[gfxVertexSize].v = tileUVArray[tiles128x128.gfxDataPos[gfxIndex] + tileGFXPos]; tileGFXPos++; gfxPolyList[gfxVertexSize].colour.r = 0xFF; gfxPolyList[gfxVertexSize].colour.g = 0xFF; gfxPolyList[gfxVertexSize].colour.b = 0xFF; gfxPolyList[gfxVertexSize].colour.a = 0xFF; gfxVertexSize++; gfxPolyList[gfxVertexSize].x = deformX2 + (CHUNK_SIZE * 2); gfxPolyList[gfxVertexSize].y = deformY + CHUNK_SIZE; gfxPolyList[gfxVertexSize].u = tileUVArray[tiles128x128.gfxDataPos[gfxIndex] + tileGFXPos]; tileGFXPos++; gfxPolyList[gfxVertexSize].v = gfxPolyList[gfxVertexSize - 1].v; gfxPolyList[gfxVertexSize].colour.r = 0xFF; gfxPolyList[gfxVertexSize].colour.g = 0xFF; gfxPolyList[gfxVertexSize].colour.b = 0xFF; gfxPolyList[gfxVertexSize].colour.a = 0xFF; gfxVertexSize++; gfxPolyList[gfxVertexSize].x = deformX1; gfxPolyList[gfxVertexSize].y = deformY; gfxPolyList[gfxVertexSize].u = gfxPolyList[gfxVertexSize - 2].u; gfxPolyList[gfxVertexSize].v = tileUVArray[tiles128x128.gfxDataPos[gfxIndex] + tileGFXPos] - 8; gfxPolyList[gfxVertexSize].colour.r = 0xFF; gfxPolyList[gfxVertexSize].colour.g = 0xFF; gfxPolyList[gfxVertexSize].colour.b = 0xFF; gfxPolyList[gfxVertexSize].colour.a = 0xFF; gfxVertexSize++; gfxPolyList[gfxVertexSize].x = deformX1 + (CHUNK_SIZE * 2); gfxPolyList[gfxVertexSize].y = gfxPolyList[gfxVertexSize - 1].y; gfxPolyList[gfxVertexSize].u = gfxPolyList[gfxVertexSize - 2].u; gfxPolyList[gfxVertexSize].v = gfxPolyList[gfxVertexSize - 1].v; gfxPolyList[gfxVertexSize].colour.r = 0xFF; gfxPolyList[gfxVertexSize].colour.g = 0xFF; gfxPolyList[gfxVertexSize].colour.b = 0xFF; gfxPolyList[gfxVertexSize].colour.a = 0xFF; gfxVertexSize++; gfxIndexSize += 6; break; } case FLIP_XY: { gfxPolyList[gfxVertexSize].x = deformX2 + (CHUNK_SIZE * 2); gfxPolyList[gfxVertexSize].y = deformY + CHUNK_SIZE; gfxPolyList[gfxVertexSize].u = tileUVArray[tiles128x128.gfxDataPos[gfxIndex] + tileGFXPos]; tileGFXPos++; gfxPolyList[gfxVertexSize].v = tileUVArray[tiles128x128.gfxDataPos[gfxIndex] + tileGFXPos]; tileGFXPos++; gfxPolyList[gfxVertexSize].colour.r = 0xFF; gfxPolyList[gfxVertexSize].colour.g = 0xFF; gfxPolyList[gfxVertexSize].colour.b = 0xFF; gfxPolyList[gfxVertexSize].colour.a = 0xFF; gfxVertexSize++; gfxPolyList[gfxVertexSize].x = deformX2; gfxPolyList[gfxVertexSize].y = deformY + CHUNK_SIZE; gfxPolyList[gfxVertexSize].u = tileUVArray[tiles128x128.gfxDataPos[gfxIndex] + tileGFXPos]; tileGFXPos++; gfxPolyList[gfxVertexSize].v = gfxPolyList[gfxVertexSize - 1].v; gfxPolyList[gfxVertexSize].colour.r = 0xFF; gfxPolyList[gfxVertexSize].colour.g = 0xFF; gfxPolyList[gfxVertexSize].colour.b = 0xFF; gfxPolyList[gfxVertexSize].colour.a = 0xFF; gfxVertexSize++; gfxPolyList[gfxVertexSize].x = deformX1 + (CHUNK_SIZE * 2); gfxPolyList[gfxVertexSize].y = deformY; gfxPolyList[gfxVertexSize].u = gfxPolyList[gfxVertexSize - 2].u; gfxPolyList[gfxVertexSize].v = tileUVArray[tiles128x128.gfxDataPos[gfxIndex] + tileGFXPos] - 8; gfxPolyList[gfxVertexSize].colour.r = 0xFF; gfxPolyList[gfxVertexSize].colour.g = 0xFF; gfxPolyList[gfxVertexSize].colour.b = 0xFF; gfxPolyList[gfxVertexSize].colour.a = 0xFF; gfxVertexSize++; gfxPolyList[gfxVertexSize].x = deformX1; gfxPolyList[gfxVertexSize].y = gfxPolyList[gfxVertexSize - 1].y; gfxPolyList[gfxVertexSize].u = gfxPolyList[gfxVertexSize - 2].u; gfxPolyList[gfxVertexSize].v = gfxPolyList[gfxVertexSize - 1].v; gfxPolyList[gfxVertexSize].colour.r = 0xFF; gfxPolyList[gfxVertexSize].colour.g = 0xFF; gfxPolyList[gfxVertexSize].colour.b = 0xFF; gfxPolyList[gfxVertexSize].colour.a = 0xFF; gfxVertexSize++; gfxIndexSize += 6; break; } } } deformX1 += (CHUNK_SIZE * 2); deformX2 += (CHUNK_SIZE * 2); if (++chunkTileX < 8) { gfxIndex++; } else { if (++chunkPosX == layerWidth) { chunkPosX = 0; } chunkTileX = 0; gfxIndex = layer->tiles[chunkPosX + (chunkPosY << 8)] << 6; gfxIndex += chunkTileX + (chunkTileY << 3); } } deformY += CHUNK_SIZE; } else { if (parallaxLinePos < 0) parallaxLinePos += layerWidth << 7; if (parallaxLinePos >= layerWidth << 7) parallaxLinePos -= layerWidth << 7; chunkPosX = parallaxLinePos >> 7; chunkTileX = (parallaxLinePos & 0x7F) >> 4; deformX1 = -((parallaxLinePos & 0xF) << 4); deformX1 -= 0x100; deformX2 = deformX1; if (hParallax.deform[lineScrollPtr[lineID]]) { deformX1 -= deformY < waterDrawPos ? deformationData[deformOffset] : deformationDataW[deformOffsetW]; deformOffset += 16; deformOffsetW += 16; deformX2 -= (deformY + CHUNK_SIZE <= waterDrawPos) ? deformationData[deformOffset] : deformationDataW[deformOffsetW]; } else { deformOffset += 16; deformOffsetW += 16; } lineID += 16; gfxIndex = (chunkPosX > -1 && chunkPosY > -1) ? (layer->tiles[chunkPosX + (chunkPosY << 8)] << 6) : 0; gfxIndex += chunkTileX + (chunkTileY << 3); for (int i = renderWidth; i > 0; i--) { if (tiles128x128.visualPlane[gfxIndex] == highPlane && tiles128x128.gfxDataPos[gfxIndex] > 0) { tileGFXPos = 0; switch (tiles128x128.direction[gfxIndex]) { case FLIP_NONE: { gfxPolyList[gfxVertexSize].x = deformX1; gfxPolyList[gfxVertexSize].y = deformY; gfxPolyList[gfxVertexSize].u = tileUVArray[tiles128x128.gfxDataPos[gfxIndex] + tileGFXPos]; tileGFXPos++; gfxPolyList[gfxVertexSize].v = tileUVArray[tiles128x128.gfxDataPos[gfxIndex] + tileGFXPos]; tileGFXPos++; gfxPolyList[gfxVertexSize].colour.r = 0xFF; gfxPolyList[gfxVertexSize].colour.g = 0xFF; gfxPolyList[gfxVertexSize].colour.b = 0xFF; gfxPolyList[gfxVertexSize].colour.a = 0xFF; gfxVertexSize++; gfxPolyList[gfxVertexSize].x = deformX1 + (CHUNK_SIZE * 2); gfxPolyList[gfxVertexSize].y = deformY; gfxPolyList[gfxVertexSize].u = tileUVArray[tiles128x128.gfxDataPos[gfxIndex] + tileGFXPos]; tileGFXPos++; gfxPolyList[gfxVertexSize].v = gfxPolyList[gfxVertexSize - 1].v; gfxPolyList[gfxVertexSize].colour.r = 0xFF; gfxPolyList[gfxVertexSize].colour.g = 0xFF; gfxPolyList[gfxVertexSize].colour.b = 0xFF; gfxPolyList[gfxVertexSize].colour.a = 0xFF; gfxVertexSize++; gfxPolyList[gfxVertexSize].x = deformX2; gfxPolyList[gfxVertexSize].y = deformY + (CHUNK_SIZE * 2); gfxPolyList[gfxVertexSize].u = gfxPolyList[gfxVertexSize - 2].u; gfxPolyList[gfxVertexSize].v = tileUVArray[tiles128x128.gfxDataPos[gfxIndex] + tileGFXPos]; gfxPolyList[gfxVertexSize].colour.r = 0xFF; gfxPolyList[gfxVertexSize].colour.g = 0xFF; gfxPolyList[gfxVertexSize].colour.b = 0xFF; gfxPolyList[gfxVertexSize].colour.a = 0xFF; gfxVertexSize++; gfxPolyList[gfxVertexSize].x = deformX2 + (CHUNK_SIZE * 2); gfxPolyList[gfxVertexSize].y = gfxPolyList[gfxVertexSize - 1].y; gfxPolyList[gfxVertexSize].u = gfxPolyList[gfxVertexSize - 2].u; gfxPolyList[gfxVertexSize].v = gfxPolyList[gfxVertexSize - 1].v; gfxPolyList[gfxVertexSize].colour.r = 0xFF; gfxPolyList[gfxVertexSize].colour.g = 0xFF; gfxPolyList[gfxVertexSize].colour.b = 0xFF; gfxPolyList[gfxVertexSize].colour.a = 0xFF; gfxVertexSize++; gfxIndexSize += 6; break; } case FLIP_X: { gfxPolyList[gfxVertexSize].x = deformX1 + (CHUNK_SIZE * 2); gfxPolyList[gfxVertexSize].y = deformY; gfxPolyList[gfxVertexSize].u = tileUVArray[tiles128x128.gfxDataPos[gfxIndex] + tileGFXPos]; tileGFXPos++; gfxPolyList[gfxVertexSize].v = tileUVArray[tiles128x128.gfxDataPos[gfxIndex] + tileGFXPos]; tileGFXPos++; gfxPolyList[gfxVertexSize].colour.r = 0xFF; gfxPolyList[gfxVertexSize].colour.g = 0xFF; gfxPolyList[gfxVertexSize].colour.b = 0xFF; gfxPolyList[gfxVertexSize].colour.a = 0xFF; gfxVertexSize++; gfxPolyList[gfxVertexSize].x = deformX1; gfxPolyList[gfxVertexSize].y = deformY; gfxPolyList[gfxVertexSize].u = tileUVArray[tiles128x128.gfxDataPos[gfxIndex] + tileGFXPos]; tileGFXPos++; gfxPolyList[gfxVertexSize].v = gfxPolyList[gfxVertexSize - 1].v; gfxPolyList[gfxVertexSize].colour.r = 0xFF; gfxPolyList[gfxVertexSize].colour.g = 0xFF; gfxPolyList[gfxVertexSize].colour.b = 0xFF; gfxPolyList[gfxVertexSize].colour.a = 0xFF; gfxVertexSize++; gfxPolyList[gfxVertexSize].x = deformX2 + (CHUNK_SIZE * 2); gfxPolyList[gfxVertexSize].y = deformY + (CHUNK_SIZE * 2); gfxPolyList[gfxVertexSize].u = gfxPolyList[gfxVertexSize - 2].u; gfxPolyList[gfxVertexSize].v = tileUVArray[tiles128x128.gfxDataPos[gfxIndex] + tileGFXPos]; gfxPolyList[gfxVertexSize].colour.r = 0xFF; gfxPolyList[gfxVertexSize].colour.g = 0xFF; gfxPolyList[gfxVertexSize].colour.b = 0xFF; gfxPolyList[gfxVertexSize].colour.a = 0xFF; gfxVertexSize++; gfxPolyList[gfxVertexSize].x = deformX2; gfxPolyList[gfxVertexSize].y = gfxPolyList[gfxVertexSize - 1].y; gfxPolyList[gfxVertexSize].u = gfxPolyList[gfxVertexSize - 2].u; gfxPolyList[gfxVertexSize].v = gfxPolyList[gfxVertexSize - 1].v; gfxPolyList[gfxVertexSize].colour.r = 0xFF; gfxPolyList[gfxVertexSize].colour.g = 0xFF; gfxPolyList[gfxVertexSize].colour.b = 0xFF; gfxPolyList[gfxVertexSize].colour.a = 0xFF; gfxVertexSize++; gfxIndexSize += 6; break; } case FLIP_Y: { gfxPolyList[gfxVertexSize].x = deformX2; gfxPolyList[gfxVertexSize].y = deformY + (CHUNK_SIZE * 2); gfxPolyList[gfxVertexSize].u = tileUVArray[tiles128x128.gfxDataPos[gfxIndex] + tileGFXPos]; tileGFXPos++; gfxPolyList[gfxVertexSize].v = tileUVArray[tiles128x128.gfxDataPos[gfxIndex] + tileGFXPos]; tileGFXPos++; gfxPolyList[gfxVertexSize].colour.r = 0xFF; gfxPolyList[gfxVertexSize].colour.g = 0xFF; gfxPolyList[gfxVertexSize].colour.b = 0xFF; gfxPolyList[gfxVertexSize].colour.a = 0xFF; gfxVertexSize++; gfxPolyList[gfxVertexSize].x = deformX2 + (CHUNK_SIZE * 2); gfxPolyList[gfxVertexSize].y = deformY + (CHUNK_SIZE * 2); gfxPolyList[gfxVertexSize].u = tileUVArray[tiles128x128.gfxDataPos[gfxIndex] + tileGFXPos]; tileGFXPos++; gfxPolyList[gfxVertexSize].v = gfxPolyList[gfxVertexSize - 1].v; gfxPolyList[gfxVertexSize].colour.r = 0xFF; gfxPolyList[gfxVertexSize].colour.g = 0xFF; gfxPolyList[gfxVertexSize].colour.b = 0xFF; gfxPolyList[gfxVertexSize].colour.a = 0xFF; gfxVertexSize++; gfxPolyList[gfxVertexSize].x = deformX1; gfxPolyList[gfxVertexSize].y = deformY; gfxPolyList[gfxVertexSize].u = gfxPolyList[gfxVertexSize - 2].u; gfxPolyList[gfxVertexSize].v = tileUVArray[tiles128x128.gfxDataPos[gfxIndex] + tileGFXPos]; gfxPolyList[gfxVertexSize].colour.r = 0xFF; gfxPolyList[gfxVertexSize].colour.g = 0xFF; gfxPolyList[gfxVertexSize].colour.b = 0xFF; gfxPolyList[gfxVertexSize].colour.a = 0xFF; gfxVertexSize++; gfxPolyList[gfxVertexSize].x = deformX1 + (CHUNK_SIZE * 2); gfxPolyList[gfxVertexSize].y = gfxPolyList[gfxVertexSize - 1].y; gfxPolyList[gfxVertexSize].u = gfxPolyList[gfxVertexSize - 2].u; gfxPolyList[gfxVertexSize].v = gfxPolyList[gfxVertexSize - 1].v; gfxPolyList[gfxVertexSize].colour.r = 0xFF; gfxPolyList[gfxVertexSize].colour.g = 0xFF; gfxPolyList[gfxVertexSize].colour.b = 0xFF; gfxPolyList[gfxVertexSize].colour.a = 0xFF; gfxVertexSize++; gfxIndexSize += 6; break; } case FLIP_XY: { gfxPolyList[gfxVertexSize].x = deformX2 + (CHUNK_SIZE * 2); gfxPolyList[gfxVertexSize].y = deformY + (CHUNK_SIZE * 2); gfxPolyList[gfxVertexSize].u = tileUVArray[tiles128x128.gfxDataPos[gfxIndex] + tileGFXPos]; tileGFXPos++; gfxPolyList[gfxVertexSize].v = tileUVArray[tiles128x128.gfxDataPos[gfxIndex] + tileGFXPos]; tileGFXPos++; gfxPolyList[gfxVertexSize].colour.r = 0xFF; gfxPolyList[gfxVertexSize].colour.g = 0xFF; gfxPolyList[gfxVertexSize].colour.b = 0xFF; gfxPolyList[gfxVertexSize].colour.a = 0xFF; gfxVertexSize++; gfxPolyList[gfxVertexSize].x = deformX2; gfxPolyList[gfxVertexSize].y = deformY + (CHUNK_SIZE * 2); gfxPolyList[gfxVertexSize].u = tileUVArray[tiles128x128.gfxDataPos[gfxIndex] + tileGFXPos]; tileGFXPos++; gfxPolyList[gfxVertexSize].v = gfxPolyList[gfxVertexSize - 1].v; gfxPolyList[gfxVertexSize].colour.r = 0xFF; gfxPolyList[gfxVertexSize].colour.g = 0xFF; gfxPolyList[gfxVertexSize].colour.b = 0xFF; gfxPolyList[gfxVertexSize].colour.a = 0xFF; gfxVertexSize++; gfxPolyList[gfxVertexSize].x = deformX1 + (CHUNK_SIZE * 2); gfxPolyList[gfxVertexSize].y = deformY; gfxPolyList[gfxVertexSize].u = gfxPolyList[gfxVertexSize - 2].u; gfxPolyList[gfxVertexSize].v = tileUVArray[tiles128x128.gfxDataPos[gfxIndex] + tileGFXPos]; gfxPolyList[gfxVertexSize].colour.r = 0xFF; gfxPolyList[gfxVertexSize].colour.g = 0xFF; gfxPolyList[gfxVertexSize].colour.b = 0xFF; gfxPolyList[gfxVertexSize].colour.a = 0xFF; gfxVertexSize++; gfxPolyList[gfxVertexSize].x = deformX1; gfxPolyList[gfxVertexSize].y = gfxPolyList[gfxVertexSize - 1].y; gfxPolyList[gfxVertexSize].u = gfxPolyList[gfxVertexSize - 2].u; gfxPolyList[gfxVertexSize].v = gfxPolyList[gfxVertexSize - 1].v; gfxPolyList[gfxVertexSize].colour.r = 0xFF; gfxPolyList[gfxVertexSize].colour.g = 0xFF; gfxPolyList[gfxVertexSize].colour.b = 0xFF; gfxPolyList[gfxVertexSize].colour.a = 0xFF; gfxVertexSize++; gfxIndexSize += 6; break; } } } deformX1 += (CHUNK_SIZE * 2); deformX2 += (CHUNK_SIZE * 2); if (++chunkTileX < 8) { gfxIndex++; } else { if (++chunkPosX == layerWidth) chunkPosX = 0; chunkTileX = 0; gfxIndex = layer->tiles[chunkPosX + (chunkPosY << 8)] << 6; gfxIndex += chunkTileX + (chunkTileY << 3); } } deformY += CHUNK_SIZE * 2; } if (++chunkTileY > 7) { if (++chunkPosY == layerHeight) { chunkPosY = 0; lineID -= (layerHeight << 7); } chunkTileY = 0; } } waterDrawPos >>= 4; #endif } void DrawVLineScrollLayer(int layerID) { #if RETRO_SOFTWARE_RENDER TileLayer *layer = &stageLayouts[activeTileLayers[layerID]]; int layerwidth = layer->width; int layerheight = layer->height; bool aboveMidPoint = layerID >= tLayerMidPoint; byte *lineScroll; int *deformationData; int xscrollOffset = 0; if (activeTileLayers[layerID]) { // BG Layer int xScroll = xScrollOffset * layer->parallaxFactor >> 8; int fullLayerwidth = layerwidth << 7; layer->scrollPos += layer->scrollSpeed; if (layer->scrollPos > fullLayerwidth << 16) layer->scrollPos -= fullLayerwidth << 16; xscrollOffset = (xScroll + (layer->scrollPos >> 16)) % fullLayerwidth; layerwidth = fullLayerwidth >> 7; lineScroll = layer->lineScroll; deformationData = &bgDeformationData2[(byte)(xscrollOffset + layer->deformationOffset)]; } else { // FG Layer lastYSize = layer->height; xscrollOffset = xScrollOffset; lineScroll = layer->lineScroll; vParallax.linePos[0] = yScrollOffset; vParallax.deform[0] = true; deformationData = &bgDeformationData0[(byte)(xScrollOffset + layer->deformationOffset)]; } if (layer->type == LAYER_VSCROLL) { if (lastYSize != layerheight) { int fullLayerheight = layerheight << 7; for (int i = 0; i < vParallax.entryCount; ++i) { vParallax.linePos[i] = xScrollOffset * vParallax.parallaxFactor[i] >> 8; if (vParallax.scrollPos[i] > fullLayerheight << 16) vParallax.scrollPos[i] -= fullLayerheight << 16; if (vParallax.scrollPos[i] < 0) vParallax.scrollPos[i] += vParallax.scrollPos[i] << 16; vParallax.linePos[i] += vParallax.scrollPos[i] >> 16; vParallax.linePos[i] %= fullLayerheight; } layerheight = fullLayerheight >> 7; } lastYSize = layerwidth; } ushort *frameBufferPtr = Engine.frameBuffer; activePalette = fullPalette[gfxLineBuffer[0]]; activePalette32 = fullPalette32[gfxLineBuffer[0]]; int tileXPos = xscrollOffset % (layerheight << 7); if (tileXPos < 0) tileXPos += layerheight << 7; byte *scrollIndex = &lineScroll[tileXPos]; int tileX16 = tileXPos & 0xF; int tileX = (tileXPos & 0x7F) >> 4; // Draw Above Water (if applicable) int drawableLines = waterDrawPos; while (drawableLines--) { int chunkY = vParallax.linePos[*scrollIndex]; if (vParallax.deform[*scrollIndex]) chunkY += *deformationData; ++deformationData; ++scrollIndex; int fullLayerHeight = layerheight << 7; if (chunkY < 0) chunkY += fullLayerHeight; if (chunkY >= fullLayerHeight) chunkY -= fullLayerHeight; int chunkYPos = chunkY >> 7; int tileY = chunkY & 0xF; int tileYPxRemain = 0x10 - tileY; int chunk = (layer->tiles[chunkY + (chunkY >> 7 << 8)] << 6) + tileX + 8 * ((chunkY & 0x7F) >> 4); int tileOffsetXFlipX = 0xF - tileX16; int tileOffsetXFlipY = tileX16 + SCREEN_YSIZE; int tileOffsetXFlipXY = 0xFF - tileX16; int lineRemain = SCREEN_YSIZE; byte *gfxDataPtr = NULL; int tilePxLineCnt = 0; // Draw the first tile to the left if (tiles128x128.visualPlane[chunk] == (byte)aboveMidPoint) { tilePxLineCnt = 0x10 - tileY; lineRemain -= tilePxLineCnt; switch (tiles128x128.direction[chunk]) { case FLIP_NONE: gfxDataPtr = &tilesetGFXData[0x10 * tileY + tileX16 + tiles128x128.gfxDataPos[chunk]]; while (tilePxLineCnt--) { if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; frameBufferPtr += SCREEN_XSIZE; gfxDataPtr += 0x10; } break; case FLIP_X: gfxDataPtr = &tilesetGFXData[0x10 * tileY + tileOffsetXFlipX + tiles128x128.gfxDataPos[chunk]]; while (tilePxLineCnt--) { if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; frameBufferPtr += SCREEN_XSIZE; gfxDataPtr += 0x10; } break; case FLIP_Y: gfxDataPtr = &tilesetGFXData[tileOffsetXFlipY + tiles128x128.gfxDataPos[chunk] - 0x10 * tileY]; while (tilePxLineCnt--) { if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; frameBufferPtr += SCREEN_XSIZE; gfxDataPtr -= 0x10; } break; case FLIP_XY: gfxDataPtr = &tilesetGFXData[tileOffsetXFlipXY + tiles128x128.gfxDataPos[chunk] - 16 * tileY]; while (tilePxLineCnt--) { if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; frameBufferPtr += SCREEN_XSIZE; gfxDataPtr -= 0x10; } break; default: break; } } else { frameBufferPtr += SCREEN_XSIZE * tileYPxRemain; lineRemain -= tileYPxRemain; } // Draw the bulk of the tiles int chunkTileY = ((chunkY & 0x7F) >> 4) + 1; int tilesPerLine = 14; while (tilesPerLine--) { if (chunkTileY <= 7) { chunk += 8; } else { if (++chunkYPos == layerheight) chunkYPos = 0; chunkTileY = 0; chunk = (layer->tiles[chunkY + (chunkYPos << 8)] << 6) + tileX; } lineRemain -= TILE_SIZE; // Loop Unrolling (faster but messier code) if (tiles128x128.visualPlane[chunk] == (byte)aboveMidPoint) { switch (tiles128x128.direction[chunk]) { case FLIP_NONE: gfxDataPtr = &tilesetGFXData[tiles128x128.gfxDataPos[chunk] + tileX16]; if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; frameBufferPtr += SCREEN_XSIZE; gfxDataPtr += 0x10; if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; frameBufferPtr += SCREEN_XSIZE; gfxDataPtr += 0x10; if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; frameBufferPtr += SCREEN_XSIZE; gfxDataPtr += 0x10; if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; frameBufferPtr += SCREEN_XSIZE; gfxDataPtr += 0x10; if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; frameBufferPtr += SCREEN_XSIZE; gfxDataPtr += 0x10; if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; frameBufferPtr += SCREEN_XSIZE; gfxDataPtr += 0x10; if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; frameBufferPtr += SCREEN_XSIZE; gfxDataPtr += 0x10; if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; frameBufferPtr += SCREEN_XSIZE; gfxDataPtr += 0x10; if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; frameBufferPtr += SCREEN_XSIZE; gfxDataPtr += 0x10; if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; frameBufferPtr += SCREEN_XSIZE; gfxDataPtr += 0x10; if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; frameBufferPtr += SCREEN_XSIZE; gfxDataPtr += 0x10; if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; frameBufferPtr += SCREEN_XSIZE; gfxDataPtr += 0x10; if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; frameBufferPtr += SCREEN_XSIZE; gfxDataPtr += 0x10; if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; frameBufferPtr += SCREEN_XSIZE; gfxDataPtr += 0x10; if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; frameBufferPtr += SCREEN_XSIZE; gfxDataPtr += 0x10; if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; frameBufferPtr += SCREEN_XSIZE; gfxDataPtr += 0x10; break; case FLIP_X: gfxDataPtr = &tilesetGFXData[tiles128x128.gfxDataPos[chunk] + tileOffsetXFlipX]; if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; frameBufferPtr += SCREEN_XSIZE; gfxDataPtr += 0x10; if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; frameBufferPtr += SCREEN_XSIZE; gfxDataPtr += 0x10; if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; frameBufferPtr += SCREEN_XSIZE; gfxDataPtr += 0x10; if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; frameBufferPtr += SCREEN_XSIZE; gfxDataPtr += 0x10; if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; frameBufferPtr += SCREEN_XSIZE; gfxDataPtr += 0x10; if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; frameBufferPtr += SCREEN_XSIZE; gfxDataPtr += 0x10; if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; frameBufferPtr += SCREEN_XSIZE; gfxDataPtr += 0x10; if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; frameBufferPtr += SCREEN_XSIZE; gfxDataPtr += 0x10; if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; frameBufferPtr += SCREEN_XSIZE; gfxDataPtr += 0x10; if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; frameBufferPtr += SCREEN_XSIZE; gfxDataPtr += 0x10; if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; frameBufferPtr += SCREEN_XSIZE; gfxDataPtr += 0x10; if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; frameBufferPtr += SCREEN_XSIZE; gfxDataPtr += 0x10; if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; frameBufferPtr += SCREEN_XSIZE; gfxDataPtr += 0x10; if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; frameBufferPtr += SCREEN_XSIZE; gfxDataPtr += 0x10; if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; frameBufferPtr += SCREEN_XSIZE; gfxDataPtr += 0x10; if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; frameBufferPtr += SCREEN_XSIZE; gfxDataPtr += 0x10; break; case FLIP_Y: gfxDataPtr = &tilesetGFXData[tiles128x128.gfxDataPos[chunk] + tileOffsetXFlipY]; if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; frameBufferPtr += SCREEN_XSIZE; gfxDataPtr -= 0x10; if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; frameBufferPtr += SCREEN_XSIZE; gfxDataPtr -= 0x10; if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; frameBufferPtr += SCREEN_XSIZE; gfxDataPtr -= 0x10; if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; frameBufferPtr += SCREEN_XSIZE; gfxDataPtr -= 0x10; if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; frameBufferPtr += SCREEN_XSIZE; gfxDataPtr -= 0x10; if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; frameBufferPtr += SCREEN_XSIZE; gfxDataPtr -= 0x10; if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; frameBufferPtr += SCREEN_XSIZE; gfxDataPtr -= 0x10; if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; frameBufferPtr += SCREEN_XSIZE; gfxDataPtr -= 0x10; if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; frameBufferPtr += SCREEN_XSIZE; gfxDataPtr -= 0x10; if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; frameBufferPtr += SCREEN_XSIZE; gfxDataPtr -= 0x10; if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; frameBufferPtr += SCREEN_XSIZE; gfxDataPtr -= 0x10; if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; frameBufferPtr += SCREEN_XSIZE; gfxDataPtr -= 0x10; if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; frameBufferPtr += SCREEN_XSIZE; gfxDataPtr -= 0x10; if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; frameBufferPtr += SCREEN_XSIZE; gfxDataPtr -= 0x10; if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; frameBufferPtr += SCREEN_XSIZE; gfxDataPtr -= 0x10; if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; frameBufferPtr += SCREEN_XSIZE; gfxDataPtr -= 0x10; break; case FLIP_XY: gfxDataPtr = &tilesetGFXData[tiles128x128.gfxDataPos[chunk] + tileOffsetXFlipXY]; if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; frameBufferPtr += SCREEN_XSIZE; gfxDataPtr -= 0x10; if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; frameBufferPtr += SCREEN_XSIZE; gfxDataPtr -= 0x10; if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; frameBufferPtr += SCREEN_XSIZE; gfxDataPtr -= 0x10; if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; frameBufferPtr += SCREEN_XSIZE; gfxDataPtr -= 0x10; if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; frameBufferPtr += SCREEN_XSIZE; gfxDataPtr -= 0x10; if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; frameBufferPtr += SCREEN_XSIZE; gfxDataPtr -= 0x10; if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; frameBufferPtr += SCREEN_XSIZE; gfxDataPtr -= 0x10; if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; frameBufferPtr += SCREEN_XSIZE; gfxDataPtr -= 0x10; if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; frameBufferPtr += SCREEN_XSIZE; gfxDataPtr -= 0x10; if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; frameBufferPtr += SCREEN_XSIZE; gfxDataPtr -= 0x10; if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; frameBufferPtr += SCREEN_XSIZE; gfxDataPtr -= 0x10; if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; frameBufferPtr += SCREEN_XSIZE; gfxDataPtr -= 0x10; if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; frameBufferPtr += SCREEN_XSIZE; gfxDataPtr -= 0x10; if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; frameBufferPtr += SCREEN_XSIZE; gfxDataPtr -= 0x10; if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; frameBufferPtr += SCREEN_XSIZE; gfxDataPtr -= 0x10; if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; frameBufferPtr += SCREEN_XSIZE; gfxDataPtr -= 0x10; break; } } else { frameBufferPtr += 0x10; } ++chunkTileY; } // Draw any remaining tiles while (lineRemain > 0) { if (chunkTileY++ <= 7) { chunk += 8; } else { chunkTileY = 0; if (++chunkYPos == layerheight) chunkYPos = 0; chunkTileY = 0; chunk = (layer->tiles[chunkY + (chunkYPos << 8)] << 6) + tileX; } tilePxLineCnt = lineRemain >= TILE_SIZE ? TILE_SIZE : lineRemain; lineRemain -= tilePxLineCnt; if (tiles128x128.visualPlane[chunk] == (byte)aboveMidPoint) { switch (tiles128x128.direction[chunk]) { case FLIP_NONE: gfxDataPtr = &tilesetGFXData[0x10 * tileY + tileX16 + tiles128x128.gfxDataPos[chunk]]; while (tilePxLineCnt--) { if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; frameBufferPtr += SCREEN_XSIZE; gfxDataPtr += 0x10; } break; case FLIP_X: gfxDataPtr = &tilesetGFXData[0x10 * tileY + tileOffsetXFlipX + tiles128x128.gfxDataPos[chunk]]; while (tilePxLineCnt--) { if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; frameBufferPtr += SCREEN_XSIZE; gfxDataPtr += 0x10; } break; case FLIP_Y: gfxDataPtr = &tilesetGFXData[tileOffsetXFlipY + tiles128x128.gfxDataPos[chunk] - 0x10 * tileY]; while (tilePxLineCnt--) { if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; frameBufferPtr += SCREEN_XSIZE; gfxDataPtr -= 0x10; } break; case FLIP_XY: gfxDataPtr = &tilesetGFXData[tileOffsetXFlipXY + tiles128x128.gfxDataPos[chunk] - 16 * tileY]; while (tilePxLineCnt--) { if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; frameBufferPtr += SCREEN_XSIZE; gfxDataPtr -= 0x10; } break; default: break; } } else { frameBufferPtr += SCREEN_XSIZE * tileYPxRemain; } } if (++tileX16 > 0xF) { tileX16 = 0; ++tileX; } if (tileX > 7) { if (++chunkY == layerwidth) { chunkY = 0; scrollIndex -= 0x80 * layerwidth; } tileX = 0; } } #endif #if RETRO_HARDWARE_RENDER // unimplimented in RSDK #endif } void Draw3DFloorLayer(int layerID) { #if RETRO_SOFTWARE_RENDER TileLayer *layer = &stageLayouts[activeTileLayers[layerID]]; int layerWidth = layer->width << 7; int layerHeight = layer->height << 7; int layerYPos = layer->YPos; int layerZPos = layer->ZPos; int sinValue = sinValM7[layer->angle]; int cosValue = cosValM7[layer->angle]; byte *linePtr = gfxLineBuffer; ushort *frameBufferPtr = &Engine.frameBuffer[132 * SCREEN_XSIZE]; int layerXPos = layer->XPos >> 4; int ZBuffer = layerZPos >> 4; for (int i = 4; i < 112; ++i) { if (!(i & 1)) { activePalette = fullPalette[*linePtr]; activePalette32 = fullPalette32[*linePtr]; linePtr++; } int XBuffer = layerYPos / (i << 9) * -cosValue >> 8; int YBuffer = sinValue * (layerYPos / (i << 9)) >> 8; int XPos = layerXPos + (3 * sinValue * (layerYPos / (i << 9)) >> 2) - XBuffer * SCREEN_CENTERX; int YPos = ZBuffer + (3 * cosValue * (layerYPos / (i << 9)) >> 2) - YBuffer * SCREEN_CENTERX; int lineBuffer = 0; while (lineBuffer < SCREEN_XSIZE) { int tileX = XPos >> 12; int tileY = YPos >> 12; if (tileX > -1 && tileX < layerWidth && tileY > -1 && tileY < layerHeight) { int chunk = tile3DFloorBuffer[(YPos >> 16 << 8) + (XPos >> 16)]; byte *tilePixel = &tilesetGFXData[tiles128x128.gfxDataPos[chunk]]; switch (tiles128x128.direction[chunk]) { case FLIP_NONE: tilePixel += 16 * (tileY & 0xF) + (tileX & 0xF); break; case FLIP_X: tilePixel += 16 * (tileY & 0xF) + 15 - (tileX & 0xF); break; case FLIP_Y: tilePixel += (tileX & 0xF) + SCREEN_YSIZE - 16 * (tileY & 0xF); break; case FLIP_XY: tilePixel += 15 - (tileX & 0xF) + SCREEN_YSIZE - 16 * (tileY & 0xF); break; default: break; } if (*tilePixel > 0) *frameBufferPtr = activePalette[*tilePixel]; } ++frameBufferPtr; ++lineBuffer; XPos += XBuffer; YPos += YBuffer; } } #endif #if RETRO_HARDWARE_RENDER TileLayer *layer = &stageLayouts[activeTileLayers[layerID]]; int tileOffset, tileX, tileY, tileSinBlock, tileCosBlock; int sinValue512, cosValue512; int layerWidth = layer->width << 7; int layerHeight = layer->height << 7; ushort *currentTileMap = layer->tiles; vertexSize3D = 0; indexSize3D = 0; // low quality render polyList3D[vertexSize3D].x = 0.0f; polyList3D[vertexSize3D].y = 0.0f; polyList3D[vertexSize3D].z = 0.0f; polyList3D[vertexSize3D].u = 512; polyList3D[vertexSize3D].v = 0; polyList3D[vertexSize3D].colour.r = 0xFF; polyList3D[vertexSize3D].colour.g = 0xFF; polyList3D[vertexSize3D].colour.b = 0xFF; polyList3D[vertexSize3D].colour.a = 0xFF; vertexSize3D++; polyList3D[vertexSize3D].x = 4096.0f; polyList3D[vertexSize3D].y = 0.0f; polyList3D[vertexSize3D].z = 0.0f; polyList3D[vertexSize3D].u = 1024; polyList3D[vertexSize3D].v = 0; polyList3D[vertexSize3D].colour.r = 0xFF; polyList3D[vertexSize3D].colour.g = 0xFF; polyList3D[vertexSize3D].colour.b = 0xFF; polyList3D[vertexSize3D].colour.a = 0xFF; vertexSize3D++; polyList3D[vertexSize3D].x = 0.0f; polyList3D[vertexSize3D].y = 0.0f; polyList3D[vertexSize3D].z = 4096.0f; polyList3D[vertexSize3D].u = 512; polyList3D[vertexSize3D].v = 512; polyList3D[vertexSize3D].colour.r = 0xFF; polyList3D[vertexSize3D].colour.g = 0xFF; polyList3D[vertexSize3D].colour.b = 0xFF; polyList3D[vertexSize3D].colour.a = 0xFF; vertexSize3D++; polyList3D[vertexSize3D].x = 4096.0f; polyList3D[vertexSize3D].y = 0.0f; polyList3D[vertexSize3D].z = 4096.0f; polyList3D[vertexSize3D].u = 1024; polyList3D[vertexSize3D].v = 512; polyList3D[vertexSize3D].colour.r = 0xFF; polyList3D[vertexSize3D].colour.g = 0xFF; polyList3D[vertexSize3D].colour.b = 0xFF; polyList3D[vertexSize3D].colour.a = 0xFF; vertexSize3D++; indexSize3D += 6; if (hq3DFloorEnabled) { sinValue512 = (layer->XPos >> 16) - 0x100; sinValue512 += (sinVal512[layer->angle] >> 1); sinValue512 = sinValue512 >> 4 << 4; cosValue512 = (layer->ZPos >> 16) - 0x100; cosValue512 += (cosVal512[layer->angle] >> 1); cosValue512 = cosValue512 >> 4 << 4; for (int i = 32; i > 0; i--) { for (int j = 32; j > 0; j--) { if (sinValue512 > -1 && sinValue512 < layerWidth && cosValue512 > -1 && cosValue512 < layerHeight) { tileX = sinValue512 >> 7; tileY = cosValue512 >> 7; tileSinBlock = (sinValue512 & 127) >> 4; tileCosBlock = (cosValue512 & 127) >> 4; int tileIndex = currentTileMap[tileX + (tileY << 8)] << 6; tileIndex = tileIndex + tileSinBlock + (tileCosBlock << 3); if (tiles128x128.gfxDataPos[tileIndex] > 0) { tileOffset = 0; switch (tiles128x128.direction[tileIndex]) { case FLIP_NONE: { polyList3D[vertexSize3D].x = sinValue512; polyList3D[vertexSize3D].y = 0.0f; polyList3D[vertexSize3D].z = cosValue512; polyList3D[vertexSize3D].u = tileUVArray[tiles128x128.gfxDataPos[tileIndex] + tileOffset]; tileOffset++; polyList3D[vertexSize3D].v = tileUVArray[tiles128x128.gfxDataPos[tileIndex] + tileOffset]; tileOffset++; polyList3D[vertexSize3D].colour.r = 0xFF; polyList3D[vertexSize3D].colour.g = 0xFF; polyList3D[vertexSize3D].colour.b = 0xFF; polyList3D[vertexSize3D].colour.a = 0xFF; vertexSize3D++; polyList3D[vertexSize3D].x = sinValue512 + 16; polyList3D[vertexSize3D].y = 0.0f; polyList3D[vertexSize3D].z = polyList3D[vertexSize3D - 1].z; polyList3D[vertexSize3D].u = tileUVArray[tiles128x128.gfxDataPos[tileIndex] + tileOffset]; tileOffset++; polyList3D[vertexSize3D].v = polyList3D[vertexSize3D - 1].v; polyList3D[vertexSize3D].colour.r = 0xFF; polyList3D[vertexSize3D].colour.g = 0xFF; polyList3D[vertexSize3D].colour.b = 0xFF; polyList3D[vertexSize3D].colour.a = 0xFF; vertexSize3D++; polyList3D[vertexSize3D].x = polyList3D[vertexSize3D - 2].x; polyList3D[vertexSize3D].y = 0.0f; polyList3D[vertexSize3D].z = cosValue512 + 16; polyList3D[vertexSize3D].u = polyList3D[vertexSize3D - 2].u; polyList3D[vertexSize3D].v = tileUVArray[tiles128x128.gfxDataPos[tileIndex] + tileOffset]; polyList3D[vertexSize3D].colour.r = 0xFF; polyList3D[vertexSize3D].colour.g = 0xFF; polyList3D[vertexSize3D].colour.b = 0xFF; polyList3D[vertexSize3D].colour.a = 0xFF; vertexSize3D++; polyList3D[vertexSize3D].x = polyList3D[vertexSize3D - 2].x; polyList3D[vertexSize3D].y = 0.0f; polyList3D[vertexSize3D].z = polyList3D[vertexSize3D - 1].z; polyList3D[vertexSize3D].u = polyList3D[vertexSize3D - 2].u; polyList3D[vertexSize3D].v = polyList3D[vertexSize3D - 1].v; polyList3D[vertexSize3D].colour.r = 0xFF; polyList3D[vertexSize3D].colour.g = 0xFF; polyList3D[vertexSize3D].colour.b = 0xFF; polyList3D[vertexSize3D].colour.a = 0xFF; vertexSize3D++; indexSize3D += 6; break; } case FLIP_X: { polyList3D[vertexSize3D].x = sinValue512 + 16; polyList3D[vertexSize3D].y = 0.0f; polyList3D[vertexSize3D].z = cosValue512; polyList3D[vertexSize3D].u = tileUVArray[tiles128x128.gfxDataPos[tileIndex] + tileOffset]; tileOffset++; polyList3D[vertexSize3D].v = tileUVArray[tiles128x128.gfxDataPos[tileIndex] + tileOffset]; tileOffset++; polyList3D[vertexSize3D].colour.r = 0xFF; polyList3D[vertexSize3D].colour.g = 0xFF; polyList3D[vertexSize3D].colour.b = 0xFF; polyList3D[vertexSize3D].colour.a = 0xFF; vertexSize3D++; polyList3D[vertexSize3D].x = sinValue512; polyList3D[vertexSize3D].y = 0.0f; polyList3D[vertexSize3D].z = polyList3D[vertexSize3D - 1].z; polyList3D[vertexSize3D].u = tileUVArray[tiles128x128.gfxDataPos[tileIndex] + tileOffset]; tileOffset++; polyList3D[vertexSize3D].v = polyList3D[vertexSize3D - 1].v; polyList3D[vertexSize3D].colour.r = 0xFF; polyList3D[vertexSize3D].colour.g = 0xFF; polyList3D[vertexSize3D].colour.b = 0xFF; polyList3D[vertexSize3D].colour.a = 0xFF; vertexSize3D++; polyList3D[vertexSize3D].x = polyList3D[vertexSize3D - 2].x; polyList3D[vertexSize3D].y = 0.0f; polyList3D[vertexSize3D].z = cosValue512 + 16; polyList3D[vertexSize3D].u = polyList3D[vertexSize3D - 2].u; polyList3D[vertexSize3D].v = tileUVArray[tiles128x128.gfxDataPos[tileIndex] + tileOffset]; polyList3D[vertexSize3D].colour.r = 0xFF; polyList3D[vertexSize3D].colour.g = 0xFF; polyList3D[vertexSize3D].colour.b = 0xFF; polyList3D[vertexSize3D].colour.a = 0xFF; vertexSize3D++; polyList3D[vertexSize3D].x = polyList3D[vertexSize3D - 2].x; polyList3D[vertexSize3D].y = 0.0f; polyList3D[vertexSize3D].z = polyList3D[vertexSize3D - 1].z; polyList3D[vertexSize3D].u = polyList3D[vertexSize3D - 2].u; polyList3D[vertexSize3D].v = polyList3D[vertexSize3D - 1].v; polyList3D[vertexSize3D].colour.r = 0xFF; polyList3D[vertexSize3D].colour.g = 0xFF; polyList3D[vertexSize3D].colour.b = 0xFF; polyList3D[vertexSize3D].colour.a = 0xFF; vertexSize3D++; indexSize3D += 6; break; } case 2: { polyList3D[vertexSize3D].x = sinValue512; polyList3D[vertexSize3D].y = 0.0f; polyList3D[vertexSize3D].z = cosValue512 + 16; polyList3D[vertexSize3D].u = tileUVArray[tiles128x128.gfxDataPos[tileIndex] + tileOffset]; tileOffset++; polyList3D[vertexSize3D].v = tileUVArray[tiles128x128.gfxDataPos[tileIndex] + tileOffset]; tileOffset++; polyList3D[vertexSize3D].colour.r = 0xFF; polyList3D[vertexSize3D].colour.g = 0xFF; polyList3D[vertexSize3D].colour.b = 0xFF; polyList3D[vertexSize3D].colour.a = 0xFF; vertexSize3D++; polyList3D[vertexSize3D].x = sinValue512 + 16; polyList3D[vertexSize3D].y = 0.0f; polyList3D[vertexSize3D].z = polyList3D[vertexSize3D - 1].z; polyList3D[vertexSize3D].u = tileUVArray[tiles128x128.gfxDataPos[tileIndex] + tileOffset]; tileOffset++; polyList3D[vertexSize3D].v = polyList3D[vertexSize3D - 1].v; polyList3D[vertexSize3D].colour.r = 0xFF; polyList3D[vertexSize3D].colour.g = 0xFF; polyList3D[vertexSize3D].colour.b = 0xFF; polyList3D[vertexSize3D].colour.a = 0xFF; vertexSize3D++; polyList3D[vertexSize3D].x = polyList3D[vertexSize3D - 2].x; polyList3D[vertexSize3D].y = 0.0f; polyList3D[vertexSize3D].z = cosValue512; polyList3D[vertexSize3D].u = polyList3D[vertexSize3D - 2].u; polyList3D[vertexSize3D].v = tileUVArray[tiles128x128.gfxDataPos[tileIndex] + tileOffset]; polyList3D[vertexSize3D].colour.r = 0xFF; polyList3D[vertexSize3D].colour.g = 0xFF; polyList3D[vertexSize3D].colour.b = 0xFF; polyList3D[vertexSize3D].colour.a = 0xFF; vertexSize3D++; polyList3D[vertexSize3D].x = polyList3D[vertexSize3D - 2].x; polyList3D[vertexSize3D].y = 0.0f; polyList3D[vertexSize3D].z = polyList3D[vertexSize3D - 1].z; polyList3D[vertexSize3D].u = polyList3D[vertexSize3D - 2].u; polyList3D[vertexSize3D].v = polyList3D[vertexSize3D - 1].v; polyList3D[vertexSize3D].colour.r = 0xFF; polyList3D[vertexSize3D].colour.g = 0xFF; polyList3D[vertexSize3D].colour.b = 0xFF; polyList3D[vertexSize3D].colour.a = 0xFF; vertexSize3D++; indexSize3D += 6; break; } case FLIP_XY: { polyList3D[vertexSize3D].x = sinValue512 + 16; polyList3D[vertexSize3D].y = 0.0f; polyList3D[vertexSize3D].z = cosValue512 + 16; polyList3D[vertexSize3D].u = tileUVArray[tiles128x128.gfxDataPos[tileIndex] + tileOffset]; tileOffset++; polyList3D[vertexSize3D].v = tileUVArray[tiles128x128.gfxDataPos[tileIndex] + tileOffset]; tileOffset++; polyList3D[vertexSize3D].colour.r = 0xFF; polyList3D[vertexSize3D].colour.g = 0xFF; polyList3D[vertexSize3D].colour.b = 0xFF; polyList3D[vertexSize3D].colour.a = 0xFF; vertexSize3D++; polyList3D[vertexSize3D].x = sinValue512; polyList3D[vertexSize3D].y = 0.0f; polyList3D[vertexSize3D].z = polyList3D[vertexSize3D - 1].z; polyList3D[vertexSize3D].u = tileUVArray[tiles128x128.gfxDataPos[tileIndex] + tileOffset]; tileOffset++; polyList3D[vertexSize3D].v = polyList3D[vertexSize3D - 1].v; polyList3D[vertexSize3D].colour.r = 0xFF; polyList3D[vertexSize3D].colour.g = 0xFF; polyList3D[vertexSize3D].colour.b = 0xFF; polyList3D[vertexSize3D].colour.a = 0xFF; vertexSize3D++; polyList3D[vertexSize3D].x = polyList3D[vertexSize3D - 2].x; polyList3D[vertexSize3D].y = 0.0f; polyList3D[vertexSize3D].z = cosValue512; polyList3D[vertexSize3D].u = polyList3D[vertexSize3D - 2].u; polyList3D[vertexSize3D].v = tileUVArray[tiles128x128.gfxDataPos[tileIndex] + tileOffset]; polyList3D[vertexSize3D].colour.r = 0xFF; polyList3D[vertexSize3D].colour.g = 0xFF; polyList3D[vertexSize3D].colour.b = 0xFF; polyList3D[vertexSize3D].colour.a = 0xFF; vertexSize3D++; polyList3D[vertexSize3D].x = polyList3D[vertexSize3D - 2].x; polyList3D[vertexSize3D].y = 0.0f; polyList3D[vertexSize3D].z = polyList3D[vertexSize3D - 1].z; polyList3D[vertexSize3D].u = polyList3D[vertexSize3D - 2].u; polyList3D[vertexSize3D].v = polyList3D[vertexSize3D - 1].v; polyList3D[vertexSize3D].colour.r = 0xFF; polyList3D[vertexSize3D].colour.g = 0xFF; polyList3D[vertexSize3D].colour.b = 0xFF; polyList3D[vertexSize3D].colour.a = 0xFF; vertexSize3D++; indexSize3D += 6; break; } } } } sinValue512 += 16; } sinValue512 -= 0x200; cosValue512 += 16; } } else { sinValue512 = (layer->XPos >> 16) - 160; sinValue512 += sinVal512[layer->angle] / 3; sinValue512 = sinValue512 >> 4 << 4; cosValue512 = (layer->ZPos >> 16) - 160; cosValue512 += cosVal512[layer->angle] / 3; cosValue512 = cosValue512 >> 4 << 4; for (int i = 20; i > 0; i--) { for (int j = 20; j > 0; j--) { if (sinValue512 > -1 && sinValue512 < layerWidth && cosValue512 > -1 && cosValue512 < layerHeight) { tileX = sinValue512 >> 7; tileY = cosValue512 >> 7; tileSinBlock = (sinValue512 & 127) >> 4; tileCosBlock = (cosValue512 & 127) >> 4; int tileIndex = currentTileMap[tileX + (tileY << 8)] << 6; tileIndex = tileIndex + tileSinBlock + (tileCosBlock << 3); if (tiles128x128.gfxDataPos[tileIndex] > 0) { tileOffset = 0; switch (tiles128x128.direction[tileIndex]) { case FLIP_NONE: { polyList3D[vertexSize3D].x = sinValue512; polyList3D[vertexSize3D].y = 0.0f; polyList3D[vertexSize3D].z = cosValue512; polyList3D[vertexSize3D].u = tileUVArray[tiles128x128.gfxDataPos[tileIndex] + tileOffset]; tileOffset++; polyList3D[vertexSize3D].v = tileUVArray[tiles128x128.gfxDataPos[tileIndex] + tileOffset]; tileOffset++; polyList3D[vertexSize3D].colour.r = 0xFF; polyList3D[vertexSize3D].colour.g = 0xFF; polyList3D[vertexSize3D].colour.b = 0xFF; polyList3D[vertexSize3D].colour.a = 0xFF; vertexSize3D++; polyList3D[vertexSize3D].x = sinValue512 + 16; polyList3D[vertexSize3D].y = 0.0f; polyList3D[vertexSize3D].z = polyList3D[vertexSize3D - 1].z; polyList3D[vertexSize3D].u = tileUVArray[tiles128x128.gfxDataPos[tileIndex] + tileOffset]; tileOffset++; polyList3D[vertexSize3D].v = polyList3D[vertexSize3D - 1].v; polyList3D[vertexSize3D].colour.r = 0xFF; polyList3D[vertexSize3D].colour.g = 0xFF; polyList3D[vertexSize3D].colour.b = 0xFF; polyList3D[vertexSize3D].colour.a = 0xFF; vertexSize3D++; polyList3D[vertexSize3D].x = polyList3D[vertexSize3D - 2].x; polyList3D[vertexSize3D].y = 0.0f; polyList3D[vertexSize3D].z = cosValue512 + 16; polyList3D[vertexSize3D].u = polyList3D[vertexSize3D - 2].u; polyList3D[vertexSize3D].v = tileUVArray[tiles128x128.gfxDataPos[tileIndex] + tileOffset]; polyList3D[vertexSize3D].colour.r = 0xFF; polyList3D[vertexSize3D].colour.g = 0xFF; polyList3D[vertexSize3D].colour.b = 0xFF; polyList3D[vertexSize3D].colour.a = 0xFF; vertexSize3D++; polyList3D[vertexSize3D].x = polyList3D[vertexSize3D - 2].x; polyList3D[vertexSize3D].y = 0.0f; polyList3D[vertexSize3D].z = polyList3D[vertexSize3D - 1].z; polyList3D[vertexSize3D].u = polyList3D[vertexSize3D - 2].u; polyList3D[vertexSize3D].v = polyList3D[vertexSize3D - 1].v; polyList3D[vertexSize3D].colour.r = 0xFF; polyList3D[vertexSize3D].colour.g = 0xFF; polyList3D[vertexSize3D].colour.b = 0xFF; polyList3D[vertexSize3D].colour.a = 0xFF; vertexSize3D++; indexSize3D += 6; break; } case FLIP_X: { polyList3D[vertexSize3D].x = sinValue512 + 16; polyList3D[vertexSize3D].y = 0.0f; polyList3D[vertexSize3D].z = cosValue512; polyList3D[vertexSize3D].u = tileUVArray[tiles128x128.gfxDataPos[tileIndex] + tileOffset]; tileOffset++; polyList3D[vertexSize3D].v = tileUVArray[tiles128x128.gfxDataPos[tileIndex] + tileOffset]; tileOffset++; polyList3D[vertexSize3D].colour.r = 0xFF; polyList3D[vertexSize3D].colour.g = 0xFF; polyList3D[vertexSize3D].colour.b = 0xFF; polyList3D[vertexSize3D].colour.a = 0xFF; vertexSize3D++; polyList3D[vertexSize3D].x = sinValue512; polyList3D[vertexSize3D].y = 0.0f; polyList3D[vertexSize3D].z = polyList3D[vertexSize3D - 1].z; polyList3D[vertexSize3D].u = tileUVArray[tiles128x128.gfxDataPos[tileIndex] + tileOffset]; tileOffset++; polyList3D[vertexSize3D].v = polyList3D[vertexSize3D - 1].v; polyList3D[vertexSize3D].colour.r = 0xFF; polyList3D[vertexSize3D].colour.g = 0xFF; polyList3D[vertexSize3D].colour.b = 0xFF; polyList3D[vertexSize3D].colour.a = 0xFF; vertexSize3D++; polyList3D[vertexSize3D].x = polyList3D[vertexSize3D - 2].x; polyList3D[vertexSize3D].y = 0.0f; polyList3D[vertexSize3D].z = cosValue512 + 16; polyList3D[vertexSize3D].u = polyList3D[vertexSize3D - 2].u; polyList3D[vertexSize3D].v = tileUVArray[tiles128x128.gfxDataPos[tileIndex] + tileOffset]; polyList3D[vertexSize3D].colour.r = 0xFF; polyList3D[vertexSize3D].colour.g = 0xFF; polyList3D[vertexSize3D].colour.b = 0xFF; polyList3D[vertexSize3D].colour.a = 0xFF; vertexSize3D++; polyList3D[vertexSize3D].x = polyList3D[vertexSize3D - 2].x; polyList3D[vertexSize3D].y = 0.0f; polyList3D[vertexSize3D].z = polyList3D[vertexSize3D - 1].z; polyList3D[vertexSize3D].u = polyList3D[vertexSize3D - 2].u; polyList3D[vertexSize3D].v = polyList3D[vertexSize3D - 1].v; polyList3D[vertexSize3D].colour.r = 0xFF; polyList3D[vertexSize3D].colour.g = 0xFF; polyList3D[vertexSize3D].colour.b = 0xFF; polyList3D[vertexSize3D].colour.a = 0xFF; vertexSize3D++; indexSize3D += 6; break; } case FLIP_Y: { polyList3D[vertexSize3D].x = sinValue512; polyList3D[vertexSize3D].y = 0.0f; polyList3D[vertexSize3D].z = cosValue512 + 16; polyList3D[vertexSize3D].u = tileUVArray[tiles128x128.gfxDataPos[tileIndex] + tileOffset]; tileOffset++; polyList3D[vertexSize3D].v = tileUVArray[tiles128x128.gfxDataPos[tileIndex] + tileOffset]; tileOffset++; polyList3D[vertexSize3D].colour.r = 0xFF; polyList3D[vertexSize3D].colour.g = 0xFF; polyList3D[vertexSize3D].colour.b = 0xFF; polyList3D[vertexSize3D].colour.a = 0xFF; vertexSize3D++; polyList3D[vertexSize3D].x = sinValue512 + 16; polyList3D[vertexSize3D].y = 0.0f; polyList3D[vertexSize3D].z = polyList3D[vertexSize3D - 1].z; polyList3D[vertexSize3D].u = tileUVArray[tiles128x128.gfxDataPos[tileIndex] + tileOffset]; tileOffset++; polyList3D[vertexSize3D].v = polyList3D[vertexSize3D - 1].v; polyList3D[vertexSize3D].colour.r = 0xFF; polyList3D[vertexSize3D].colour.g = 0xFF; polyList3D[vertexSize3D].colour.b = 0xFF; polyList3D[vertexSize3D].colour.a = 0xFF; vertexSize3D++; polyList3D[vertexSize3D].x = polyList3D[vertexSize3D - 2].x; polyList3D[vertexSize3D].y = 0.0f; polyList3D[vertexSize3D].z = cosValue512; polyList3D[vertexSize3D].u = polyList3D[vertexSize3D - 2].u; polyList3D[vertexSize3D].v = tileUVArray[tiles128x128.gfxDataPos[tileIndex] + tileOffset]; polyList3D[vertexSize3D].colour.r = 0xFF; polyList3D[vertexSize3D].colour.g = 0xFF; polyList3D[vertexSize3D].colour.b = 0xFF; polyList3D[vertexSize3D].colour.a = 0xFF; vertexSize3D++; polyList3D[vertexSize3D].x = polyList3D[vertexSize3D - 2].x; polyList3D[vertexSize3D].y = 0.0f; polyList3D[vertexSize3D].z = polyList3D[vertexSize3D - 1].z; polyList3D[vertexSize3D].u = polyList3D[vertexSize3D - 2].u; polyList3D[vertexSize3D].v = polyList3D[vertexSize3D - 1].v; polyList3D[vertexSize3D].colour.r = 0xFF; polyList3D[vertexSize3D].colour.g = 0xFF; polyList3D[vertexSize3D].colour.b = 0xFF; polyList3D[vertexSize3D].colour.a = 0xFF; vertexSize3D++; indexSize3D += 6; break; } case FLIP_XY: { polyList3D[vertexSize3D].x = sinValue512 + 16; polyList3D[vertexSize3D].y = 0.0f; polyList3D[vertexSize3D].z = cosValue512 + 16; polyList3D[vertexSize3D].u = tileUVArray[tiles128x128.gfxDataPos[tileIndex] + tileOffset]; tileOffset++; polyList3D[vertexSize3D].v = tileUVArray[tiles128x128.gfxDataPos[tileIndex] + tileOffset]; tileOffset++; polyList3D[vertexSize3D].colour.r = 0xFF; polyList3D[vertexSize3D].colour.g = 0xFF; polyList3D[vertexSize3D].colour.b = 0xFF; polyList3D[vertexSize3D].colour.a = 0xFF; vertexSize3D++; polyList3D[vertexSize3D].x = sinValue512; polyList3D[vertexSize3D].y = 0.0f; polyList3D[vertexSize3D].z = polyList3D[vertexSize3D - 1].z; polyList3D[vertexSize3D].u = tileUVArray[tiles128x128.gfxDataPos[tileIndex] + tileOffset]; tileOffset++; polyList3D[vertexSize3D].v = polyList3D[vertexSize3D - 1].v; polyList3D[vertexSize3D].colour.r = 0xFF; polyList3D[vertexSize3D].colour.g = 0xFF; polyList3D[vertexSize3D].colour.b = 0xFF; polyList3D[vertexSize3D].colour.a = 0xFF; vertexSize3D++; polyList3D[vertexSize3D].x = polyList3D[vertexSize3D - 2].x; polyList3D[vertexSize3D].y = 0.0f; polyList3D[vertexSize3D].z = cosValue512; polyList3D[vertexSize3D].u = polyList3D[vertexSize3D - 2].u; polyList3D[vertexSize3D].v = tileUVArray[tiles128x128.gfxDataPos[tileIndex] + tileOffset]; polyList3D[vertexSize3D].colour.r = 0xFF; polyList3D[vertexSize3D].colour.g = 0xFF; polyList3D[vertexSize3D].colour.b = 0xFF; polyList3D[vertexSize3D].colour.a = 0xFF; vertexSize3D++; polyList3D[vertexSize3D].x = polyList3D[vertexSize3D - 2].x; polyList3D[vertexSize3D].y = 0.0f; polyList3D[vertexSize3D].z = polyList3D[vertexSize3D - 1].z; polyList3D[vertexSize3D].u = polyList3D[vertexSize3D - 2].u; polyList3D[vertexSize3D].v = polyList3D[vertexSize3D - 1].v; polyList3D[vertexSize3D].colour.r = 0xFF; polyList3D[vertexSize3D].colour.g = 0xFF; polyList3D[vertexSize3D].colour.b = 0xFF; polyList3D[vertexSize3D].colour.a = 0xFF; vertexSize3D++; indexSize3D += 6; break; } } } } sinValue512 += 16; } sinValue512 -= 0x140; cosValue512 -= 16; } } floor3DXPos = (layer->XPos >> 8) * -0.00390625f; floor3DYPos = (layer->YPos >> 8) * 0.00390625f; floor3DZPos = (layer->ZPos >> 8) * -0.00390625f; floor3DAngle = layer->angle / 512.0f * -360.0f; render3DEnabled = true; #endif } void Draw3DSkyLayer(int layerID) { #if RETRO_SOFTWARE_RENDER TileLayer *layer = &stageLayouts[activeTileLayers[layerID]]; int layerWidth = layer->width << 7; int layerHeight = layer->height << 7; int layerYPos = layer->YPos; int sinValue = sinValM7[layer->angle & 0x1FF]; int cosValue = cosValM7[layer->angle & 0x1FF]; ushort *frameBufferPtr = &Engine.frameBuffer[((SCREEN_YSIZE / 2) + 12) * SCREEN_XSIZE]; ushort *bufferPtr = Engine.frameBuffer2x; if (!drawStageGFXHQ) bufferPtr = &Engine.frameBuffer[((SCREEN_YSIZE / 2) + 12) * SCREEN_XSIZE]; byte *linePtr = &gfxLineBuffer[((SCREEN_YSIZE / 2) + 12)]; int layerXPos = layer->XPos >> 4; int layerZPos = layer->ZPos >> 4; for (int i = TILE_SIZE / 2; i < SCREEN_YSIZE - TILE_SIZE; ++i) { if (!(i & 1)) { activePalette = fullPalette[*linePtr]; activePalette32 = fullPalette32[*linePtr]; linePtr++; } int xBuffer = layerYPos / (i << 8) * -cosValue >> 9; int yBuffer = sinValue * (layerYPos / (i << 8)) >> 9; int XPos = layerXPos + (3 * sinValue * (layerYPos / (i << 8)) >> 2) - xBuffer * SCREEN_XSIZE; int YPos = layerZPos + (3 * cosValue * (layerYPos / (i << 8)) >> 2) - yBuffer * SCREEN_XSIZE; int lineBuffer = 0; while (lineBuffer < SCREEN_XSIZE * 2) { int tileX = XPos >> 12; int tileY = YPos >> 12; if (tileX > -1 && tileX < layerWidth && tileY > -1 && tileY < layerHeight) { int chunk = tile3DFloorBuffer[(YPos >> 16 << 8) + (XPos >> 16)]; byte *tilePixel = &tilesetGFXData[tiles128x128.gfxDataPos[chunk]]; switch (tiles128x128.direction[chunk]) { case FLIP_NONE: tilePixel += TILE_SIZE * (tileY & 0xF) + (tileX & 0xF); break; case FLIP_X: tilePixel += TILE_SIZE * (tileY & 0xF) + 0xF - (tileX & 0xF); break; case FLIP_Y: tilePixel += (tileX & 0xF) + SCREEN_YSIZE - TILE_SIZE * (tileY & 0xF); break; case FLIP_XY: tilePixel += 0xF - (tileX & 0xF) + SCREEN_YSIZE - TILE_SIZE * (tileY & 0xF); break; default: break; } if (*tilePixel > 0) *bufferPtr = activePalette[*tilePixel]; else if (drawStageGFXHQ) *bufferPtr = *frameBufferPtr; } else if (drawStageGFXHQ) { *bufferPtr = *frameBufferPtr; } if (lineBuffer & 1) ++frameBufferPtr; if (drawStageGFXHQ) { bufferPtr++; } else if (lineBuffer & 1) { ++bufferPtr; } lineBuffer++; XPos += xBuffer; YPos += yBuffer; } if (!(i & 1)) frameBufferPtr -= SCREEN_XSIZE; if (!(i & 1) && !drawStageGFXHQ) { bufferPtr -= SCREEN_XSIZE; } } if (drawStageGFXHQ) { frameBufferPtr = &Engine.frameBuffer[((SCREEN_YSIZE / 2) + 12) * SCREEN_XSIZE]; int cnt = ((SCREEN_YSIZE / 2) - 12) * SCREEN_XSIZE; while (cnt--) *frameBufferPtr++ = 0xF81F; // Magenta } #endif #if RETRO_HARDWARE_RENDER // unimplimented in RSDK #endif } void DrawRectangle(int XPos, int YPos, int width, int height, int R, int G, int B, int A) { if (A > 0xFF) A = 0xFF; #if RETRO_SOFTWARE_RENDER if (width + XPos > SCREEN_XSIZE) width = SCREEN_XSIZE - XPos; if (XPos < 0) { width += XPos; XPos = 0; } if (height + YPos > SCREEN_YSIZE) height = SCREEN_YSIZE - YPos; if (YPos < 0) { height += YPos; YPos = 0; } if (width <= 0 || height <= 0 || A <= 0) return; int pitch = SCREEN_XSIZE - width; ushort *frameBufferPtr = &Engine.frameBuffer[XPos + SCREEN_XSIZE * YPos]; ushort clr = RGB888_TO_RGB565(R, G, B); if (A == 0xFF) { int h = height; while (h--) { int w = width; while (w--) { *frameBufferPtr = clr; ++frameBufferPtr; } frameBufferPtr += pitch; } } else { int h = height; while (h--) { int w = width; while (w--) { ushort *blendPtrB = &blendLookupTable[BLENDTABLE_XSIZE * (0xFF - A)]; ushort *blendPtrA = &blendLookupTable[BLENDTABLE_XSIZE * A]; *frameBufferPtr = (blendPtrB[*frameBufferPtr & (BLENDTABLE_XSIZE - 1)] + blendPtrA[((byte)(B >> 3) | (byte)(32 * (G >> 2))) & 0x1F]) | ((blendPtrB[(*frameBufferPtr & 0x7E0) >> 6] + blendPtrA[(clr & 0x7E0) >> 6]) << 6) | ((blendPtrB[(*frameBufferPtr & 0xF800) >> 11] + blendPtrA[(clr & 0xF800) >> 11]) << 11); ++frameBufferPtr; } frameBufferPtr += pitch; } } #endif #if RETRO_HARDWARE_RENDER if (gfxVertexSize < VERTEX_LIMIT) { gfxPolyList[gfxVertexSize].x = XPos << 4; gfxPolyList[gfxVertexSize].y = YPos << 4; gfxPolyList[gfxVertexSize].colour.r = R; gfxPolyList[gfxVertexSize].colour.g = G; gfxPolyList[gfxVertexSize].colour.b = B; gfxPolyList[gfxVertexSize].colour.a = A; gfxPolyList[gfxVertexSize].u = 0.0f; gfxPolyList[gfxVertexSize].v = 0.0f; gfxVertexSize++; gfxPolyList[gfxVertexSize].x = XPos + width << 4; gfxPolyList[gfxVertexSize].y = YPos << 4; gfxPolyList[gfxVertexSize].colour.r = R; gfxPolyList[gfxVertexSize].colour.g = G; gfxPolyList[gfxVertexSize].colour.b = B; gfxPolyList[gfxVertexSize].colour.a = A; gfxPolyList[gfxVertexSize].u = 0.01f; gfxPolyList[gfxVertexSize].v = gfxPolyList[gfxVertexSize - 1].v; gfxVertexSize++; gfxPolyList[gfxVertexSize].x = XPos << 4; gfxPolyList[gfxVertexSize].y = YPos + height << 4; gfxPolyList[gfxVertexSize].colour.r = R; gfxPolyList[gfxVertexSize].colour.g = G; gfxPolyList[gfxVertexSize].colour.b = B; gfxPolyList[gfxVertexSize].colour.a = A; gfxPolyList[gfxVertexSize].u = 0.0f; gfxPolyList[gfxVertexSize].v = 0.01f; gfxVertexSize++; gfxPolyList[gfxVertexSize].x = gfxPolyList[gfxVertexSize - 2].x; gfxPolyList[gfxVertexSize].y = gfxPolyList[gfxVertexSize - 1].y; gfxPolyList[gfxVertexSize].colour.r = R; gfxPolyList[gfxVertexSize].colour.g = G; gfxPolyList[gfxVertexSize].colour.b = B; gfxPolyList[gfxVertexSize].colour.a = A; gfxPolyList[gfxVertexSize].u = 0.01f; gfxPolyList[gfxVertexSize].v = 0.01f; gfxVertexSize++; gfxIndexSize += 6; } #endif } void SetFadeHQ(int R, int G, int B, int A) { #if RETRO_SOFTWARE_RENDER if (A <= 0) return; if (A > 0xFF) A = 0xFF; int pitch = SCREEN_XSIZE * 2; ushort *frameBufferPtr = Engine.frameBuffer2x; ushort clr = RGB888_TO_RGB565(R, G, B); if (A == 0xFF) { int h = SCREEN_YSIZE; while (h--) { int w = pitch; while (w--) { *frameBufferPtr = clr; ++frameBufferPtr; } } } else { int h = SCREEN_YSIZE; while (h--) { int w = pitch; while (w--) { ushort *blendPtrB = &blendLookupTable[BLENDTABLE_XSIZE * (0xFF - A)]; ushort *blendPtrA = &blendLookupTable[BLENDTABLE_XSIZE * A]; *frameBufferPtr = (blendPtrB[*frameBufferPtr & (BLENDTABLE_XSIZE - 1)] + blendPtrA[((byte)(B >> 3) | (byte)(32 * (G >> 2))) & 0x1F]) | ((blendPtrB[(*frameBufferPtr & 0x7E0) >> 6] + blendPtrA[(clr & 0x7E0) >> 6]) << 6) | ((blendPtrB[(*frameBufferPtr & 0xF800) >> 11] + blendPtrA[(clr & 0xF800) >> 11]) << 11); ++frameBufferPtr; } } } #endif #if RETRO_HARDWARE_RENDER // TODO: this #endif } void DrawTintRectangle(int XPos, int YPos, int width, int height) { #if RETRO_SOFTWARE_RENDER if (width + XPos > SCREEN_XSIZE) width = SCREEN_XSIZE - XPos; if (XPos < 0) { width += XPos; XPos = 0; } if (height + YPos > SCREEN_YSIZE) height = SCREEN_YSIZE - YPos; if (YPos < 0) { height += YPos; YPos = 0; } if (width <= 0 || height <= 0) return; int yOffset = SCREEN_XSIZE - width; for (ushort *frameBufferPtr = &Engine.frameBuffer[XPos + SCREEN_XSIZE * YPos];; frameBufferPtr += yOffset) { height--; if (!height) break; int w = width; while (w--) { *frameBufferPtr = tintLookupTable[*frameBufferPtr]; ++frameBufferPtr; } } #endif #if RETRO_HARDWARE_RENDER // Not avaliable in HW Render mode #endif } void DrawScaledTintMask(int direction, int XPos, int YPos, int pivotX, int pivotY, int scaleX, int scaleY, int width, int height, int sprX, int sprY, int sheetID) { #if RETRO_SOFTWARE_RENDER int roundedYPos = 0; int roundedXPos = 0; int truescaleX = 4 * scaleX; int truescaleY = 4 * scaleY; int widthM1 = width - 1; int trueXPos = XPos - (truescaleX * pivotX >> 11); width = truescaleX * width >> 11; int trueYPos = YPos - (truescaleY * pivotY >> 11); height = truescaleY * height >> 11; int finalscaleX = (signed int)(float)((float)(2048.0 / (float)truescaleX) * 2048.0); int finalscaleY = (signed int)(float)((float)(2048.0 / (float)truescaleY) * 2048.0); if (width + trueXPos > SCREEN_XSIZE) { width = SCREEN_XSIZE - trueXPos; } if (direction) { if (trueXPos < 0) { widthM1 -= trueXPos * -finalscaleX >> 11; roundedXPos = (ushort)trueXPos * -(short)finalscaleX & 0x7FF; width += trueXPos; trueXPos = 0; } } else if (trueXPos < 0) { sprX += trueXPos * -finalscaleX >> 11; roundedXPos = (ushort)trueXPos * -(short)finalscaleX & 0x7FF; width += trueXPos; trueXPos = 0; } if (height + trueYPos > SCREEN_YSIZE) { height = SCREEN_YSIZE - trueYPos; } if (trueYPos < 0) { sprY += trueYPos * -finalscaleY >> 11; roundedYPos = (ushort)trueYPos * -(short)finalscaleY & 0x7FF; height += trueYPos; trueYPos = 0; } if (width <= 0 || height <= 0) return; GFXSurface *surface = &gfxSurface[sheetID]; int pitch = SCREEN_XSIZE - width; int gfxwidth = surface->width; // byte *lineBuffer = &gfxLineBuffer[trueYPos]; byte *gfxData = &graphicData[sprX + surface->width * sprY + surface->dataPosition]; ushort *frameBufferPtr = &Engine.frameBuffer[trueXPos + SCREEN_XSIZE * trueYPos]; if (direction == FLIP_X) { byte *gfxDataPtr = &gfxData[widthM1]; int gfxPitch = 0; while (height--) { int roundXPos = roundedXPos; int w = width; while (w--) { if (*gfxDataPtr > 0) *frameBufferPtr = tintLookupTable[*gfxDataPtr]; int offsetX = finalscaleX + roundXPos; gfxDataPtr -= offsetX >> 11; gfxPitch += offsetX >> 11; roundXPos = offsetX & 0x7FF; ++frameBufferPtr; } frameBufferPtr += pitch; int offsetY = finalscaleY + roundedYPos; gfxDataPtr += gfxPitch + (offsetY >> 11) * gfxwidth; roundedYPos = offsetY & 0x7FF; gfxPitch = 0; } } else { int gfxPitch = 0; int h = height; while (h--) { int roundXPos = roundedXPos; int w = width; while (w--) { if (*gfxData > 0) *frameBufferPtr = tintLookupTable[*gfxData]; int offsetX = finalscaleX + roundXPos; gfxData += offsetX >> 11; gfxPitch += offsetX >> 11; roundXPos = offsetX & 0x7FF; ++frameBufferPtr; } frameBufferPtr += pitch; int offsetY = finalscaleY + roundedYPos; gfxData += (offsetY >> 11) * gfxwidth - gfxPitch; roundedYPos = offsetY & 0x7FF; gfxPitch = 0; } } #endif #if RETRO_HARDWARE_RENDER // Not avaliable in HW Render mode #endif } void DrawSprite(int XPos, int YPos, int width, int height, int sprX, int sprY, int sheetID) { #if RETRO_SOFTWARE_RENDER if (width + XPos > SCREEN_XSIZE) width = SCREEN_XSIZE - XPos; if (XPos < 0) { sprX -= XPos; width += XPos; XPos = 0; } if (height + YPos > SCREEN_YSIZE) height = SCREEN_YSIZE - YPos; if (YPos < 0) { sprY -= YPos; height += YPos; YPos = 0; } if (width <= 0 || height <= 0) return; GFXSurface *surface = &gfxSurface[sheetID]; int pitch = SCREEN_XSIZE - width; int gfxPitch = surface->width - width; byte *lineBuffer = &gfxLineBuffer[YPos]; byte *gfxDataPtr = &graphicData[sprX + surface->width * sprY + surface->dataPosition]; ushort *frameBufferPtr = &Engine.frameBuffer[XPos + SCREEN_XSIZE * YPos]; while (height--) { activePalette = fullPalette[*lineBuffer]; activePalette32 = fullPalette32[*lineBuffer]; lineBuffer++; int w = width; while (w--) { if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; ++gfxDataPtr; ++frameBufferPtr; } frameBufferPtr += pitch; gfxDataPtr += gfxPitch; } #endif #if RETRO_HARDWARE_RENDER GFXSurface *surface = &gfxSurface[sheetID]; if (surface->texStartX > -1 && gfxVertexSize < VERTEX_LIMIT && XPos > -512 && XPos < 872 && YPos > -512 && YPos < 752) { gfxPolyList[gfxVertexSize].x = XPos << 4; gfxPolyList[gfxVertexSize].y = YPos << 4; gfxPolyList[gfxVertexSize].colour.r = 0xFF; gfxPolyList[gfxVertexSize].colour.g = 0xFF; gfxPolyList[gfxVertexSize].colour.b = 0xFF; gfxPolyList[gfxVertexSize].colour.a = 0xFF; gfxPolyList[gfxVertexSize].u = (surface->texStartX + sprX); gfxPolyList[gfxVertexSize].v = (surface->texStartY + sprY); gfxVertexSize++; gfxPolyList[gfxVertexSize].x = XPos + width << 4; gfxPolyList[gfxVertexSize].y = YPos << 4; gfxPolyList[gfxVertexSize].colour.r = 0xFF; gfxPolyList[gfxVertexSize].colour.g = 0xFF; gfxPolyList[gfxVertexSize].colour.b = 0xFF; gfxPolyList[gfxVertexSize].colour.a = 0xFF; gfxPolyList[gfxVertexSize].u = (surface->texStartX + sprX + width); gfxPolyList[gfxVertexSize].v = gfxPolyList[gfxVertexSize - 1].v; gfxVertexSize++; gfxPolyList[gfxVertexSize].x = XPos << 4; gfxPolyList[gfxVertexSize].y = YPos + height << 4; gfxPolyList[gfxVertexSize].colour.r = 0xFF; gfxPolyList[gfxVertexSize].colour.g = 0xFF; gfxPolyList[gfxVertexSize].colour.b = 0xFF; gfxPolyList[gfxVertexSize].colour.a = 0xFF; gfxPolyList[gfxVertexSize].u = gfxPolyList[gfxVertexSize - 2].u; gfxPolyList[gfxVertexSize].v = (surface->texStartY + sprY + height); gfxVertexSize++; gfxPolyList[gfxVertexSize].x = gfxPolyList[gfxVertexSize - 2].x; gfxPolyList[gfxVertexSize].y = gfxPolyList[gfxVertexSize - 1].y; gfxPolyList[gfxVertexSize].colour.r = 0xFF; gfxPolyList[gfxVertexSize].colour.g = 0xFF; gfxPolyList[gfxVertexSize].colour.b = 0xFF; gfxPolyList[gfxVertexSize].colour.a = 0xFF; gfxPolyList[gfxVertexSize].u = gfxPolyList[gfxVertexSize - 2].u; gfxPolyList[gfxVertexSize].v = gfxPolyList[gfxVertexSize - 1].v; gfxVertexSize++; gfxIndexSize += 6; } #endif } void DrawSpriteFlipped(int XPos, int YPos, int width, int height, int sprX, int sprY, int direction, int sheetID) { #if RETRO_SOFTWARE_RENDER int widthFlip = width; int heightFlip = height; if (width + XPos > SCREEN_XSIZE) { width = SCREEN_XSIZE - XPos; } if (XPos < 0) { sprX -= XPos; width += XPos; widthFlip += XPos + XPos; XPos = 0; } if (height + YPos > SCREEN_YSIZE) { height = SCREEN_YSIZE - YPos; } if (YPos < 0) { sprY -= YPos; height += YPos; heightFlip += YPos + YPos; YPos = 0; } if (width <= 0 || height <= 0) return; GFXSurface *surface = &gfxSurface[sheetID]; int pitch; int gfxPitch; byte *lineBuffer; byte *gfxData; ushort *frameBufferPtr; switch (direction) { case FLIP_NONE: pitch = SCREEN_XSIZE - width; gfxPitch = surface->width - width; lineBuffer = &gfxLineBuffer[YPos]; gfxData = &graphicData[sprX + surface->width * sprY + surface->dataPosition]; frameBufferPtr = &Engine.frameBuffer[XPos + SCREEN_XSIZE * YPos]; while (height--) { activePalette = fullPalette[*lineBuffer]; activePalette32 = fullPalette32[*lineBuffer]; lineBuffer++; int w = width; while (w--) { if (*gfxData > 0) *frameBufferPtr = activePalette[*gfxData]; ++gfxData; ++frameBufferPtr; } frameBufferPtr += pitch; gfxData += gfxPitch; } break; case FLIP_X: pitch = SCREEN_XSIZE - width; gfxPitch = width + surface->width; lineBuffer = &gfxLineBuffer[YPos]; gfxData = &graphicData[widthFlip - 1 + sprX + surface->width * sprY + surface->dataPosition]; frameBufferPtr = &Engine.frameBuffer[XPos + SCREEN_XSIZE * YPos]; while (height--) { activePalette = fullPalette[*lineBuffer]; activePalette32 = fullPalette32[*lineBuffer]; lineBuffer++; int w = width; while (w--) { if (*gfxData > 0) *frameBufferPtr = activePalette[*gfxData]; --gfxData; ++frameBufferPtr; } frameBufferPtr += pitch; gfxData += gfxPitch; } break; case FLIP_Y: pitch = SCREEN_XSIZE - width; gfxPitch = width + surface->width; lineBuffer = &gfxLineBuffer[YPos]; gfxData = &graphicData[sprX + surface->width * (sprY + heightFlip - 1) + surface->dataPosition]; frameBufferPtr = &Engine.frameBuffer[XPos + SCREEN_XSIZE * YPos]; while (height--) { activePalette = fullPalette[*lineBuffer]; activePalette32 = fullPalette32[*lineBuffer]; lineBuffer++; int w = width; while (w--) { if (*gfxData > 0) *frameBufferPtr = activePalette[*gfxData]; ++gfxData; ++frameBufferPtr; } frameBufferPtr += pitch; gfxData -= gfxPitch; } break; case FLIP_XY: pitch = SCREEN_XSIZE - width; gfxPitch = surface->width - width; lineBuffer = &gfxLineBuffer[YPos]; gfxData = &graphicData[widthFlip - 1 + sprX + surface->width * (sprY + heightFlip - 1) + surface->dataPosition]; frameBufferPtr = &Engine.frameBuffer[XPos + SCREEN_XSIZE * YPos]; while (height--) { activePalette = fullPalette[*lineBuffer]; activePalette32 = fullPalette32[*lineBuffer]; lineBuffer++; int w = width; while (w--) { if (*gfxData > 0) *frameBufferPtr = activePalette[*gfxData]; --gfxData; ++frameBufferPtr; } frameBufferPtr += pitch; gfxData -= gfxPitch; } break; default: break; } #endif #if RETRO_HARDWARE_RENDER GFXSurface *surface = &gfxSurface[sheetID]; if (surface->texStartX > -1 && gfxVertexSize < VERTEX_LIMIT && XPos > -512 && XPos < 872 && YPos > -512 && YPos < 752) { switch (direction) { case FLIP_NONE: gfxPolyList[gfxVertexSize].x = XPos << 4; gfxPolyList[gfxVertexSize].y = YPos << 4; gfxPolyList[gfxVertexSize].colour.r = 0xFF; gfxPolyList[gfxVertexSize].colour.g = 0xFF; gfxPolyList[gfxVertexSize].colour.b = 0xFF; gfxPolyList[gfxVertexSize].colour.a = 0xFF; gfxPolyList[gfxVertexSize].u = (surface->texStartX + sprX); gfxPolyList[gfxVertexSize].v = (surface->texStartY + sprY); gfxVertexSize++; gfxPolyList[gfxVertexSize].x = XPos + width << 4; gfxPolyList[gfxVertexSize].y = YPos << 4; gfxPolyList[gfxVertexSize].colour.r = 0xFF; gfxPolyList[gfxVertexSize].colour.g = 0xFF; gfxPolyList[gfxVertexSize].colour.b = 0xFF; gfxPolyList[gfxVertexSize].colour.a = 0xFF; gfxPolyList[gfxVertexSize].u = (surface->texStartX + sprX + width); gfxPolyList[gfxVertexSize].v = gfxPolyList[gfxVertexSize - 1].v; gfxVertexSize++; gfxPolyList[gfxVertexSize].x = XPos << 4; gfxPolyList[gfxVertexSize].y = YPos + height << 4; gfxPolyList[gfxVertexSize].colour.r = 0xFF; gfxPolyList[gfxVertexSize].colour.g = 0xFF; gfxPolyList[gfxVertexSize].colour.b = 0xFF; gfxPolyList[gfxVertexSize].colour.a = 0xFF; gfxPolyList[gfxVertexSize].u = gfxPolyList[gfxVertexSize - 2].u; gfxPolyList[gfxVertexSize].v = (surface->texStartY + sprY + height); gfxVertexSize++; gfxPolyList[gfxVertexSize].x = gfxPolyList[gfxVertexSize - 2].x; gfxPolyList[gfxVertexSize].y = gfxPolyList[gfxVertexSize - 1].y; gfxPolyList[gfxVertexSize].colour.r = 0xFF; gfxPolyList[gfxVertexSize].colour.g = 0xFF; gfxPolyList[gfxVertexSize].colour.b = 0xFF; gfxPolyList[gfxVertexSize].colour.a = 0xFF; gfxPolyList[gfxVertexSize].u = gfxPolyList[gfxVertexSize - 2].u; gfxPolyList[gfxVertexSize].v = gfxPolyList[gfxVertexSize - 1].v; gfxVertexSize++; break; case FLIP_X: gfxPolyList[gfxVertexSize].x = XPos << 4; gfxPolyList[gfxVertexSize].y = YPos << 4; gfxPolyList[gfxVertexSize].colour.r = 0xFF; gfxPolyList[gfxVertexSize].colour.g = 0xFF; gfxPolyList[gfxVertexSize].colour.b = 0xFF; gfxPolyList[gfxVertexSize].colour.a = 0xFF; gfxPolyList[gfxVertexSize].u = (surface->texStartX + sprX + width); gfxPolyList[gfxVertexSize].v = (surface->texStartY + sprY); gfxVertexSize++; gfxPolyList[gfxVertexSize].x = XPos + width << 4; gfxPolyList[gfxVertexSize].y = YPos << 4; gfxPolyList[gfxVertexSize].colour.r = 0xFF; gfxPolyList[gfxVertexSize].colour.g = 0xFF; gfxPolyList[gfxVertexSize].colour.b = 0xFF; gfxPolyList[gfxVertexSize].colour.a = 0xFF; gfxPolyList[gfxVertexSize].u = (surface->texStartX + sprX); gfxPolyList[gfxVertexSize].v = gfxPolyList[gfxVertexSize - 1].v; gfxVertexSize++; gfxPolyList[gfxVertexSize].x = XPos << 4; gfxPolyList[gfxVertexSize].y = YPos + height << 4; gfxPolyList[gfxVertexSize].colour.r = 0xFF; gfxPolyList[gfxVertexSize].colour.g = 0xFF; gfxPolyList[gfxVertexSize].colour.b = 0xFF; gfxPolyList[gfxVertexSize].colour.a = 0xFF; gfxPolyList[gfxVertexSize].u = gfxPolyList[gfxVertexSize - 2].u; gfxPolyList[gfxVertexSize].v = (surface->texStartY + sprY + height); gfxVertexSize++; gfxPolyList[gfxVertexSize].x = gfxPolyList[gfxVertexSize - 2].x; gfxPolyList[gfxVertexSize].y = gfxPolyList[gfxVertexSize - 1].y; gfxPolyList[gfxVertexSize].colour.r = 0xFF; gfxPolyList[gfxVertexSize].colour.g = 0xFF; gfxPolyList[gfxVertexSize].colour.b = 0xFF; gfxPolyList[gfxVertexSize].colour.a = 0xFF; gfxPolyList[gfxVertexSize].u = gfxPolyList[gfxVertexSize - 2].u; gfxPolyList[gfxVertexSize].v = gfxPolyList[gfxVertexSize - 1].v; gfxVertexSize++; break; case FLIP_Y: gfxPolyList[gfxVertexSize].x = XPos << 4; gfxPolyList[gfxVertexSize].y = YPos << 4; gfxPolyList[gfxVertexSize].colour.r = 0xFF; gfxPolyList[gfxVertexSize].colour.g = 0xFF; gfxPolyList[gfxVertexSize].colour.b = 0xFF; gfxPolyList[gfxVertexSize].colour.a = 0xFF; gfxPolyList[gfxVertexSize].u = (surface->texStartX + sprX); gfxPolyList[gfxVertexSize].v = (surface->texStartY + sprY + height); gfxVertexSize++; gfxPolyList[gfxVertexSize].x = XPos + width << 4; gfxPolyList[gfxVertexSize].y = YPos << 4; gfxPolyList[gfxVertexSize].colour.r = 0xFF; gfxPolyList[gfxVertexSize].colour.g = 0xFF; gfxPolyList[gfxVertexSize].colour.b = 0xFF; gfxPolyList[gfxVertexSize].colour.a = 0xFF; gfxPolyList[gfxVertexSize].u = (surface->texStartX + sprX + width); gfxPolyList[gfxVertexSize].v = gfxPolyList[gfxVertexSize - 1].v; gfxVertexSize++; gfxPolyList[gfxVertexSize].x = XPos << 4; gfxPolyList[gfxVertexSize].y = YPos + height << 4; gfxPolyList[gfxVertexSize].colour.r = 0xFF; gfxPolyList[gfxVertexSize].colour.g = 0xFF; gfxPolyList[gfxVertexSize].colour.b = 0xFF; gfxPolyList[gfxVertexSize].colour.a = 0xFF; gfxPolyList[gfxVertexSize].u = gfxPolyList[gfxVertexSize - 2].u; gfxPolyList[gfxVertexSize].v = (surface->texStartY + sprY); gfxVertexSize++; gfxPolyList[gfxVertexSize].x = gfxPolyList[gfxVertexSize - 2].x; gfxPolyList[gfxVertexSize].y = gfxPolyList[gfxVertexSize - 1].y; gfxPolyList[gfxVertexSize].colour.r = 0xFF; gfxPolyList[gfxVertexSize].colour.g = 0xFF; gfxPolyList[gfxVertexSize].colour.b = 0xFF; gfxPolyList[gfxVertexSize].colour.a = 0xFF; gfxPolyList[gfxVertexSize].u = gfxPolyList[gfxVertexSize - 2].u; gfxPolyList[gfxVertexSize].v = gfxPolyList[gfxVertexSize - 1].v; gfxVertexSize++; break; case FLIP_XY: gfxPolyList[gfxVertexSize].x = XPos << 4; gfxPolyList[gfxVertexSize].y = YPos << 4; gfxPolyList[gfxVertexSize].colour.r = 0xFF; gfxPolyList[gfxVertexSize].colour.g = 0xFF; gfxPolyList[gfxVertexSize].colour.b = 0xFF; gfxPolyList[gfxVertexSize].colour.a = 0xFF; gfxPolyList[gfxVertexSize].u = (surface->texStartX + sprX + width); gfxPolyList[gfxVertexSize].v = (surface->texStartY + sprY + height); gfxVertexSize++; gfxPolyList[gfxVertexSize].x = XPos + width << 4; gfxPolyList[gfxVertexSize].y = YPos << 4; gfxPolyList[gfxVertexSize].colour.r = 0xFF; gfxPolyList[gfxVertexSize].colour.g = 0xFF; gfxPolyList[gfxVertexSize].colour.b = 0xFF; gfxPolyList[gfxVertexSize].colour.a = 0xFF; gfxPolyList[gfxVertexSize].u = (surface->texStartX + sprX); gfxPolyList[gfxVertexSize].v = gfxPolyList[gfxVertexSize - 1].v; gfxVertexSize++; gfxPolyList[gfxVertexSize].x = XPos << 4; gfxPolyList[gfxVertexSize].y = YPos + height << 4; gfxPolyList[gfxVertexSize].colour.r = 0xFF; gfxPolyList[gfxVertexSize].colour.g = 0xFF; gfxPolyList[gfxVertexSize].colour.b = 0xFF; gfxPolyList[gfxVertexSize].colour.a = 0xFF; gfxPolyList[gfxVertexSize].u = gfxPolyList[gfxVertexSize - 2].u; gfxPolyList[gfxVertexSize].v = (surface->texStartY + sprY); gfxVertexSize++; gfxPolyList[gfxVertexSize].x = gfxPolyList[gfxVertexSize - 2].x; gfxPolyList[gfxVertexSize].y = gfxPolyList[gfxVertexSize - 1].y; gfxPolyList[gfxVertexSize].colour.r = 0xFF; gfxPolyList[gfxVertexSize].colour.g = 0xFF; gfxPolyList[gfxVertexSize].colour.b = 0xFF; gfxPolyList[gfxVertexSize].colour.a = 0xFF; gfxPolyList[gfxVertexSize].u = gfxPolyList[gfxVertexSize - 2].u; gfxPolyList[gfxVertexSize].v = gfxPolyList[gfxVertexSize - 1].v; gfxVertexSize++; break; } gfxIndexSize += 6; } #endif } void DrawSpriteScaled(int direction, int XPos, int YPos, int pivotX, int pivotY, int scaleX, int scaleY, int width, int height, int sprX, int sprY, int sheetID) { #if RETRO_SOFTWARE_RENDER int roundedYPos = 0; int roundedXPos = 0; int truescaleX = 4 * scaleX; int truescaleY = 4 * scaleY; int widthM1 = width - 1; int trueXPos = XPos - (truescaleX * pivotX >> 11); width = truescaleX * width >> 11; int trueYPos = YPos - (truescaleY * pivotY >> 11); height = truescaleY * height >> 11; int finalscaleX = (signed int)(float)((float)(2048.0 / (float)truescaleX) * 2048.0); int finalscaleY = (signed int)(float)((float)(2048.0 / (float)truescaleY) * 2048.0); if (width + trueXPos > SCREEN_XSIZE) { width = SCREEN_XSIZE - trueXPos; } if (direction) { if (trueXPos < 0) { widthM1 -= trueXPos * -finalscaleX >> 11; roundedXPos = (ushort)trueXPos * -(short)finalscaleX & 0x7FF; width += trueXPos; trueXPos = 0; } } else if (trueXPos < 0) { sprX += trueXPos * -finalscaleX >> 11; roundedXPos = (ushort)trueXPos * -(short)finalscaleX & 0x7FF; width += trueXPos; trueXPos = 0; } if (height + trueYPos > SCREEN_YSIZE) { height = SCREEN_YSIZE - trueYPos; } if (trueYPos < 0) { sprY += trueYPos * -finalscaleY >> 11; roundedYPos = (ushort)trueYPos * -(short)finalscaleY & 0x7FF; height += trueYPos; trueYPos = 0; } if (width <= 0 || height <= 0) return; GFXSurface *surface = &gfxSurface[sheetID]; int pitch = SCREEN_XSIZE - width; int gfxwidth = surface->width; byte *lineBuffer = &gfxLineBuffer[trueYPos]; byte *gfxData = &graphicData[sprX + surface->width * sprY + surface->dataPosition]; ushort *frameBufferPtr = &Engine.frameBuffer[trueXPos + SCREEN_XSIZE * trueYPos]; if (direction == FLIP_X) { byte *gfxDataPtr = &gfxData[widthM1]; int gfxPitch = 0; while (height--) { activePalette = fullPalette[*lineBuffer]; activePalette32 = fullPalette32[*lineBuffer]; lineBuffer++; int roundXPos = roundedXPos; int w = width; while (w--) { if (*gfxDataPtr > 0) *frameBufferPtr = activePalette[*gfxDataPtr]; int offsetX = finalscaleX + roundXPos; gfxDataPtr -= offsetX >> 11; gfxPitch += offsetX >> 11; roundXPos = offsetX & 0x7FF; ++frameBufferPtr; } frameBufferPtr += pitch; int offsetY = finalscaleY + roundedYPos; gfxDataPtr += gfxPitch + (offsetY >> 11) * gfxwidth; roundedYPos = offsetY & 0x7FF; gfxPitch = 0; } } else { int gfxPitch = 0; int h = height; while (h--) { activePalette = fullPalette[*lineBuffer]; activePalette32 = fullPalette32[*lineBuffer]; lineBuffer++; int roundXPos = roundedXPos; int w = width; while (w--) { if (*gfxData > 0) *frameBufferPtr = activePalette[*gfxData]; int offsetX = finalscaleX + roundXPos; gfxData += offsetX >> 11; gfxPitch += offsetX >> 11; roundXPos = offsetX & 0x7FF; ++frameBufferPtr; } frameBufferPtr += pitch; int offsetY = finalscaleY + roundedYPos; gfxData += (offsetY >> 11) * gfxwidth - gfxPitch; roundedYPos = offsetY & 0x7FF; gfxPitch = 0; } } #endif #if RETRO_HARDWARE_RENDER if (gfxVertexSize < VERTEX_LIMIT && XPos > -512 && XPos < 872 && YPos > -512 && YPos < 752) { scaleX <<= 2; scaleY <<= 2; XPos -= pivotX * scaleX >> 11; scaleX = width * scaleX >> 11; YPos -= pivotY * scaleY >> 11; scaleY = height * scaleY >> 11; GFXSurface *surface = &gfxSurface[sheetID]; if (surface->texStartX > -1) { gfxPolyList[gfxVertexSize].x = XPos << 4; gfxPolyList[gfxVertexSize].y = YPos << 4; gfxPolyList[gfxVertexSize].colour.r = 0xFF; gfxPolyList[gfxVertexSize].colour.g = 0xFF; gfxPolyList[gfxVertexSize].colour.b = 0xFF; gfxPolyList[gfxVertexSize].colour.a = 0xFF; gfxPolyList[gfxVertexSize].u = (surface->texStartX + sprX); gfxPolyList[gfxVertexSize].v = (surface->texStartY + sprY); gfxVertexSize++; gfxPolyList[gfxVertexSize].x = XPos + scaleX << 4; gfxPolyList[gfxVertexSize].y = YPos << 4; gfxPolyList[gfxVertexSize].colour.r = 0xFF; gfxPolyList[gfxVertexSize].colour.g = 0xFF; gfxPolyList[gfxVertexSize].colour.b = 0xFF; gfxPolyList[gfxVertexSize].colour.a = 0xFF; gfxPolyList[gfxVertexSize].u = (surface->texStartX + sprX + width); gfxPolyList[gfxVertexSize].v = gfxPolyList[gfxVertexSize - 1].v; gfxVertexSize++; gfxPolyList[gfxVertexSize].x = XPos << 4; gfxPolyList[gfxVertexSize].y = YPos + scaleY << 4; gfxPolyList[gfxVertexSize].colour.r = 0xFF; gfxPolyList[gfxVertexSize].colour.g = 0xFF; gfxPolyList[gfxVertexSize].colour.b = 0xFF; gfxPolyList[gfxVertexSize].colour.a = 0xFF; gfxPolyList[gfxVertexSize].u = gfxPolyList[gfxVertexSize - 2].u; gfxPolyList[gfxVertexSize].v = (surface->texStartY + sprY + height); gfxVertexSize++; gfxPolyList[gfxVertexSize].x = gfxPolyList[gfxVertexSize - 2].x; gfxPolyList[gfxVertexSize].y = gfxPolyList[gfxVertexSize - 1].y; gfxPolyList[gfxVertexSize].colour.r = 0xFF; gfxPolyList[gfxVertexSize].colour.g = 0xFF; gfxPolyList[gfxVertexSize].colour.b = 0xFF; gfxPolyList[gfxVertexSize].colour.a = 0xFF; gfxPolyList[gfxVertexSize].u = gfxPolyList[gfxVertexSize - 2].u; gfxPolyList[gfxVertexSize].v = gfxPolyList[gfxVertexSize - 1].v; gfxVertexSize++; gfxIndexSize += 6; } } #endif } #if RETRO_REV01 void DrawScaledChar(int direction, int XPos, int YPos, int pivotX, int pivotY, int scaleX, int scaleY, int width, int height, int sprX, int sprY, int sheetID) { #if RETRO_SOFTWARE_RENDER // Not avaliable in SW Render mode #endif #if RETRO_HARDWARE_RENDER GFXSurface *surface = &gfxSurface[sheetID]; if (gfxVertexSize < VERTEX_LIMIT && XPos > -8192 && XPos < 13951 && YPos > -1024 && YPos < 4864) { XPos -= pivotX * scaleX >> 5; scaleX = width * scaleX >> 5; YPos -= pivotY * scaleY >> 5; scaleY = height * scaleY >> 5; if (gfxSurface[sheetID].texStartX > -1 && gfxVertexSize < 4096) { gfxPolyList[gfxVertexSize].x = XPos; gfxPolyList[gfxVertexSize].y = YPos; gfxPolyList[gfxVertexSize].colour.r = 0xFF; gfxPolyList[gfxVertexSize].colour.g = 0xFF; gfxPolyList[gfxVertexSize].colour.b = 0xFF; gfxPolyList[gfxVertexSize].colour.a = 0xFF; gfxPolyList[gfxVertexSize].u = gfxSurface[sheetID].texStartX + sprX; gfxPolyList[gfxVertexSize].v = gfxSurface[sheetID].texStartY + sprY; gfxVertexSize++; gfxPolyList[gfxVertexSize].x = XPos + scaleX; gfxPolyList[gfxVertexSize].y = YPos; gfxPolyList[gfxVertexSize].colour.r = 0xFF; gfxPolyList[gfxVertexSize].colour.g = 0xFF; gfxPolyList[gfxVertexSize].colour.b = 0xFF; gfxPolyList[gfxVertexSize].colour.a = 0xFF; gfxPolyList[gfxVertexSize].u = gfxSurface[sheetID].texStartX + sprX + width; gfxPolyList[gfxVertexSize].v = gfxPolyList[gfxVertexSize - 1].v; gfxVertexSize++; gfxPolyList[gfxVertexSize].x = XPos; gfxPolyList[gfxVertexSize].y = YPos + scaleY; gfxPolyList[gfxVertexSize].colour.r = 0xFF; gfxPolyList[gfxVertexSize].colour.g = 0xFF; gfxPolyList[gfxVertexSize].colour.b = 0xFF; gfxPolyList[gfxVertexSize].colour.a = 0xFF; gfxPolyList[gfxVertexSize].u = gfxPolyList[gfxVertexSize - 2].u; gfxPolyList[gfxVertexSize].v = gfxSurface[sheetID].texStartY + sprY + height; gfxVertexSize++; gfxPolyList[gfxVertexSize].x = gfxPolyList[gfxVertexSize - 2].x; gfxPolyList[gfxVertexSize].y = gfxPolyList[gfxVertexSize - 1].y; gfxPolyList[gfxVertexSize].colour.r = 0xFF; gfxPolyList[gfxVertexSize].colour.g = 0xFF; gfxPolyList[gfxVertexSize].colour.b = 0xFF; gfxPolyList[gfxVertexSize].colour.a = 0xFF; gfxPolyList[gfxVertexSize].u = gfxPolyList[gfxVertexSize - 2].u; gfxPolyList[gfxVertexSize].v = gfxPolyList[gfxVertexSize - 1].v; gfxVertexSize++; gfxIndexSize += 6; } } #endif } #endif void DrawSpriteRotated(int direction, int XPos, int YPos, int pivotX, int pivotY, int sprX, int sprY, int width, int height, int rotation, int sheetID) { #if RETRO_SOFTWARE_RENDER int sprXPos = (pivotX + sprX) << 9; int sprYPos = (pivotY + sprY) << 9; int fullwidth = width + sprX; int fullheight = height + sprY; int angle = rotation & 0x1FF; if (angle < 0) angle += 0x200; if (angle) angle = 0x200 - angle; int sine = sinVal512[angle]; int cosine = cosVal512[angle]; int xPositions[4]; int yPositions[4]; if (direction == FLIP_X) { xPositions[0] = XPos + ((sine * (-pivotY - 2) + cosine * (pivotX + 2)) >> 9); yPositions[0] = YPos + ((cosine * (-pivotY - 2) - sine * (pivotX + 2)) >> 9); xPositions[1] = XPos + ((sine * (-pivotY - 2) + cosine * (pivotX - width - 2)) >> 9); yPositions[1] = YPos + ((cosine * (-pivotY - 2) - sine * (pivotX - width - 2)) >> 9); xPositions[2] = XPos + ((sine * (height - pivotY + 2) + cosine * (pivotX + 2)) >> 9); yPositions[2] = YPos + ((cosine * (height - pivotY + 2) - sine * (pivotX + 2)) >> 9); int a = pivotX - width - 2; int b = height - pivotY + 2; xPositions[3] = XPos + ((sine * b + cosine * a) >> 9); yPositions[3] = YPos + ((cosine * b - sine * a) >> 9); } else { xPositions[0] = XPos + ((sine * (-pivotY - 2) + cosine * (-pivotX - 2)) >> 9); yPositions[0] = YPos + ((cosine * (-pivotY - 2) - sine * (-pivotX - 2)) >> 9); xPositions[1] = XPos + ((sine * (-pivotY - 2) + cosine * (width - pivotX + 2)) >> 9); yPositions[1] = YPos + ((cosine * (-pivotY - 2) - sine * (width - pivotX + 2)) >> 9); xPositions[2] = XPos + ((sine * (height - pivotY + 2) + cosine * (-pivotX - 2)) >> 9); yPositions[2] = YPos + ((cosine * (height - pivotY + 2) - sine * (-pivotX - 2)) >> 9); int a = width - pivotX + 2; int b = height - pivotY + 2; xPositions[3] = XPos + ((sine * b + cosine * a) >> 9); yPositions[3] = YPos + ((cosine * b - sine * a) >> 9); } int left = SCREEN_XSIZE; for (int i = 0; i < 4; ++i) { if (xPositions[i] < left) left = xPositions[i]; } if (left < 0) left = 0; int right = 0; for (int i = 0; i < 4; ++i) { if (xPositions[i] > right) right = xPositions[i]; } if (right > SCREEN_XSIZE) right = SCREEN_XSIZE; int maxX = right - left; int top = SCREEN_YSIZE; for (int i = 0; i < 4; ++i) { if (yPositions[i] < top) top = yPositions[i]; } if (top < 0) top = 0; int bottom = 0; for (int i = 0; i < 4; ++i) { if (yPositions[i] > bottom) bottom = yPositions[i]; } if (bottom > SCREEN_YSIZE) bottom = SCREEN_YSIZE; int maxY = bottom - top; if (maxX <= 0 || maxY <= 0) return; GFXSurface *surface = &gfxSurface[sheetID]; int pitch = SCREEN_XSIZE - maxX; int lineSize = surface->widthShift; ushort *frameBufferPtr = &Engine.frameBuffer[left + SCREEN_XSIZE * top]; byte *lineBuffer = &gfxLineBuffer[top]; int startX = left - XPos; int startY = top - YPos; int shiftPivot = (sprX << 9) - 1; fullwidth <<= 9; int shiftheight = (sprY << 9) - 1; fullheight <<= 9; byte *gfxData = &graphicData[surface->dataPosition]; if (cosine < 0 || sine < 0) sprYPos += sine + cosine; if (direction == FLIP_X) { int drawX = sprXPos - (cosine * startX - sine * startY) - 0x100; int drawY = cosine * startY + sprYPos + sine * startX; while (maxY--) { activePalette = fullPalette[*lineBuffer]; activePalette32 = fullPalette32[*lineBuffer]; lineBuffer++; int finalX = drawX; int finalY = drawY; int w = maxX; while (w--) { if (finalX > shiftPivot && finalX < fullwidth && finalY > shiftheight && finalY < fullheight) { byte index = gfxData[(finalY >> 9 << lineSize) + (finalX >> 9)]; if (index > 0) *frameBufferPtr = activePalette[index]; } ++frameBufferPtr; finalX -= cosine; finalY += sine; } drawX += sine; drawY += cosine; frameBufferPtr += pitch; } } else { int drawX = sprXPos + cosine * startX - sine * startY; int drawY = cosine * startY + sprYPos + sine * startX; while (maxY--) { activePalette = fullPalette[*lineBuffer]; activePalette32 = fullPalette32[*lineBuffer]; lineBuffer++; int finalX = drawX; int finalY = drawY; int w = maxX; while (w--) { if (finalX > shiftPivot && finalX < fullwidth && finalY > shiftheight && finalY < fullheight) { byte index = gfxData[(finalY >> 9 << lineSize) + (finalX >> 9)]; if (index > 0) *frameBufferPtr = activePalette[index]; } ++frameBufferPtr; finalX += cosine; finalY += sine; } drawX -= sine; drawY += cosine; frameBufferPtr += pitch; } } #endif #if RETRO_HARDWARE_RENDER GFXSurface *surface = &gfxSurface[sheetID]; XPos <<= 4; YPos <<= 4; rotation -= rotation >> 9 << 9; if (rotation < 0) { rotation += 0x200; } if (rotation != 0) { rotation = 0x200 - rotation; } int sin = sinVal512[rotation]; int cos = cosVal512[rotation]; if (surface->texStartX > -1 && gfxVertexSize < VERTEX_LIMIT && XPos > -8192 && XPos < 13952 && YPos > -8192 && YPos < 12032) { if (direction == FLIP_NONE) { int x = -pivotX; int y = -pivotY; gfxPolyList[gfxVertexSize].x = XPos + (x * cos + y * sin >> 5); gfxPolyList[gfxVertexSize].y = YPos + (y * cos - x * sin >> 5); gfxPolyList[gfxVertexSize].colour.r = 0xFF; gfxPolyList[gfxVertexSize].colour.g = 0xFF; gfxPolyList[gfxVertexSize].colour.b = 0xFF; gfxPolyList[gfxVertexSize].colour.a = 0xFF; gfxPolyList[gfxVertexSize].u = (surface->texStartX + sprX); gfxPolyList[gfxVertexSize].v = (surface->texStartY + sprY); gfxVertexSize++; x = width - pivotX; y = -pivotY; gfxPolyList[gfxVertexSize].x = XPos + (x * cos + y * sin >> 5); gfxPolyList[gfxVertexSize].y = YPos + (y * cos - x * sin >> 5); gfxPolyList[gfxVertexSize].colour.r = 0xFF; gfxPolyList[gfxVertexSize].colour.g = 0xFF; gfxPolyList[gfxVertexSize].colour.b = 0xFF; gfxPolyList[gfxVertexSize].colour.a = 0xFF; gfxPolyList[gfxVertexSize].u = (surface->texStartX + sprX + width); gfxPolyList[gfxVertexSize].v = gfxPolyList[gfxVertexSize - 1].v; gfxVertexSize++; x = -pivotX; y = height - pivotY; gfxPolyList[gfxVertexSize].x = XPos + (x * cos + y * sin >> 5); gfxPolyList[gfxVertexSize].y = YPos + (y * cos - x * sin >> 5); gfxPolyList[gfxVertexSize].colour.r = 0xFF; gfxPolyList[gfxVertexSize].colour.g = 0xFF; gfxPolyList[gfxVertexSize].colour.b = 0xFF; gfxPolyList[gfxVertexSize].colour.a = 0xFF; gfxPolyList[gfxVertexSize].u = gfxPolyList[gfxVertexSize - 2].u; gfxPolyList[gfxVertexSize].v = (surface->texStartY + sprY + height); gfxVertexSize++; x = width - pivotX; y = height - pivotY; gfxPolyList[gfxVertexSize].x = XPos + (x * cos + y * sin >> 5); gfxPolyList[gfxVertexSize].y = YPos + (y * cos - x * sin >> 5); gfxPolyList[gfxVertexSize].colour.r = 0xFF; gfxPolyList[gfxVertexSize].colour.g = 0xFF; gfxPolyList[gfxVertexSize].colour.b = 0xFF; gfxPolyList[gfxVertexSize].colour.a = 0xFF; gfxPolyList[gfxVertexSize].u = gfxPolyList[gfxVertexSize - 2].u; gfxPolyList[gfxVertexSize].v = gfxPolyList[gfxVertexSize - 1].v; gfxVertexSize++; gfxIndexSize += 6; } else { int x = pivotX; int y = -pivotY; gfxPolyList[gfxVertexSize].x = XPos + (x * cos + y * sin >> 5); gfxPolyList[gfxVertexSize].y = YPos + (y * cos - x * sin >> 5); gfxPolyList[gfxVertexSize].colour.r = 0xFF; gfxPolyList[gfxVertexSize].colour.g = 0xFF; gfxPolyList[gfxVertexSize].colour.b = 0xFF; gfxPolyList[gfxVertexSize].colour.a = 0xFF; gfxPolyList[gfxVertexSize].u = (surface->texStartX + sprX); gfxPolyList[gfxVertexSize].v = (surface->texStartY + sprY); gfxVertexSize++; x = pivotX - width; y = -pivotY; gfxPolyList[gfxVertexSize].x = XPos + (x * cos + y * sin >> 5); gfxPolyList[gfxVertexSize].y = YPos + (y * cos - x * sin >> 5); gfxPolyList[gfxVertexSize].colour.r = 0xFF; gfxPolyList[gfxVertexSize].colour.g = 0xFF; gfxPolyList[gfxVertexSize].colour.b = 0xFF; gfxPolyList[gfxVertexSize].colour.a = 0xFF; gfxPolyList[gfxVertexSize].u = (surface->texStartX + sprX + width); gfxPolyList[gfxVertexSize].v = gfxPolyList[gfxVertexSize - 1].v; gfxVertexSize++; x = pivotX; y = height - pivotY; gfxPolyList[gfxVertexSize].x = XPos + (x * cos + y * sin >> 5); gfxPolyList[gfxVertexSize].y = YPos + (y * cos - x * sin >> 5); gfxPolyList[gfxVertexSize].colour.r = 0xFF; gfxPolyList[gfxVertexSize].colour.g = 0xFF; gfxPolyList[gfxVertexSize].colour.b = 0xFF; gfxPolyList[gfxVertexSize].colour.a = 0xFF; gfxPolyList[gfxVertexSize].u = gfxPolyList[gfxVertexSize - 2].u; gfxPolyList[gfxVertexSize].v = (surface->texStartY + sprY + height); gfxVertexSize++; x = pivotX - width; y = height - pivotY; gfxPolyList[gfxVertexSize].x = XPos + (x * cos + y * sin >> 5); gfxPolyList[gfxVertexSize].y = YPos + (y * cos - x * sin >> 5); gfxPolyList[gfxVertexSize].colour.r = 0xFF; gfxPolyList[gfxVertexSize].colour.g = 0xFF; gfxPolyList[gfxVertexSize].colour.b = 0xFF; gfxPolyList[gfxVertexSize].colour.a = 0xFF; gfxPolyList[gfxVertexSize].u = gfxPolyList[gfxVertexSize - 2].u; gfxPolyList[gfxVertexSize].v = gfxPolyList[gfxVertexSize - 1].v; gfxVertexSize++; gfxIndexSize += 6; } } #endif } void DrawSpriteRotozoom(int direction, int XPos, int YPos, int pivotX, int pivotY, int sprX, int sprY, int width, int height, int rotation, int scale, int sheetID) { #if RETRO_SOFTWARE_RENDER if (scale == 0) return; int sprXPos = (pivotX + sprX) << 9; int sprYPos = (pivotY + sprY) << 9; int fullwidth = width + sprX; int fullheight = height + sprY; int angle = rotation & 0x1FF; if (angle < 0) angle += 0x200; if (angle) angle = 0x200 - angle; int sine = scale * sinVal512[angle] >> 9; int cosine = scale * cosVal512[angle] >> 9; int xPositions[4]; int yPositions[4]; if (direction == FLIP_X) { xPositions[0] = XPos + ((sine * (-pivotY - 2) + cosine * (pivotX + 2)) >> 9); yPositions[0] = YPos + ((cosine * (-pivotY - 2) - sine * (pivotX + 2)) >> 9); xPositions[1] = XPos + ((sine * (-pivotY - 2) + cosine * (pivotX - width - 2)) >> 9); yPositions[1] = YPos + ((cosine * (-pivotY - 2) - sine * (pivotX - width - 2)) >> 9); xPositions[2] = XPos + ((sine * (height - pivotY + 2) + cosine * (pivotX + 2)) >> 9); yPositions[2] = YPos + ((cosine * (height - pivotY + 2) - sine * (pivotX + 2)) >> 9); int a = pivotX - width - 2; int b = height - pivotY + 2; xPositions[3] = XPos + ((sine * b + cosine * a) >> 9); yPositions[3] = YPos + ((cosine * b - sine * a) >> 9); } else { xPositions[0] = XPos + ((sine * (-pivotY - 2) + cosine * (-pivotX - 2)) >> 9); yPositions[0] = YPos + ((cosine * (-pivotY - 2) - sine * (-pivotX - 2)) >> 9); xPositions[1] = XPos + ((sine * (-pivotY - 2) + cosine * (width - pivotX + 2)) >> 9); yPositions[1] = YPos + ((cosine * (-pivotY - 2) - sine * (width - pivotX + 2)) >> 9); xPositions[2] = XPos + ((sine * (height - pivotY + 2) + cosine * (-pivotX - 2)) >> 9); yPositions[2] = YPos + ((cosine * (height - pivotY + 2) - sine * (-pivotX - 2)) >> 9); int a = width - pivotX + 2; int b = height - pivotY + 2; xPositions[3] = XPos + ((sine * b + cosine * a) >> 9); yPositions[3] = YPos + ((cosine * b - sine * a) >> 9); } int truescale = (signed int)(float)((float)(512.0 / (float)scale) * 512.0); sine = truescale * sinVal512[angle] >> 9; cosine = truescale * cosVal512[angle] >> 9; int left = SCREEN_XSIZE; for (int i = 0; i < 4; ++i) { if (xPositions[i] < left) left = xPositions[i]; } if (left < 0) left = 0; int right = 0; for (int i = 0; i < 4; ++i) { if (xPositions[i] > right) right = xPositions[i]; } if (right > SCREEN_XSIZE) right = SCREEN_XSIZE; int maxX = right - left; int top = SCREEN_YSIZE; for (int i = 0; i < 4; ++i) { if (yPositions[i] < top) top = yPositions[i]; } if (top < 0) top = 0; int bottom = 0; for (int i = 0; i < 4; ++i) { if (yPositions[i] > bottom) bottom = yPositions[i]; } if (bottom > SCREEN_YSIZE) bottom = SCREEN_YSIZE; int maxY = bottom - top; if (maxX <= 0 || maxY <= 0) return; GFXSurface *surface = &gfxSurface[sheetID]; int pitch = SCREEN_XSIZE - maxX; int lineSize = surface->widthShift; ushort *frameBufferPtr = &Engine.frameBuffer[left + SCREEN_XSIZE * top]; byte *lineBuffer = &gfxLineBuffer[top]; int startX = left - XPos; int startY = top - YPos; int shiftPivot = (sprX << 9) - 1; fullwidth <<= 9; int shiftheight = (sprY << 9) - 1; fullheight <<= 9; byte *gfxData = &graphicData[surface->dataPosition]; if (cosine < 0 || sine < 0) sprYPos += sine + cosine; if (direction == FLIP_X) { int drawX = sprXPos - (cosine * startX - sine * startY) - (truescale >> 1); int drawY = cosine * startY + sprYPos + sine * startX; while (maxY--) { activePalette = fullPalette[*lineBuffer]; activePalette32 = fullPalette32[*lineBuffer]; lineBuffer++; int finalX = drawX; int finalY = drawY; int w = maxX; while (w--) { if (finalX > shiftPivot && finalX < fullwidth && finalY > shiftheight && finalY < fullheight) { byte index = gfxData[(finalY >> 9 << lineSize) + (finalX >> 9)]; if (index > 0) *frameBufferPtr = activePalette[index]; } ++frameBufferPtr; finalX -= cosine; finalY += sine; } drawX += sine; drawY += cosine; frameBufferPtr += pitch; } } else { int drawX = sprXPos + cosine * startX - sine * startY; int drawY = cosine * startY + sprYPos + sine * startX; while (maxY--) { activePalette = fullPalette[*lineBuffer]; activePalette32 = fullPalette32[*lineBuffer]; lineBuffer++; int finalX = drawX; int finalY = drawY; int w = maxX; while (w--) { if (finalX > shiftPivot && finalX < fullwidth && finalY > shiftheight && finalY < fullheight) { byte index = gfxData[(finalY >> 9 << lineSize) + (finalX >> 9)]; if (index > 0) *frameBufferPtr = activePalette[index]; } ++frameBufferPtr; finalX += cosine; finalY += sine; } drawX -= sine; drawY += cosine; frameBufferPtr += pitch; } } #endif #if RETRO_HARDWARE_RENDER GFXSurface *surface = &gfxSurface[sheetID]; XPos <<= 4; YPos <<= 4; rotation -= rotation >> 9 << 9; if (rotation < 0) rotation += 0x200; if (rotation != 0) rotation = 0x200 - rotation; int sin = sinVal512[rotation] * scale >> 9; int cos = cosVal512[rotation] * scale >> 9; if (surface->texStartX > -1 && gfxVertexSize < VERTEX_LIMIT && XPos > -8192 && XPos < 13952 && YPos > -8192 && YPos < 12032) { if (direction == FLIP_NONE) { int x = -pivotX; int y = -pivotY; gfxPolyList[gfxVertexSize].x = XPos + (x * cos + y * sin >> 5); gfxPolyList[gfxVertexSize].y = YPos + (y * cos - x * sin >> 5); gfxPolyList[gfxVertexSize].colour.r = 0xFF; gfxPolyList[gfxVertexSize].colour.g = 0xFF; gfxPolyList[gfxVertexSize].colour.b = 0xFF; gfxPolyList[gfxVertexSize].colour.a = 0xFF; gfxPolyList[gfxVertexSize].u = (surface->texStartX + sprX); gfxPolyList[gfxVertexSize].v = (surface->texStartY + sprY); gfxVertexSize++; x = width - pivotX; y = -pivotY; gfxPolyList[gfxVertexSize].x = XPos + (x * cos + y * sin >> 5); gfxPolyList[gfxVertexSize].y = YPos + (y * cos - x * sin >> 5); gfxPolyList[gfxVertexSize].colour.r = 0xFF; gfxPolyList[gfxVertexSize].colour.g = 0xFF; gfxPolyList[gfxVertexSize].colour.b = 0xFF; gfxPolyList[gfxVertexSize].colour.a = 0xFF; gfxPolyList[gfxVertexSize].u = (surface->texStartX + sprX + width); gfxPolyList[gfxVertexSize].v = gfxPolyList[gfxVertexSize - 1].v; gfxVertexSize++; x = -pivotX; y = height - pivotY; gfxPolyList[gfxVertexSize].x = XPos + (x * cos + y * sin >> 5); gfxPolyList[gfxVertexSize].y = YPos + (y * cos - x * sin >> 5); gfxPolyList[gfxVertexSize].colour.r = 0xFF; gfxPolyList[gfxVertexSize].colour.g = 0xFF; gfxPolyList[gfxVertexSize].colour.b = 0xFF; gfxPolyList[gfxVertexSize].colour.a = 0xFF; gfxPolyList[gfxVertexSize].u = gfxPolyList[gfxVertexSize - 2].u; gfxPolyList[gfxVertexSize].v = (surface->texStartY + sprY + height); gfxVertexSize++; x = width - pivotX; y = height - pivotY; gfxPolyList[gfxVertexSize].x = XPos + (x * cos + y * sin >> 5); gfxPolyList[gfxVertexSize].y = YPos + (y * cos - x * sin >> 5); gfxPolyList[gfxVertexSize].colour.r = 0xFF; gfxPolyList[gfxVertexSize].colour.g = 0xFF; gfxPolyList[gfxVertexSize].colour.b = 0xFF; gfxPolyList[gfxVertexSize].colour.a = 0xFF; gfxPolyList[gfxVertexSize].u = gfxPolyList[gfxVertexSize - 2].u; gfxPolyList[gfxVertexSize].v = gfxPolyList[gfxVertexSize - 1].v; gfxVertexSize++; gfxIndexSize += 6; } else { int x = pivotX; int y = -pivotY; gfxPolyList[gfxVertexSize].x = XPos + (x * cos + y * sin >> 5); gfxPolyList[gfxVertexSize].y = YPos + (y * cos - x * sin >> 5); gfxPolyList[gfxVertexSize].colour.r = 0xFF; gfxPolyList[gfxVertexSize].colour.g = 0xFF; gfxPolyList[gfxVertexSize].colour.b = 0xFF; gfxPolyList[gfxVertexSize].colour.a = 0xFF; gfxPolyList[gfxVertexSize].u = (surface->texStartX + sprX); gfxPolyList[gfxVertexSize].v = (surface->texStartY + sprY); gfxVertexSize++; x = pivotX - width; y = -pivotY; gfxPolyList[gfxVertexSize].x = XPos + (x * cos + y * sin >> 5); gfxPolyList[gfxVertexSize].y = YPos + (y * cos - x * sin >> 5); gfxPolyList[gfxVertexSize].colour.r = 0xFF; gfxPolyList[gfxVertexSize].colour.g = 0xFF; gfxPolyList[gfxVertexSize].colour.b = 0xFF; gfxPolyList[gfxVertexSize].colour.a = 0xFF; gfxPolyList[gfxVertexSize].u = (surface->texStartX + sprX + width); gfxPolyList[gfxVertexSize].v = gfxPolyList[gfxVertexSize - 1].v; gfxVertexSize++; x = pivotX; y = height - pivotY; gfxPolyList[gfxVertexSize].x = XPos + (x * cos + y * sin >> 5); gfxPolyList[gfxVertexSize].y = YPos + (y * cos - x * sin >> 5); gfxPolyList[gfxVertexSize].colour.r = 0xFF; gfxPolyList[gfxVertexSize].colour.g = 0xFF; gfxPolyList[gfxVertexSize].colour.b = 0xFF; gfxPolyList[gfxVertexSize].colour.a = 0xFF; gfxPolyList[gfxVertexSize].u = gfxPolyList[gfxVertexSize - 2].u; gfxPolyList[gfxVertexSize].v = (surface->texStartY + sprY + height); gfxVertexSize++; x = pivotX - width; y = height - pivotY; gfxPolyList[gfxVertexSize].x = XPos + (x * cos + y * sin >> 5); gfxPolyList[gfxVertexSize].y = YPos + (y * cos - x * sin >> 5); gfxPolyList[gfxVertexSize].colour.r = 0xFF; gfxPolyList[gfxVertexSize].colour.g = 0xFF; gfxPolyList[gfxVertexSize].colour.b = 0xFF; gfxPolyList[gfxVertexSize].colour.a = 0xFF; gfxPolyList[gfxVertexSize].u = gfxPolyList[gfxVertexSize - 2].u; gfxPolyList[gfxVertexSize].v = gfxPolyList[gfxVertexSize - 1].v; gfxVertexSize++; gfxIndexSize += 6; } } #endif } void DrawBlendedSprite(int XPos, int YPos, int width, int height, int sprX, int sprY, int sheetID) { #if RETRO_SOFTWARE_RENDER if (width + XPos > SCREEN_XSIZE) width = SCREEN_XSIZE - XPos; if (XPos < 0) { sprX -= XPos; width += XPos; XPos = 0; } if (height + YPos > SCREEN_YSIZE) height = SCREEN_YSIZE - YPos; if (YPos < 0) { sprY -= YPos; height += YPos; YPos = 0; } if (width <= 0 || height <= 0) return; GFXSurface *surface = &gfxSurface[sheetID]; int pitch = SCREEN_XSIZE - width; int gfxPitch = surface->width - width; byte *lineBuffer = &gfxLineBuffer[YPos]; byte *gfxData = &graphicData[sprX + surface->width * sprY + surface->dataPosition]; ushort *frameBufferPtr = &Engine.frameBuffer[XPos + SCREEN_XSIZE * YPos]; while (height--) { activePalette = fullPalette[*lineBuffer]; activePalette32 = fullPalette32[*lineBuffer]; lineBuffer++; int w = width; while (w--) { if (*gfxData > 0) *frameBufferPtr = ((activePalette[*gfxData] & 0xF7DE) >> 1) + ((*frameBufferPtr & 0xF7DE) >> 1); ++gfxData; ++frameBufferPtr; } frameBufferPtr += pitch; gfxData += gfxPitch; } #endif #if RETRO_HARDWARE_RENDER GFXSurface *surface = &gfxSurface[sheetID]; if (surface->texStartX > -1 && gfxVertexSize < VERTEX_LIMIT && XPos > -512 && XPos < 872 && YPos > -512 && YPos < 752) { gfxPolyList[gfxVertexSize].x = XPos << 4; gfxPolyList[gfxVertexSize].y = YPos << 4; gfxPolyList[gfxVertexSize].colour.r = 0xFF; gfxPolyList[gfxVertexSize].colour.g = 0xFF; gfxPolyList[gfxVertexSize].colour.b = 0xFF; gfxPolyList[gfxVertexSize].colour.a = 0x80; gfxPolyList[gfxVertexSize].u = (surface->texStartX + sprX); gfxPolyList[gfxVertexSize].v = (surface->texStartY + sprY); gfxVertexSize++; gfxPolyList[gfxVertexSize].x = XPos + width << 4; gfxPolyList[gfxVertexSize].y = YPos << 4; gfxPolyList[gfxVertexSize].colour.r = 0xFF; gfxPolyList[gfxVertexSize].colour.g = 0xFF; gfxPolyList[gfxVertexSize].colour.b = 0xFF; gfxPolyList[gfxVertexSize].colour.a = 0x80; gfxPolyList[gfxVertexSize].u = (surface->texStartX + sprX + width); gfxPolyList[gfxVertexSize].v = gfxPolyList[gfxVertexSize - 1].v; gfxVertexSize++; gfxPolyList[gfxVertexSize].x = XPos << 4; gfxPolyList[gfxVertexSize].y = YPos + height << 4; gfxPolyList[gfxVertexSize].colour.r = 0xFF; gfxPolyList[gfxVertexSize].colour.g = 0xFF; gfxPolyList[gfxVertexSize].colour.b = 0xFF; gfxPolyList[gfxVertexSize].colour.a = 0x80; gfxPolyList[gfxVertexSize].u = gfxPolyList[gfxVertexSize - 2].u; gfxPolyList[gfxVertexSize].v = (surface->texStartY + sprY + height); gfxVertexSize++; gfxPolyList[gfxVertexSize].x = gfxPolyList[gfxVertexSize - 2].x; gfxPolyList[gfxVertexSize].y = gfxPolyList[gfxVertexSize - 1].y; gfxPolyList[gfxVertexSize].colour.r = 0xFF; gfxPolyList[gfxVertexSize].colour.g = 0xFF; gfxPolyList[gfxVertexSize].colour.b = 0xFF; gfxPolyList[gfxVertexSize].colour.a = 0x80; gfxPolyList[gfxVertexSize].u = gfxPolyList[gfxVertexSize - 2].u; gfxPolyList[gfxVertexSize].v = gfxPolyList[gfxVertexSize - 1].v; gfxVertexSize++; gfxIndexSize += 6; } #endif } void DrawAlphaBlendedSprite(int XPos, int YPos, int width, int height, int sprX, int sprY, int alpha, int sheetID) { if (alpha > 0xFF) alpha = 0xFF; #if RETRO_SOFTWARE_RENDER if (width + XPos > SCREEN_XSIZE) width = SCREEN_XSIZE - XPos; if (XPos < 0) { sprX -= XPos; width += XPos; XPos = 0; } if (height + YPos > SCREEN_YSIZE) height = SCREEN_YSIZE - YPos; if (YPos < 0) { sprY -= YPos; height += YPos; YPos = 0; } if (width <= 0 || height <= 0 || alpha <= 0) return; GFXSurface *surface = &gfxSurface[sheetID]; int pitch = SCREEN_XSIZE - width; int gfxPitch = surface->width - width; byte *lineBuffer = &gfxLineBuffer[YPos]; byte *gfxData = &graphicData[sprX + surface->width * sprY + surface->dataPosition]; ushort *frameBufferPtr = &Engine.frameBuffer[XPos + SCREEN_XSIZE * YPos]; if (alpha == 0xFF) { while (height--) { activePalette = fullPalette[*lineBuffer]; activePalette32 = fullPalette32[*lineBuffer]; lineBuffer++; int w = width; while (w--) { if (*gfxData > 0) *frameBufferPtr = activePalette[*gfxData]; ++gfxData; ++frameBufferPtr; } frameBufferPtr += pitch; gfxData += gfxPitch; } } else { while (height--) { activePalette = fullPalette[*lineBuffer]; activePalette32 = fullPalette32[*lineBuffer]; lineBuffer++; int w = width; while (w--) { if (*gfxData > 0) { ushort colour = activePalette[*gfxData]; ushort *blendTablePtrA = &blendLookupTable[BLENDTABLE_XSIZE * ((BLENDTABLE_YSIZE - 1) - alpha)]; ushort *blendTablePtrB = &blendLookupTable[BLENDTABLE_XSIZE * alpha]; *frameBufferPtr = (blendTablePtrA[*frameBufferPtr & (BLENDTABLE_XSIZE - 1)] + blendTablePtrB[colour & (BLENDTABLE_XSIZE - 1)]) | ((blendTablePtrA[(*frameBufferPtr & 0x7E0) >> 6] + blendTablePtrB[(colour & 0x7E0) >> 6]) << 6) | ((blendTablePtrA[(*frameBufferPtr & 0xF800) >> 11] + blendTablePtrB[(colour & 0xF800) >> 11]) << 11); } ++gfxData; ++frameBufferPtr; } frameBufferPtr += pitch; gfxData += gfxPitch; } } #endif #if RETRO_HARDWARE_RENDER GFXSurface *surface = &gfxSurface[sheetID]; if (surface->texStartX > -1 && gfxVertexSize < VERTEX_LIMIT && XPos > -512 && XPos < 872 && YPos > -512 && YPos < 752) { gfxPolyList[gfxVertexSize].x = XPos << 4; gfxPolyList[gfxVertexSize].y = YPos << 4; gfxPolyList[gfxVertexSize].colour.r = 0xFF; gfxPolyList[gfxVertexSize].colour.g = 0xFF; gfxPolyList[gfxVertexSize].colour.b = 0xFF; gfxPolyList[gfxVertexSize].colour.a = alpha; gfxPolyList[gfxVertexSize].u = (surface->texStartX + sprX); gfxPolyList[gfxVertexSize].v = (surface->texStartY + sprY); gfxVertexSize++; gfxPolyList[gfxVertexSize].x = XPos + width << 4; gfxPolyList[gfxVertexSize].y = YPos << 4; gfxPolyList[gfxVertexSize].colour.r = 0xFF; gfxPolyList[gfxVertexSize].colour.g = 0xFF; gfxPolyList[gfxVertexSize].colour.b = 0xFF; gfxPolyList[gfxVertexSize].colour.a = alpha; gfxPolyList[gfxVertexSize].u = (surface->texStartX + sprX + width); gfxPolyList[gfxVertexSize].v = gfxPolyList[gfxVertexSize - 1].v; gfxVertexSize++; gfxPolyList[gfxVertexSize].x = XPos << 4; gfxPolyList[gfxVertexSize].y = YPos + height << 4; gfxPolyList[gfxVertexSize].colour.r = 0xFF; gfxPolyList[gfxVertexSize].colour.g = 0xFF; gfxPolyList[gfxVertexSize].colour.b = 0xFF; gfxPolyList[gfxVertexSize].colour.a = alpha; gfxPolyList[gfxVertexSize].u = gfxPolyList[gfxVertexSize - 2].u; gfxPolyList[gfxVertexSize].v = (surface->texStartY + sprY + height); gfxVertexSize++; gfxPolyList[gfxVertexSize].x = gfxPolyList[gfxVertexSize - 2].x; gfxPolyList[gfxVertexSize].y = gfxPolyList[gfxVertexSize - 1].y; gfxPolyList[gfxVertexSize].colour.r = 0xFF; gfxPolyList[gfxVertexSize].colour.g = 0xFF; gfxPolyList[gfxVertexSize].colour.b = 0xFF; gfxPolyList[gfxVertexSize].colour.a = alpha; gfxPolyList[gfxVertexSize].u = gfxPolyList[gfxVertexSize - 2].u; gfxPolyList[gfxVertexSize].v = gfxPolyList[gfxVertexSize - 1].v; gfxVertexSize++; gfxIndexSize += 6; } #endif } void DrawAdditiveBlendedSprite(int XPos, int YPos, int width, int height, int sprX, int sprY, int alpha, int sheetID) { if (alpha > 0xFF) alpha = 0xFF; #if RETRO_SOFTWARE_RENDER if (width + XPos > SCREEN_XSIZE) width = SCREEN_XSIZE - XPos; if (XPos < 0) { sprX -= XPos; width += XPos; XPos = 0; } if (height + YPos > SCREEN_YSIZE) height = SCREEN_YSIZE - YPos; if (YPos < 0) { sprY -= YPos; height += YPos; YPos = 0; } if (width <= 0 || height <= 0 || alpha <= 0) return; ushort *blendTablePtr = &blendLookupTable[BLENDTABLE_XSIZE * alpha]; GFXSurface *surface = &gfxSurface[sheetID]; int pitch = SCREEN_XSIZE - width; int gfxPitch = surface->width - width; byte *lineBuffer = &gfxLineBuffer[YPos]; byte *gfxData = &graphicData[sprX + surface->width * sprY + surface->dataPosition]; ushort *frameBufferPtr = &Engine.frameBuffer[XPos + SCREEN_XSIZE * YPos]; while (height--) { activePalette = fullPalette[*lineBuffer]; activePalette32 = fullPalette32[*lineBuffer]; lineBuffer++; int w = width; while (w--) { if (*gfxData > 0) { ushort colour = activePalette[*gfxData]; int v20 = 0; int v21 = 0; int finalColour = 0; if ((blendTablePtr[(colour & 0xF800) >> 11] << 11) + (*frameBufferPtr & 0xF800) <= 0xF800) v20 = (blendTablePtr[(colour & 0xF800) >> 11] << 11) + (*frameBufferPtr & 0xF800); else v20 = 0xF800; int v12 = (blendTablePtr[(colour & 0x7E0) >> 6] << 6) + (*frameBufferPtr & 0x7E0); if (v12 <= 0x7E0) v21 = v12 | v20; else v21 = v20 | 0x7E0; int v13 = blendTablePtr[colour & (BLENDTABLE_XSIZE - 1)] + (*frameBufferPtr & 0x1F); if (v13 <= 0x1F) finalColour = v13 | v21; else finalColour = v21 | 0x1F; *frameBufferPtr = finalColour; } ++gfxData; ++frameBufferPtr; } frameBufferPtr += pitch; gfxData += gfxPitch; } #endif #if RETRO_HARDWARE_RENDER GFXSurface *surface = &gfxSurface[sheetID]; if (surface->texStartX > -1 && gfxVertexSize < VERTEX_LIMIT && XPos > -512 && XPos < 872 && YPos > -512 && YPos < 752) { gfxPolyList[gfxVertexSize].x = XPos << 4; gfxPolyList[gfxVertexSize].y = YPos << 4; gfxPolyList[gfxVertexSize].colour.r = 0xFF; gfxPolyList[gfxVertexSize].colour.g = 0xFF; gfxPolyList[gfxVertexSize].colour.b = 0xFF; gfxPolyList[gfxVertexSize].colour.a = alpha; gfxPolyList[gfxVertexSize].u = (surface->texStartX + sprX); gfxPolyList[gfxVertexSize].v = (surface->texStartY + sprY); gfxVertexSize++; gfxPolyList[gfxVertexSize].x = XPos + width << 4; gfxPolyList[gfxVertexSize].y = YPos << 4; gfxPolyList[gfxVertexSize].colour.r = 0xFF; gfxPolyList[gfxVertexSize].colour.g = 0xFF; gfxPolyList[gfxVertexSize].colour.b = 0xFF; gfxPolyList[gfxVertexSize].colour.a = alpha; gfxPolyList[gfxVertexSize].u = (surface->texStartX + sprX + width); gfxPolyList[gfxVertexSize].v = gfxPolyList[gfxVertexSize - 1].v; gfxVertexSize++; gfxPolyList[gfxVertexSize].x = XPos << 4; gfxPolyList[gfxVertexSize].y = YPos + height << 4; gfxPolyList[gfxVertexSize].colour.r = 0xFF; gfxPolyList[gfxVertexSize].colour.g = 0xFF; gfxPolyList[gfxVertexSize].colour.b = 0xFF; gfxPolyList[gfxVertexSize].colour.a = alpha; gfxPolyList[gfxVertexSize].u = gfxPolyList[gfxVertexSize - 2].u; gfxPolyList[gfxVertexSize].v = (surface->texStartY + sprY + height); gfxVertexSize++; gfxPolyList[gfxVertexSize].x = gfxPolyList[gfxVertexSize - 2].x; gfxPolyList[gfxVertexSize].y = gfxPolyList[gfxVertexSize - 1].y; gfxPolyList[gfxVertexSize].colour.r = 0xFF; gfxPolyList[gfxVertexSize].colour.g = 0xFF; gfxPolyList[gfxVertexSize].colour.b = 0xFF; gfxPolyList[gfxVertexSize].colour.a = alpha; gfxPolyList[gfxVertexSize].u = gfxPolyList[gfxVertexSize - 2].u; gfxPolyList[gfxVertexSize].v = gfxPolyList[gfxVertexSize - 1].v; gfxVertexSize++; gfxIndexSize += 6; } #endif } void DrawSubtractiveBlendedSprite(int XPos, int YPos, int width, int height, int sprX, int sprY, int alpha, int sheetID) { if (alpha > 0xFF) alpha = 0xFF; #if RETRO_SOFTWARE_RENDER if (width + XPos > SCREEN_XSIZE) width = SCREEN_XSIZE - XPos; if (XPos < 0) { sprX -= XPos; width += XPos; XPos = 0; } if (height + YPos > SCREEN_YSIZE) height = SCREEN_YSIZE - YPos; if (YPos < 0) { sprY -= YPos; height += YPos; YPos = 0; } if (width <= 0 || height <= 0 || alpha <= 0) return; ushort *subBlendTable = &subtractLookupTable[BLENDTABLE_XSIZE * alpha]; GFXSurface *surface = &gfxSurface[sheetID]; int pitch = SCREEN_XSIZE - width; int gfxPitch = surface->width - width; byte *lineBuffer = &gfxLineBuffer[YPos]; byte *gfxData = &graphicData[sprX + surface->width * sprY + surface->dataPosition]; ushort *frameBufferPtr = &Engine.frameBuffer[XPos + SCREEN_XSIZE * YPos]; while (height--) { activePalette = fullPalette[*lineBuffer]; activePalette32 = fullPalette32[*lineBuffer]; lineBuffer++; int w = width; while (w--) { if (*gfxData > 0) { ushort colour = activePalette[*gfxData]; ushort finalColour = 0; if ((*frameBufferPtr & 0xF800) - (subBlendTable[(colour & 0xF800) >> 11] << 11) <= 0) finalColour = 0; else finalColour = (*frameBufferPtr & 0xF800) - (subBlendTable[(colour & 0xF800) >> 11] << 11); int v12 = (*frameBufferPtr & 0x7E0) - (subBlendTable[(colour & 0x7E0) >> 6] << 6); if (v12 > 0) finalColour |= v12; int v13 = (*frameBufferPtr & 0x1F) - subBlendTable[colour & 0x1F]; if (v13 > 0) finalColour |= v13; *frameBufferPtr = finalColour; } ++gfxData; ++frameBufferPtr; } frameBufferPtr += pitch; gfxData += gfxPitch; } #endif #if RETRO_HARDWARE_RENDER GFXSurface *surface = &gfxSurface[sheetID]; if (surface->texStartX > -1 && gfxVertexSize < VERTEX_LIMIT && XPos > -512 && XPos < 872 && YPos > -512 && YPos < 752) { gfxPolyList[gfxVertexSize].x = XPos << 4; gfxPolyList[gfxVertexSize].y = YPos << 4; gfxPolyList[gfxVertexSize].colour.r = 0xFF; gfxPolyList[gfxVertexSize].colour.g = 0xFF; gfxPolyList[gfxVertexSize].colour.b = 0xFF; gfxPolyList[gfxVertexSize].colour.a = alpha; gfxPolyList[gfxVertexSize].u = (surface->texStartX + sprX); gfxPolyList[gfxVertexSize].v = (surface->texStartY + sprY); gfxVertexSize++; gfxPolyList[gfxVertexSize].x = XPos + width << 4; gfxPolyList[gfxVertexSize].y = YPos << 4; gfxPolyList[gfxVertexSize].colour.r = 0xFF; gfxPolyList[gfxVertexSize].colour.g = 0xFF; gfxPolyList[gfxVertexSize].colour.b = 0xFF; gfxPolyList[gfxVertexSize].colour.a = alpha; gfxPolyList[gfxVertexSize].u = (surface->texStartX + sprX + width); gfxPolyList[gfxVertexSize].v = gfxPolyList[gfxVertexSize - 1].v; gfxVertexSize++; gfxPolyList[gfxVertexSize].x = XPos << 4; gfxPolyList[gfxVertexSize].y = YPos + height << 4; gfxPolyList[gfxVertexSize].colour.r = 0xFF; gfxPolyList[gfxVertexSize].colour.g = 0xFF; gfxPolyList[gfxVertexSize].colour.b = 0xFF; gfxPolyList[gfxVertexSize].colour.a = alpha; gfxPolyList[gfxVertexSize].u = gfxPolyList[gfxVertexSize - 2].u; gfxPolyList[gfxVertexSize].v = (surface->texStartY + sprY + height); gfxVertexSize++; gfxPolyList[gfxVertexSize].x = gfxPolyList[gfxVertexSize - 2].x; gfxPolyList[gfxVertexSize].y = gfxPolyList[gfxVertexSize - 1].y; gfxPolyList[gfxVertexSize].colour.r = 0xFF; gfxPolyList[gfxVertexSize].colour.g = 0xFF; gfxPolyList[gfxVertexSize].colour.b = 0xFF; gfxPolyList[gfxVertexSize].colour.a = alpha; gfxPolyList[gfxVertexSize].u = gfxPolyList[gfxVertexSize - 2].u; gfxPolyList[gfxVertexSize].v = gfxPolyList[gfxVertexSize - 1].v; gfxVertexSize++; gfxIndexSize += 6; } #endif } void DrawObjectAnimation(void *objScr, void *ent, int XPos, int YPos) { ObjectScript *objectScript = (ObjectScript *)objScr; Entity *entity = (Entity *)ent; SpriteAnimation *sprAnim = &animationList[objectScript->animFile->aniListOffset + entity->animation]; SpriteFrame *frame = &animFrames[sprAnim->frameListOffset + entity->frame]; int rotation = 0; switch (sprAnim->rotationFlag) { case ROTFLAG_NONE: switch (entity->direction) { case FLIP_NONE: DrawSpriteFlipped(frame->pivotX + XPos, frame->pivotY + YPos, frame->width, frame->height, frame->sprX, frame->sprY, FLIP_NONE, frame->sheetID); break; case FLIP_X: DrawSpriteFlipped(XPos - frame->width - frame->pivotX, frame->pivotY + YPos, frame->width, frame->height, frame->sprX, frame->sprY, FLIP_X, frame->sheetID); break; case FLIP_Y: DrawSpriteFlipped(frame->pivotX + XPos, YPos - frame->height - frame->pivotY, frame->width, frame->height, frame->sprX, frame->sprY, FLIP_Y, frame->sheetID); break; case FLIP_XY: DrawSpriteFlipped(XPos - frame->width - frame->pivotX, YPos - frame->height - frame->pivotY, frame->width, frame->height, frame->sprX, frame->sprY, FLIP_XY, frame->sheetID); break; default: break; } break; case ROTFLAG_FULL: DrawSpriteRotated(entity->direction, XPos, YPos, -frame->pivotX, -frame->pivotY, frame->sprX, frame->sprY, frame->width, frame->height, entity->rotation, frame->sheetID); break; case ROTFLAG_45DEG: if (entity->rotation >= 0x100) DrawSpriteRotated(entity->direction, XPos, YPos, -frame->pivotX, -frame->pivotY, frame->sprX, frame->sprY, frame->width, frame->height, 0x200 - ((0x214 - entity->rotation) >> 6 << 6), frame->sheetID); else DrawSpriteRotated(entity->direction, XPos, YPos, -frame->pivotX, -frame->pivotY, frame->sprX, frame->sprY, frame->width, frame->height, (entity->rotation + 20) >> 6 << 6, frame->sheetID); break; case ROTFLAG_STATICFRAMES: { if (entity->rotation >= 0x100) rotation = 8 - ((532 - entity->rotation) >> 6); else rotation = (entity->rotation + 20) >> 6; int frameID = entity->frame; switch (rotation) { case 0: // 0 deg case 8: // 360 deg rotation = 0x00; break; case 1: // 45 deg frameID += sprAnim->frameCount; if (entity->direction) rotation = 0; else rotation = 0x80; break; case 2: // 90 deg rotation = 0x80; break; case 3: // 135 deg frameID += sprAnim->frameCount; if (entity->direction) rotation = 0x80; else rotation = 0x100; break; case 4: // 180 deg rotation = 0x100; break; case 5: // 225 deg frameID += sprAnim->frameCount; if (entity->direction) rotation = 0x100; else rotation = 384; break; case 6: // 270 deg rotation = 384; break; case 7: // 315 deg frameID += sprAnim->frameCount; if (entity->direction) rotation = 384; else rotation = 0; break; default: break; } frame = &animFrames[sprAnim->frameListOffset + frameID]; DrawSpriteRotated(entity->direction, XPos, YPos, -frame->pivotX, -frame->pivotY, frame->sprX, frame->sprY, frame->width, frame->height, rotation, frame->sheetID); // DrawSpriteRotozoom(entity->direction, XPos, YPos, -frame->pivotX, -frame->pivotY, frame->sprX, frame->sprY, frame->width, // frame->height, // rotation, entity->scale, frame->sheetID); break; } default: break; } } void DrawFace(void *v, uint colour) { Vertex *verts = (Vertex *)v; int alpha = (colour & 0x7F000000) >> 23; if (alpha < 1) return; if (alpha > 0xFF) alpha = 0xFF; if (verts[0].x < 0 && verts[1].x < 0 && verts[2].x < 0 && verts[3].x < 0) return; if (verts[0].x > SCREEN_XSIZE && verts[1].x > SCREEN_XSIZE && verts[2].x > SCREEN_XSIZE && verts[3].x > SCREEN_XSIZE) return; if (verts[0].y < 0 && verts[1].y < 0 && verts[2].y < 0 && verts[3].y < 0) return; if (verts[0].y > SCREEN_YSIZE && verts[1].y > SCREEN_YSIZE && verts[2].y > SCREEN_YSIZE && verts[3].y > SCREEN_YSIZE) return; if (verts[0].x == verts[1].x && verts[1].x == verts[2].x && verts[2].x == verts[3].x) return; if (verts[0].y == verts[1].y && verts[1].y == verts[2].y && verts[2].y == verts[3].y) return; #if RETRO_SOFTWARE_RENDER int vertexA = 0; int vertexB = 1; int vertexC = 2; int vertexD = 3; if (verts[1].y < verts[0].y) { vertexA = 1; vertexB = 0; } if (verts[2].y < verts[vertexA].y) { int temp = vertexA; vertexA = 2; vertexC = temp; } if (verts[3].y < verts[vertexA].y) { int temp = vertexA; vertexA = 3; vertexD = temp; } if (verts[vertexC].y < verts[vertexB].y) { int temp = vertexB; vertexB = vertexC; vertexC = temp; } if (verts[vertexD].y < verts[vertexB].y) { int temp = vertexB; vertexB = vertexD; vertexD = temp; } if (verts[vertexD].y < verts[vertexC].y) { int temp = vertexC; vertexC = vertexD; vertexD = temp; } int faceTop = verts[vertexA].y; int faceBottom = verts[vertexD].y; if (faceTop < 0) faceTop = 0; if (faceBottom > SCREEN_YSIZE) faceBottom = SCREEN_YSIZE; for (int i = faceTop; i < faceBottom; ++i) { faceLineStart[i] = 100000; faceLineEnd[i] = -100000; } processScanEdge(&verts[vertexA], &verts[vertexB]); processScanEdge(&verts[vertexA], &verts[vertexC]); processScanEdge(&verts[vertexA], &verts[vertexD]); processScanEdge(&verts[vertexB], &verts[vertexC]); processScanEdge(&verts[vertexC], &verts[vertexD]); processScanEdge(&verts[vertexB], &verts[vertexD]); ushort colour16 = RGB888_TO_RGB565(((colour >> 16) & 0xFF), ((colour >> 8) & 0xFF), ((colour >> 0) & 0xFF)); ushort *frameBufferPtr = &Engine.frameBuffer[SCREEN_XSIZE * faceTop]; if (alpha == 255) { while (faceTop < faceBottom) { int startX = faceLineStart[faceTop]; int endX = faceLineEnd[faceTop]; if (startX >= SCREEN_XSIZE || endX <= 0) { frameBufferPtr += SCREEN_XSIZE; } else { if (startX < 0) startX = 0; if (endX > SCREEN_XSIZE - 1) endX = SCREEN_XSIZE - 1; ushort *fbPtr = &frameBufferPtr[startX]; frameBufferPtr += SCREEN_XSIZE; int vertexwidth = endX - startX + 1; while (vertexwidth--) { *fbPtr = colour16; ++fbPtr; } } ++faceTop; } } else { while (faceTop < faceBottom) { int startX = faceLineStart[faceTop]; int endX = faceLineEnd[faceTop]; if (startX >= SCREEN_XSIZE || endX <= 0) { frameBufferPtr += SCREEN_XSIZE; } else { if (startX < 0) startX = 0; if (endX > SCREEN_XSIZE - 1) endX = SCREEN_XSIZE - 1; ushort *fbPtr = &frameBufferPtr[startX]; frameBufferPtr += SCREEN_XSIZE; int vertexwidth = endX - startX + 1; while (vertexwidth--) { ushort *blendTableA = &blendLookupTable[BLENDTABLE_XSIZE * ((BLENDTABLE_YSIZE - 1) - alpha)]; ushort *blendTableB = &blendLookupTable[BLENDTABLE_XSIZE * alpha]; *fbPtr = (blendTableA[*fbPtr & (BLENDTABLE_XSIZE - 1)] + blendTableB[colour16 & (BLENDTABLE_XSIZE - 1)]) | ((blendTableA[(*fbPtr & 0x7E0) >> 6] + blendTableB[(colour16 & 0x7E0) >> 6]) << 6) | ((blendTableA[(*fbPtr & 0xF800) >> 11] + blendTableB[(colour16 & 0xF800) >> 11]) << 11); ++fbPtr; } } ++faceTop; } } #endif #if RETRO_HARDWARE_RENDER if (gfxVertexSize < VERTEX_LIMIT) { gfxPolyList[gfxVertexSize].x = verts[0].x << 4; gfxPolyList[gfxVertexSize].y = verts[0].y << 4; gfxPolyList[gfxVertexSize].colour.r = ((colour >> 16) & 0xFF); gfxPolyList[gfxVertexSize].colour.g = ((colour >> 8) & 0xFF); gfxPolyList[gfxVertexSize].colour.b = ((colour >> 0) & 0xFF); if (alpha > 0xFD) { gfxPolyList[gfxVertexSize].colour.a = 0xFF; } else { gfxPolyList[gfxVertexSize].colour.a = alpha; } gfxPolyList[gfxVertexSize].u = 10.24f; // 0.01f, scaled upto pixels vs floats gfxPolyList[gfxVertexSize].v = 10.24f; // 0.01f, scaled upto pixels vs floats gfxVertexSize++; gfxPolyList[gfxVertexSize].x = verts[1].x << 4; gfxPolyList[gfxVertexSize].y = verts[1].y << 4; gfxPolyList[gfxVertexSize].colour.r = gfxPolyList[gfxVertexSize - 1].colour.r; gfxPolyList[gfxVertexSize].colour.g = gfxPolyList[gfxVertexSize - 1].colour.g; gfxPolyList[gfxVertexSize].colour.b = gfxPolyList[gfxVertexSize - 1].colour.b; gfxPolyList[gfxVertexSize].colour.a = gfxPolyList[gfxVertexSize - 1].colour.a; gfxPolyList[gfxVertexSize].u = 10.24f; // 0.01f, scaled upto pixels vs floats gfxPolyList[gfxVertexSize].v = 10.24f; // 0.01f, scaled upto pixels vs floats gfxVertexSize++; gfxPolyList[gfxVertexSize].x = verts[2].x << 4; gfxPolyList[gfxVertexSize].y = verts[2].y << 4; gfxPolyList[gfxVertexSize].colour.r = gfxPolyList[gfxVertexSize - 1].colour.r; gfxPolyList[gfxVertexSize].colour.g = gfxPolyList[gfxVertexSize - 1].colour.g; gfxPolyList[gfxVertexSize].colour.b = gfxPolyList[gfxVertexSize - 1].colour.b; gfxPolyList[gfxVertexSize].colour.a = gfxPolyList[gfxVertexSize - 1].colour.a; gfxPolyList[gfxVertexSize].u = 10.24f; // 0.01f, scaled upto pixels vs floats gfxPolyList[gfxVertexSize].v = 10.24f; // 0.01f, scaled upto pixels vs floats gfxVertexSize++; gfxPolyList[gfxVertexSize].x = verts[3].x << 4; gfxPolyList[gfxVertexSize].y = verts[3].y << 4; gfxPolyList[gfxVertexSize].colour.r = gfxPolyList[gfxVertexSize - 1].colour.r; gfxPolyList[gfxVertexSize].colour.g = gfxPolyList[gfxVertexSize - 1].colour.g; gfxPolyList[gfxVertexSize].colour.b = gfxPolyList[gfxVertexSize - 1].colour.b; gfxPolyList[gfxVertexSize].colour.a = gfxPolyList[gfxVertexSize - 1].colour.a; gfxPolyList[gfxVertexSize].u = 10.24f; // 0.01f, scaled upto pixels vs floats gfxPolyList[gfxVertexSize].v = 10.24f; // 0.01f, scaled upto pixels vs floats gfxVertexSize++; gfxIndexSize += 6; } #endif } void DrawFadedFace(void *v, uint colour, uint fogColour, int alpha) { Vertex *verts = (Vertex *)v; if (alpha > 0xFF) alpha = 0xFF; if (alpha < 1) return; if (verts[0].x < 0 && verts[1].x < 0 && verts[2].x < 0 && verts[3].x < 0) return; if (verts[0].x > SCREEN_XSIZE && verts[1].x > SCREEN_XSIZE && verts[2].x > SCREEN_XSIZE && verts[3].x > SCREEN_XSIZE) return; if (verts[0].y < 0 && verts[1].y < 0 && verts[2].y < 0 && verts[3].y < 0) return; if (verts[0].y > SCREEN_YSIZE && verts[1].y > SCREEN_YSIZE && verts[2].y > SCREEN_YSIZE && verts[3].y > SCREEN_YSIZE) return; if (verts[0].x == verts[1].x && verts[1].x == verts[2].x && verts[2].x == verts[3].x) return; if (verts[0].y == verts[1].y && verts[1].y == verts[2].y && verts[2].y == verts[3].y) return; #if RETRO_SOFTWARE_RENDER int vertexA = 0; int vertexB = 1; int vertexC = 2; int vertexD = 3; if (verts[1].y < verts[0].y) { vertexA = 1; vertexB = 0; } if (verts[2].y < verts[vertexA].y) { int temp = vertexA; vertexA = 2; vertexC = temp; } if (verts[3].y < verts[vertexA].y) { int temp = vertexA; vertexA = 3; vertexD = temp; } if (verts[vertexC].y < verts[vertexB].y) { int temp = vertexB; vertexB = vertexC; vertexC = temp; } if (verts[vertexD].y < verts[vertexB].y) { int temp = vertexB; vertexB = vertexD; vertexD = temp; } if (verts[vertexD].y < verts[vertexC].y) { int temp = vertexC; vertexC = vertexD; vertexD = temp; } int faceTop = verts[vertexA].y; int faceBottom = verts[vertexD].y; if (faceTop < 0) faceTop = 0; if (faceBottom > SCREEN_YSIZE) faceBottom = SCREEN_YSIZE; for (int i = faceTop; i < faceBottom; ++i) { faceLineStart[i] = 100000; faceLineEnd[i] = -100000; } processScanEdge(&verts[vertexA], &verts[vertexB]); processScanEdge(&verts[vertexA], &verts[vertexC]); processScanEdge(&verts[vertexA], &verts[vertexD]); processScanEdge(&verts[vertexB], &verts[vertexC]); processScanEdge(&verts[vertexC], &verts[vertexD]); processScanEdge(&verts[vertexB], &verts[vertexD]); ushort colour16 = PACK_RGB888(((colour >> 16) & 0xFF), ((colour >> 8) & 0xFF), ((colour >> 0) & 0xFF)); ushort fogColour16 = PACK_RGB888(((fogColour >> 16) & 0xFF), ((fogColour >> 8) & 0xFF), ((fogColour >> 0) & 0xFF)); ushort *frameBufferPtr = &Engine.frameBuffer[SCREEN_XSIZE * faceTop]; while (faceTop < faceBottom) { int startX = faceLineStart[faceTop]; int endX = faceLineEnd[faceTop]; if (startX >= SCREEN_XSIZE || endX <= 0) { frameBufferPtr += SCREEN_XSIZE; } else { if (startX < 0) startX = 0; if (endX > SCREEN_XSIZE - 1) endX = SCREEN_XSIZE - 1; ushort *fbPtr = &frameBufferPtr[startX]; frameBufferPtr += SCREEN_XSIZE; int vertexwidth = endX - startX + 1; while (vertexwidth--) { ushort *blendTableA = &blendLookupTable[BLENDTABLE_XSIZE * ((BLENDTABLE_YSIZE - 1) - alpha)]; ushort *blendTableB = &blendLookupTable[BLENDTABLE_XSIZE * alpha]; *fbPtr = (blendTableA[fogColour16 & (BLENDTABLE_XSIZE - 1)] + blendTableB[colour16 & (BLENDTABLE_XSIZE - 1)]) | ((blendTableA[(fogColour16 & 0x7E0) >> 6] + blendTableB[(colour16 & 0x7E0) >> 6]) << 6) | ((blendTableA[(fogColour16 & 0xF800) >> 11] + blendTableB[(colour16 & 0xF800) >> 11]) << 11); ++fbPtr; } } ++faceTop; } #endif #if RETRO_HARDWARE_RENDER if (gfxVertexSize < VERTEX_LIMIT) { byte cr = ((colour >> 16) & 0xFF); byte cg = ((colour >> 8) & 0xFF); byte cb = ((colour >> 0) & 0xFF); byte fr = ((fogColour >> 16) & 0xFF); byte fg = ((fogColour >> 8) & 0xFF); byte fb = ((fogColour >> 0) & 0xFF); gfxPolyList[gfxVertexSize].x = verts[0].x << 4; gfxPolyList[gfxVertexSize].y = verts[0].y << 4; gfxPolyList[gfxVertexSize].colour.r = ((ushort)(fr * (0xFF - alpha) + alpha * cr) >> 8); gfxPolyList[gfxVertexSize].colour.g = ((ushort)(fg * (0xFF - alpha) + alpha * cg) >> 8); gfxPolyList[gfxVertexSize].colour.b = ((ushort)(fb * (0xFF - alpha) + alpha * cb) >> 8); gfxPolyList[gfxVertexSize].colour.a = 0xFF; gfxPolyList[gfxVertexSize].u = 10.24f; // 0.01f, scaled upto pixels vs floats gfxPolyList[gfxVertexSize].v = 10.24f; // 0.01f, scaled upto pixels vs floats gfxVertexSize++; gfxPolyList[gfxVertexSize].x = verts[1].x << 4; gfxPolyList[gfxVertexSize].y = verts[1].y << 4; gfxPolyList[gfxVertexSize].colour.r = gfxPolyList[gfxVertexSize - 1].colour.r; gfxPolyList[gfxVertexSize].colour.g = gfxPolyList[gfxVertexSize - 1].colour.g; gfxPolyList[gfxVertexSize].colour.b = gfxPolyList[gfxVertexSize - 1].colour.b; gfxPolyList[gfxVertexSize].colour.a = gfxPolyList[gfxVertexSize - 1].colour.a; gfxPolyList[gfxVertexSize].u = 10.24f; // 0.01f, scaled upto pixels vs floats gfxPolyList[gfxVertexSize].v = 10.24f; // 0.01f, scaled upto pixels vs floats gfxVertexSize++; gfxPolyList[gfxVertexSize].x = verts[3].x << 4; gfxPolyList[gfxVertexSize].y = verts[3].y << 4; gfxPolyList[gfxVertexSize].colour.r = gfxPolyList[gfxVertexSize - 1].colour.r; gfxPolyList[gfxVertexSize].colour.g = gfxPolyList[gfxVertexSize - 1].colour.g; gfxPolyList[gfxVertexSize].colour.b = gfxPolyList[gfxVertexSize - 1].colour.b; gfxPolyList[gfxVertexSize].colour.a = gfxPolyList[gfxVertexSize - 1].colour.a; gfxPolyList[gfxVertexSize].u = 10.24f; // 0.01f, scaled upto pixels vs floats gfxPolyList[gfxVertexSize].v = 10.24f; // 0.01f, scaled upto pixels vs floats gfxVertexSize++; gfxPolyList[gfxVertexSize].x = verts[2].x << 4; gfxPolyList[gfxVertexSize].y = verts[2].y << 4; gfxPolyList[gfxVertexSize].colour.r = gfxPolyList[gfxVertexSize - 1].colour.r; gfxPolyList[gfxVertexSize].colour.g = gfxPolyList[gfxVertexSize - 1].colour.g; gfxPolyList[gfxVertexSize].colour.b = gfxPolyList[gfxVertexSize - 1].colour.b; gfxPolyList[gfxVertexSize].colour.a = gfxPolyList[gfxVertexSize - 1].colour.a; gfxPolyList[gfxVertexSize].u = 10.24f; // 0.01f, scaled upto pixels vs floats gfxPolyList[gfxVertexSize].v = 10.24f; // 0.01f, scaled upto pixels vs floats gfxVertexSize++; gfxIndexSize += 6; } #endif } void DrawTexturedFace(void *v, byte sheetID) { Vertex *verts = (Vertex *)v; if (verts[0].x < 0 && verts[1].x < 0 && verts[2].x < 0 && verts[3].x < 0) return; if (verts[0].x > SCREEN_XSIZE && verts[1].x > SCREEN_XSIZE && verts[2].x > SCREEN_XSIZE && verts[3].x > SCREEN_XSIZE) return; if (verts[0].y < 0 && verts[1].y < 0 && verts[2].y < 0 && verts[3].y < 0) return; if (verts[0].y > SCREEN_YSIZE && verts[1].y > SCREEN_YSIZE && verts[2].y > SCREEN_YSIZE && verts[3].y > SCREEN_YSIZE) return; if (verts[0].x == verts[1].x && verts[1].x == verts[2].x && verts[2].x == verts[3].x) return; if (verts[0].y == verts[1].y && verts[1].y == verts[2].y && verts[2].y == verts[3].y) return; #if RETRO_SOFTWARE_RENDER int vertexA = 0; int vertexB = 1; int vertexC = 2; int vertexD = 3; if (verts[1].y < verts[0].y) { vertexA = 1; vertexB = 0; } if (verts[2].y < verts[vertexA].y) { int temp = vertexA; vertexA = 2; vertexC = temp; } if (verts[3].y < verts[vertexA].y) { int temp = vertexA; vertexA = 3; vertexD = temp; } if (verts[vertexC].y < verts[vertexB].y) { int temp = vertexB; vertexB = vertexC; vertexC = temp; } if (verts[vertexD].y < verts[vertexB].y) { int temp = vertexB; vertexB = vertexD; vertexD = temp; } if (verts[vertexD].y < verts[vertexC].y) { int temp = vertexC; vertexC = vertexD; vertexD = temp; } int faceTop = verts[vertexA].y; int faceBottom = verts[vertexD].y; if (faceTop < 0) faceTop = 0; if (faceBottom > SCREEN_YSIZE) faceBottom = SCREEN_YSIZE; for (int i = faceTop; i < faceBottom; ++i) { faceLineStart[i] = 100000; faceLineEnd[i] = -100000; } processScanEdgeUV(&verts[vertexA], &verts[vertexB]); processScanEdgeUV(&verts[vertexA], &verts[vertexC]); processScanEdgeUV(&verts[vertexA], &verts[vertexD]); processScanEdgeUV(&verts[vertexB], &verts[vertexC]); processScanEdgeUV(&verts[vertexC], &verts[vertexD]); processScanEdgeUV(&verts[vertexB], &verts[vertexD]); ushort *frameBufferPtr = &Engine.frameBuffer[SCREEN_XSIZE * faceTop]; byte *sheetPtr = &graphicData[gfxSurface[sheetID].dataPosition]; int shiftwidth = gfxSurface[sheetID].widthShift; byte *lineBuffer = &gfxLineBuffer[faceTop]; while (faceTop < faceBottom) { activePalette = fullPalette[*lineBuffer]; activePalette32 = fullPalette32[*lineBuffer]; lineBuffer++; int startX = faceLineStart[faceTop]; int endX = faceLineEnd[faceTop]; int UPos = faceLineStartU[faceTop]; int VPos = faceLineStartV[faceTop]; if (startX >= SCREEN_XSIZE || endX <= 0) { frameBufferPtr += SCREEN_XSIZE; } else { int posDifference = endX - startX; int bufferedUPos = 0; int bufferedVPos = 0; if (endX == startX) { bufferedUPos = 0; bufferedVPos = 0; } else { bufferedUPos = (faceLineEndU[faceTop] - UPos) / posDifference; bufferedVPos = (faceLineEndV[faceTop] - VPos) / posDifference; } if (endX > SCREEN_XSIZE - 1) posDifference = (SCREEN_XSIZE - 1) - startX; if (startX < 0) { posDifference += startX; UPos -= startX * bufferedUPos; VPos -= startX * bufferedVPos; startX = 0; } ushort *fbPtr = &frameBufferPtr[startX]; frameBufferPtr += SCREEN_XSIZE; int counter = posDifference + 1; while (counter--) { if (UPos < 0) UPos = 0; if (VPos < 0) VPos = 0; ushort index = sheetPtr[(VPos >> 16 << shiftwidth) + (UPos >> 16)]; if (index > 0) *fbPtr = activePalette[index]; fbPtr++; UPos += bufferedUPos; VPos += bufferedVPos; } } ++faceTop; } #endif #if RETRO_HARDWARE_RENDER GFXSurface *surface = &gfxSurface[sheetID]; if (gfxVertexSize < VERTEX_LIMIT) { gfxPolyList[gfxVertexSize].x = verts[0].x << 4; gfxPolyList[gfxVertexSize].y = verts[0].y << 4; gfxPolyList[gfxVertexSize].colour.r = 0xFF; gfxPolyList[gfxVertexSize].colour.g = 0xFF; gfxPolyList[gfxVertexSize].colour.b = 0xFF; gfxPolyList[gfxVertexSize].colour.a = 0xFF; gfxPolyList[gfxVertexSize].u = (surface->texStartX + verts[0].u); gfxPolyList[gfxVertexSize].v = (surface->texStartY + verts[0].v); gfxVertexSize++; gfxPolyList[gfxVertexSize].x = verts[1].x << 4; gfxPolyList[gfxVertexSize].y = verts[1].y << 4; gfxPolyList[gfxVertexSize].colour.r = 0xFF; gfxPolyList[gfxVertexSize].colour.g = 0xFF; gfxPolyList[gfxVertexSize].colour.b = 0xFF; gfxPolyList[gfxVertexSize].colour.a = 0xFF; gfxPolyList[gfxVertexSize].u = (surface->texStartX + verts[1].u); gfxPolyList[gfxVertexSize].v = (surface->texStartY + verts[1].v); gfxVertexSize++; gfxPolyList[gfxVertexSize].x = verts[2].x << 4; gfxPolyList[gfxVertexSize].y = verts[2].y << 4; gfxPolyList[gfxVertexSize].colour.r = 0xFF; gfxPolyList[gfxVertexSize].colour.g = 0xFF; gfxPolyList[gfxVertexSize].colour.b = 0xFF; gfxPolyList[gfxVertexSize].colour.a = 0xFF; gfxPolyList[gfxVertexSize].u = (surface->texStartX + verts[2].u); gfxPolyList[gfxVertexSize].v = (surface->texStartY + verts[2].v); gfxVertexSize++; gfxPolyList[gfxVertexSize].x = verts[3].x << 4; gfxPolyList[gfxVertexSize].y = verts[3].y << 4; gfxPolyList[gfxVertexSize].colour.r = 0xFF; gfxPolyList[gfxVertexSize].colour.g = 0xFF; gfxPolyList[gfxVertexSize].colour.b = 0xFF; gfxPolyList[gfxVertexSize].colour.a = 0xFF; gfxPolyList[gfxVertexSize].u = (surface->texStartX + verts[3].u); gfxPolyList[gfxVertexSize].v = (surface->texStartY + verts[3].v); gfxVertexSize++; gfxIndexSize += 6; } #endif } void DrawTexturedFaceBlended(void *v, byte sheetID) { Vertex *verts = (Vertex *)v; if (verts[0].x < 0 && verts[1].x < 0 && verts[2].x < 0 && verts[3].x < 0) return; if (verts[0].x > SCREEN_XSIZE && verts[1].x > SCREEN_XSIZE && verts[2].x > SCREEN_XSIZE && verts[3].x > SCREEN_XSIZE) return; if (verts[0].y < 0 && verts[1].y < 0 && verts[2].y < 0 && verts[3].y < 0) return; if (verts[0].y > SCREEN_YSIZE && verts[1].y > SCREEN_YSIZE && verts[2].y > SCREEN_YSIZE && verts[3].y > SCREEN_YSIZE) return; if (verts[0].x == verts[1].x && verts[1].x == verts[2].x && verts[2].x == verts[3].x) return; if (verts[0].y == verts[1].y && verts[1].y == verts[2].y && verts[2].y == verts[3].y) return; #if RETRO_SOFTWARE_RENDER int vertexA = 0; int vertexB = 1; int vertexC = 2; int vertexD = 3; if (verts[1].y < verts[0].y) { vertexA = 1; vertexB = 0; } if (verts[2].y < verts[vertexA].y) { int temp = vertexA; vertexA = 2; vertexC = temp; } if (verts[3].y < verts[vertexA].y) { int temp = vertexA; vertexA = 3; vertexD = temp; } if (verts[vertexC].y < verts[vertexB].y) { int temp = vertexB; vertexB = vertexC; vertexC = temp; } if (verts[vertexD].y < verts[vertexB].y) { int temp = vertexB; vertexB = vertexD; vertexD = temp; } if (verts[vertexD].y < verts[vertexC].y) { int temp = vertexC; vertexC = vertexD; vertexD = temp; } int faceTop = verts[vertexA].y; int faceBottom = verts[vertexD].y; if (faceTop < 0) faceTop = 0; if (faceBottom > SCREEN_YSIZE) faceBottom = SCREEN_YSIZE; for (int i = faceTop; i < faceBottom; ++i) { faceLineStart[i] = 100000; faceLineEnd[i] = -100000; } processScanEdgeUV(&verts[vertexA], &verts[vertexB]); processScanEdgeUV(&verts[vertexA], &verts[vertexC]); processScanEdgeUV(&verts[vertexA], &verts[vertexD]); processScanEdgeUV(&verts[vertexB], &verts[vertexC]); processScanEdgeUV(&verts[vertexC], &verts[vertexD]); processScanEdgeUV(&verts[vertexB], &verts[vertexD]); ushort *frameBufferPtr = &Engine.frameBuffer[SCREEN_XSIZE * faceTop]; byte *sheetPtr = &graphicData[gfxSurface[sheetID].dataPosition]; int shiftwidth = gfxSurface[sheetID].widthShift; byte *lineBuffer = &gfxLineBuffer[faceTop]; while (faceTop < faceBottom) { activePalette = fullPalette[*lineBuffer]; activePalette32 = fullPalette32[*lineBuffer]; lineBuffer++; int startX = faceLineStart[faceTop]; int endX = faceLineEnd[faceTop]; int UPos = faceLineStartU[faceTop]; int VPos = faceLineStartV[faceTop]; if (startX >= SCREEN_XSIZE || endX <= 0) { frameBufferPtr += SCREEN_XSIZE; } else { int posDifference = endX - startX; int bufferedUPos = 0; int bufferedVPos = 0; if (endX == startX) { bufferedUPos = 0; bufferedVPos = 0; } else { bufferedUPos = (faceLineEndU[faceTop] - UPos) / posDifference; bufferedVPos = (faceLineEndV[faceTop] - VPos) / posDifference; } if (endX > SCREEN_XSIZE - 1) posDifference = (SCREEN_XSIZE - 1) - startX; if (startX < 0) { posDifference += startX; UPos -= startX * bufferedUPos; VPos -= startX * bufferedVPos; startX = 0; } ushort *fbPtr = &frameBufferPtr[startX]; frameBufferPtr += SCREEN_XSIZE; int counter = posDifference + 1; while (counter--) { if (UPos < 0) UPos = 0; if (VPos < 0) VPos = 0; ushort index = sheetPtr[(VPos >> 16 << shiftwidth) + (UPos >> 16)]; if (index > 0) *fbPtr = ((activePalette[index] & 0xF7BC) >> 1) + ((*fbPtr & 0xF7BC) >> 1); fbPtr++; UPos += bufferedUPos; VPos += bufferedVPos; } } ++faceTop; } #endif #if RETRO_HARDWARE_RENDER GFXSurface *surface = &gfxSurface[sheetID]; if (gfxVertexSize < VERTEX_LIMIT) { gfxPolyList[gfxVertexSize].x = verts[0].x << 4; gfxPolyList[gfxVertexSize].y = verts[0].y << 4; gfxPolyList[gfxVertexSize].colour.r = 0xFF; gfxPolyList[gfxVertexSize].colour.g = 0xFF; gfxPolyList[gfxVertexSize].colour.b = 0xFF; gfxPolyList[gfxVertexSize].colour.a = 0x80; gfxPolyList[gfxVertexSize].u = (surface->texStartX + verts[0].u); gfxPolyList[gfxVertexSize].v = (surface->texStartY + verts[0].v); gfxVertexSize++; gfxPolyList[gfxVertexSize].x = verts[1].x << 4; gfxPolyList[gfxVertexSize].y = verts[1].y << 4; gfxPolyList[gfxVertexSize].colour.r = 0xFF; gfxPolyList[gfxVertexSize].colour.g = 0xFF; gfxPolyList[gfxVertexSize].colour.b = 0xFF; gfxPolyList[gfxVertexSize].colour.a = 0x80; gfxPolyList[gfxVertexSize].u = (surface->texStartX + verts[1].u); gfxPolyList[gfxVertexSize].v = (surface->texStartY + verts[1].v); gfxVertexSize++; gfxPolyList[gfxVertexSize].x = verts[2].x << 4; gfxPolyList[gfxVertexSize].y = verts[2].y << 4; gfxPolyList[gfxVertexSize].colour.r = 0xFF; gfxPolyList[gfxVertexSize].colour.g = 0xFF; gfxPolyList[gfxVertexSize].colour.b = 0xFF; gfxPolyList[gfxVertexSize].colour.a = 0x80; gfxPolyList[gfxVertexSize].u = (surface->texStartX + verts[2].u); gfxPolyList[gfxVertexSize].v = (surface->texStartY + verts[2].v); gfxVertexSize++; gfxPolyList[gfxVertexSize].x = verts[3].x << 4; gfxPolyList[gfxVertexSize].y = verts[3].y << 4; gfxPolyList[gfxVertexSize].colour.r = 0xFF; gfxPolyList[gfxVertexSize].colour.g = 0xFF; gfxPolyList[gfxVertexSize].colour.b = 0xFF; gfxPolyList[gfxVertexSize].colour.a = 0x80; gfxPolyList[gfxVertexSize].u = (surface->texStartX + verts[3].u); gfxPolyList[gfxVertexSize].v = (surface->texStartY + verts[3].v); gfxVertexSize++; gfxIndexSize += 6; } #endif } #if RETRO_REV01 void DrawBitmapText(void *menu, int XPos, int YPos, int scale, int spacing, int rowStart, int rowCount) { TextMenu *tMenu = (TextMenu *)menu; int Y = YPos << 9; if (rowCount < 0) rowCount = tMenu->rowCount; if (rowStart + rowCount > tMenu->rowCount) rowCount = tMenu->rowCount - rowStart; while (rowCount > 0) { int X = XPos << 9; for (int i = 0; i < tMenu->entrySize[rowStart]; ++i) { ushort c = tMenu->textData[tMenu->entryStart[rowStart] + i]; FontCharacter *fChar = &fontCharacterList[c]; #if RETRO_SOFTWARE_RENDER DrawSpriteScaled(FLIP_NONE, X >> 9, Y >> 9, -fChar->pivotX, -fChar->pivotY, scale, scale, fChar->width, fChar->height, fChar->srcX, fChar->srcY, textMenuSurfaceNo); #endif #if RETRO_HARDWARE_RENDER DrawScaledChar(FLIP_NONE, X >> 5, Y >> 5, -fChar->pivotX, -fChar->pivotY, scale, scale, fChar->width, fChar->height, fChar->srcX, fChar->srcY, textMenuSurfaceNo); #endif X += fChar->xAdvance * scale; } Y += spacing * scale; rowStart++; rowCount--; } } #endif void DrawTextMenuEntry(void *menu, int rowID, int XPos, int YPos, int textHighlight) { TextMenu *tMenu = (TextMenu *)menu; int id = tMenu->entryStart[rowID]; for (int i = 0; i < tMenu->entrySize[rowID]; ++i) { DrawSprite(XPos + (i << 3) - (((tMenu->entrySize[rowID] % 2) & (tMenu->alignment == 2)) * 4), YPos, 8, 8, (int)((int)(tMenu->textData[id] & 0xF) << 3), (int)((int)(tMenu->textData[id] >> 4) << 3) + textHighlight, textMenuSurfaceNo); id++; } } void DrawStageTextEntry(void *menu, int rowID, int XPos, int YPos, int textHighlight) { TextMenu *tMenu = (TextMenu *)menu; int id = tMenu->entryStart[rowID]; for (int i = 0; i < tMenu->entrySize[rowID]; ++i) { if (i == tMenu->entrySize[rowID] - 1) { DrawSprite(XPos + (i << 3), YPos, 8, 8, (int)((int)(tMenu->textData[id] & 0xF) << 3), (int)((int)(tMenu->textData[id] >> 4) << 3), textMenuSurfaceNo); } else { DrawSprite(XPos + (i << 3), YPos, 8, 8, (int)((int)(tMenu->textData[id] & 0xF) << 3), (int)((int)(tMenu->textData[id] >> 4) << 3) + textHighlight, textMenuSurfaceNo); } id++; } } void DrawBlendedTextMenuEntry(void *menu, int rowID, int XPos, int YPos, int textHighlight) { TextMenu *tMenu = (TextMenu *)menu; int id = tMenu->entryStart[rowID]; for (int i = 0; i < tMenu->entrySize[rowID]; ++i) { DrawBlendedSprite(XPos + (i << 3), YPos, 8, 8, (int)((int)(tMenu->textData[id] & 0xF) << 3), (int)((int)(tMenu->textData[id] >> 4) << 3) + textHighlight, textMenuSurfaceNo); id++; } } void DrawTextMenu(void *menu, int XPos, int YPos) { TextMenu *tMenu = (TextMenu *)menu; int cnt = 0; if (tMenu->visibleRowCount > 0) { cnt = (int)(tMenu->visibleRowCount + tMenu->visibleRowOffset); } else { tMenu->visibleRowOffset = 0; cnt = (int)tMenu->rowCount; } if (tMenu->selectionCount == 3) { tMenu->selection2 = -1; for (int i = 0; i < tMenu->selection1 + 1; ++i) { if (tMenu->entryHighlight[i]) { tMenu->selection2 = i; } } } switch (tMenu->alignment) { case 0: for (int i = (int)tMenu->visibleRowOffset; i < cnt; ++i) { switch (tMenu->selectionCount) { case 1: if (i == tMenu->selection1) DrawTextMenuEntry(tMenu, i, XPos, YPos, 128); else DrawTextMenuEntry(tMenu, i, XPos, YPos, 0); break; case 2: if (i == tMenu->selection1 || i == tMenu->selection2) DrawTextMenuEntry(tMenu, i, XPos, YPos, 128); else DrawTextMenuEntry(tMenu, i, XPos, YPos, 0); break; case 3: if (i == tMenu->selection1) DrawTextMenuEntry(tMenu, i, XPos, YPos, 128); else DrawTextMenuEntry(tMenu, i, XPos, YPos, 0); if (i == tMenu->selection2 && i != tMenu->selection1) DrawStageTextEntry(tMenu, i, XPos, YPos, 128); break; } YPos += 8; } return; case 1: for (int i = (int)tMenu->visibleRowOffset; i < cnt; ++i) { int XPos2 = XPos - (tMenu->entrySize[i] << 3); switch (tMenu->selectionCount) { case 1: if (i == tMenu->selection1) DrawTextMenuEntry(tMenu, i, XPos2, YPos, 128); else DrawTextMenuEntry(tMenu, i, XPos2, YPos, 0); break; case 2: if (i == tMenu->selection1 || i == tMenu->selection2) DrawTextMenuEntry(tMenu, i, XPos2, YPos, 128); else DrawTextMenuEntry(tMenu, i, XPos2, YPos, 0); break; case 3: if (i == tMenu->selection1) DrawTextMenuEntry(tMenu, i, XPos2, YPos, 128); else DrawTextMenuEntry(tMenu, i, XPos2, YPos, 0); if (i == tMenu->selection2 && i != tMenu->selection1) DrawStageTextEntry(tMenu, i, XPos2, YPos, 128); break; } YPos += 8; } return; case 2: for (int i = (int)tMenu->visibleRowOffset; i < cnt; ++i) { int XPos2 = XPos - (tMenu->entrySize[i] >> 1 << 3); switch (tMenu->selectionCount) { case 1: if (i == tMenu->selection1) DrawTextMenuEntry(tMenu, i, XPos2, YPos, 128); else DrawTextMenuEntry(tMenu, i, XPos2, YPos, 0); break; case 2: if (i == tMenu->selection1 || i == tMenu->selection2) DrawTextMenuEntry(tMenu, i, XPos2, YPos, 128); else DrawTextMenuEntry(tMenu, i, XPos2, YPos, 0); break; case 3: if (i == tMenu->selection1) DrawTextMenuEntry(tMenu, i, XPos2, YPos, 128); else DrawTextMenuEntry(tMenu, i, XPos2, YPos, 0); if (i == tMenu->selection2 && i != tMenu->selection1) DrawStageTextEntry(tMenu, i, XPos2, YPos, 128); break; } YPos += 8; } return; default: return; } }
45.357965
150
0.500844
0xR00KIE
3ebcc01edad99381289f8cf0fce2666bd9a70fa5
1,932
cpp
C++
components/rollkit/src/session_manager.cpp
NeilBetham/rollk
e82026397c892b5f0d3b53891d5efa51d941fd9d
[ "MIT" ]
4
2018-06-12T21:48:01.000Z
2021-04-01T15:18:50.000Z
components/rollkit/src/session_manager.cpp
NeilBetham/rollk
e82026397c892b5f0d3b53891d5efa51d941fd9d
[ "MIT" ]
null
null
null
components/rollkit/src/session_manager.cpp
NeilBetham/rollk
e82026397c892b5f0d3b53891d5efa51d941fd9d
[ "MIT" ]
1
2018-08-18T13:05:31.000Z
2018-08-18T13:05:31.000Z
#include "rollkit/session_manager.hpp" #include <string> #include <cstring> #include <utility> #include <functional> #include <esp_log.h> #include "rollkit/request.hpp" using namespace std; namespace rollkit { SessionManager::SessionManager(interfaces::ISessionDelegate* delegate) : _session_delegate(delegate) {} SessionManager::~SessionManager(){ for(auto &session : sessions){ session.second.close(); } } void SessionManager::handle_mg_event(struct mg_connection* nc, int event, void *event_data){ switch(event){ // New connection case MG_EV_ACCEPT: { ESP_LOGD("session-manager", "MG Event Accept"); sessions.emplace(std::piecewise_construct, std::make_tuple(nc), std::make_tuple(_session_delegate, nc)); break; } // New data on existing connection case MG_EV_RECV: { int recevied_bytes = nc->recv_mbuf.len; ESP_LOGD("session-manager", "MG Event Recv Bytes Len: %d, Con: %p", recevied_bytes, nc); // Allocate a string to fit the recevied data string message; message.resize(recevied_bytes); // Copy recived contents to local buffer memcpy(&message[0], nc->recv_mbuf.buf, recevied_bytes); // Clear mongoose buffer mbuf_remove(&nc->recv_mbuf, recevied_bytes); // Give data to session for processing sessions[nc].handle_request(message); break; } // Existing connection closed case MG_EV_CLOSE: { ESP_LOGD("session-manager", "MG Event Close"); if(sessions.find(nc) != sessions.end()){ // If the session exists close it sessions[nc].close(); sessions.erase(nc); ESP_LOGI("session-manager", "Connection Closed: %p", nc); } break; } case MG_EV_SEND : { int* bytes_sent = (int*)event_data; ESP_LOGD("session-manager", "MG Sent %i bytes", *bytes_sent); } default: break; } } } // namespace rollkit
25.421053
110
0.65942
NeilBetham
3ebde6284f9fa389e0896782e2c4b0b5ee1bbe47
7,115
cpp
C++
calculus/if.cpp
lilissun/spa
d44974c51017691ff4ada29c212c54bb0ee931c2
[ "Apache-2.0" ]
null
null
null
calculus/if.cpp
lilissun/spa
d44974c51017691ff4ada29c212c54bb0ee931c2
[ "Apache-2.0" ]
null
null
null
calculus/if.cpp
lilissun/spa
d44974c51017691ff4ada29c212c54bb0ee931c2
[ "Apache-2.0" ]
1
2020-04-24T02:28:32.000Z
2020-04-24T02:28:32.000Z
// // if.cpp // calculus // // Created by Li Li on 9/5/15. // Copyright (c) 2015 Lilissun. All rights reserved. // #include "if.h" #include <sstream> #include "common/iostream.h" #include "common/debug.h" #include "symbolic/term.h" #include "symbolic/function.h" #include "symbolic/tuple.h" #include "symbolic/guard.h" #include "symbolic/constraint.h" #include "expression.h" #include "state.h" namespace cal { If::~If() { delete _left; delete _right; delete _then_process; delete _else_process; } void If::execute(Program *program, const State *state, std::vector<tim::Rule *> &rules) const { auto next_state = state->clone(); auto left = _left->evaluate(program, next_state); auto right = _right->evaluate(program, next_state); ASSERT(_then_process != nullptr); auto left_sort = left->sort(); auto right_sort = right->sort(); if (_op == IfType::IF_EQUAL) { if ((left_sort == sym::TermSort::TERM_SORT_NUMBER || left_sort == sym::TERM_SORT_USER_DEFINED) && (right_sort == sym::TermSort::TERM_SORT_NUMBER || right_sort == sym::TermSort::TERM_SORT_USER_DEFINED)) { auto then_state = next_state->clone(); then_state->unify(left, right); _then_process->execute(program, then_state, rules); if (_else_process != nullptr) { next_state->add_guard(sym::make_guard_not_equal(left->clone(), right->clone())); _else_process->execute(program, next_state, rules); } delete then_state; } else if ((left_sort == sym::TermSort::TERM_SORT_NUMBER || left_sort == sym::TERM_SORT_LINEAR_EXPRESSION) && (right_sort == sym::TermSort::TERM_SORT_NUMBER || right_sort == sym::TermSort::TERM_SORT_LINEAR_EXPRESSION)) { auto then_state = next_state->clone(); then_state->add_constraint(sym::make_constraint_equal(left, right)); _then_process->execute(program, then_state, rules); if (_else_process != nullptr) { auto else_state = then_state->clone(); else_state->add_constraint(sym::make_constraint_not_equal(left, right)); _else_process->execute(program, else_state, rules); delete else_state; } delete then_state; } else { std::stringstream ss; ss << "@if condition at " << _location << " is not equivalence"; ss << " of linear expressions or user-defined functions"; USER_ERROR(ss.str()); } } else if (_op == IfType::IF_NOT_EQUAL) { if ((left_sort == sym::TermSort::TERM_SORT_NUMBER || left_sort == sym::TERM_SORT_USER_DEFINED) && (right_sort == sym::TermSort::TERM_SORT_NUMBER || right_sort == sym::TermSort::TERM_SORT_USER_DEFINED)) { auto then_state = next_state->clone(); then_state->add_guard(sym::make_guard_not_equal(left, right)); _then_process->execute(program, then_state, rules); if (_else_process != nullptr) { next_state->unify(left->clone(), right->clone()); _else_process->execute(program, next_state, rules); } delete then_state; } else if ((left_sort == sym::TermSort::TERM_SORT_NUMBER || left_sort == sym::TERM_SORT_LINEAR_EXPRESSION) && (right_sort == sym::TermSort::TERM_SORT_NUMBER || right_sort == sym::TermSort::TERM_SORT_LINEAR_EXPRESSION)) { auto then_state = next_state->clone(); then_state->add_constraint(sym::make_constraint_not_equal(left, right)); _then_process->execute(program, then_state, rules); if (_else_process != nullptr) { auto else_state = then_state->clone(); else_state->add_constraint(sym::make_constraint_equal(left, right)); _else_process->execute(program, else_state, rules); delete else_state; } delete then_state; } else { std::stringstream ss; ss << "@if condition at " << _location << " is not inequivalence"; ss << " of linear expressions or user-defined functions"; USER_ERROR(ss.str()); } } else { if ((left_sort == sym::TermSort::TERM_SORT_NUMBER || left_sort == sym::TERM_SORT_LINEAR_EXPRESSION) && (right_sort == sym::TermSort::TERM_SORT_NUMBER || right_sort == sym::TermSort::TERM_SORT_LINEAR_EXPRESSION)) { auto then_state = next_state->clone(); sym::Constraint *constraint = nullptr; if (_op == IfType::IF_LESS) { constraint = sym::make_constraint_less(left, right); } else if (_op == IfType::IF_LESS_EQUAL) { constraint = sym::make_constraint_less_equal(left, right); } else if (_op == IfType::IF_GREATER) { constraint = sym::make_constraint_greater(left, right); } else { ASSERT(_op == IfType::IF_GREATER_EQUAL); constraint = sym::make_constraint_greater_equal(left, right); } then_state->add_constraint(constraint); _then_process->execute(program, then_state, rules); if (_else_process != nullptr) { auto else_state = next_state->clone(); auto reverse = constraint->reverse(); else_state->add_constraint(reverse); _else_process->execute(program, else_state, rules); delete else_state; } delete then_state; } else { std::stringstream ss; ss << "@if condition at " << _location << " is not inequivalence of linear expressions"; USER_ERROR(ss.str()); } } delete next_state; } void If::info(const size_t depth, std::ostream &os) const { os << com::tabs(process_tab_size, depth) << process_if << process_space << process_left_para; _left->info(os); os << process_space << IfTypeName[_op] << process_space; _right->info(os); os << process_right_para << process_space; if (_else_process == nullptr) { os << process_then << std::endl; _then_process->info(depth, os); } else { os << process_left_bracket << std::endl; _then_process->info(depth + 1, os); os << com::tabs(process_tab_size, depth) << process_right_bracket << process_space << process_else << process_space << process_left_bracket << std::endl; _else_process->info(depth + 1, os); os << com::tabs(process_tab_size, depth) << process_right_bracket << std::endl; } } }
48.401361
232
0.568096
lilissun
3ebe87f68766be6b33877ebc316614bf278c657c
1,029
cpp
C++
TorentMakerConsoleApplication/Geometry/QuadStripFltIdx.cpp
sssr33/TorrentMaker
75dc4b7b45c3c277342470f705e4a35264f942f7
[ "MIT" ]
null
null
null
TorentMakerConsoleApplication/Geometry/QuadStripFltIdx.cpp
sssr33/TorrentMaker
75dc4b7b45c3c277342470f705e4a35264f942f7
[ "MIT" ]
null
null
null
TorentMakerConsoleApplication/Geometry/QuadStripFltIdx.cpp
sssr33/TorrentMaker
75dc4b7b45c3c277342470f705e4a35264f942f7
[ "MIT" ]
null
null
null
#include "QuadStripFltIdx.h" QuadStripFltIdx::QuadStripFltIdx(ID3D11Device *d3dDev) { HRESULT hr = S_OK; float idx[] = { 0, 1, 2, 3 }; D3D11_BUFFER_DESC bufDesc; D3D11_SUBRESOURCE_DATA subResData; bufDesc.ByteWidth = sizeof(idx); bufDesc.Usage = D3D11_USAGE_IMMUTABLE; bufDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER; bufDesc.CPUAccessFlags = 0; bufDesc.MiscFlags = 0; bufDesc.StructureByteStride = 0; subResData.pSysMem = idx; subResData.SysMemPitch = 0; subResData.SysMemSlicePitch = 0; hr = d3dDev->CreateBuffer(&bufDesc, &subResData, fltIdxBuf.GetAddressOf()); H::System::ThrowIfFailed(hr); } void QuadStripFltIdx::SetToContext(ID3D11DeviceContext *d3dCtx, uint32_t startSlot) const { uint32_t stride = (uint32_t)sizeof(float); uint32_t offset = 0; d3dCtx->IASetVertexBuffers(startSlot, 1, fltIdxBuf.GetAddressOf(), &stride, &offset); } D3D11_PRIMITIVE_TOPOLOGY QuadStripFltIdx::GetTopology() { return D3D11_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP; } uint32_t QuadStripFltIdx::GetVertexCount() { return 4; }
27.810811
91
0.773567
sssr33
3ebecb308309f9ce85e2a139966937a055cf05f6
2,005
cpp
C++
DeepSpace/src/main/cpp/commands/ElevatorCalibrate.cpp
NorthernForce/DeepSpace
b8446f0fb732e7df030970332574e13d94e79df9
[ "MIT" ]
3
2019-01-08T00:09:56.000Z
2020-03-12T03:05:20.000Z
DeepSpace/src/main/cpp/commands/ElevatorCalibrate.cpp
NorthernForce/DeepSpace
b8446f0fb732e7df030970332574e13d94e79df9
[ "MIT" ]
12
2019-01-17T00:33:54.000Z
2019-06-27T01:56:18.000Z
DeepSpace/src/main/cpp/commands/ElevatorCalibrate.cpp
NorthernForce/DeepSpace
b8446f0fb732e7df030970332574e13d94e79df9
[ "MIT" ]
null
null
null
/*----------------------------------------------------------------------------*/ /* Copyright (c) 2017-2018 FIRST. All Rights Reserved. */ /* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ /* the project. */ /*----------------------------------------------------------------------------*/ #include "commands/ElevatorCalibrate.h" #include "Robot.h" const double ElevatorCalibrate::k_highSpeed = -0.5; const double ElevatorCalibrate::k_lowSpeed = -0.4; const double ElevatorCalibrate::k_speedThreshold = 1500; ElevatorCalibrate::ElevatorCalibrate() : Command("ElevatorCalibrate") { Requires(Robot::m_elevator.get()); } // Called just before this Command runs the first time void ElevatorCalibrate::Initialize() { Robot::m_elevator->enableReverseLimitSwitch(); Robot::m_elevator->enableForwardLimitSwitch(); } // Called repeatedly when this Command is scheduled to run void ElevatorCalibrate::Execute() { if (Robot::m_elevator->getSelectedSensorPosition() > k_speedThreshold) { Robot::m_elevator->setSpeed(k_highSpeed); } else { Robot::m_elevator->setSpeed(k_lowSpeed); } } // Make this return true when this Command no longer needs to run execute() bool ElevatorCalibrate::IsFinished() { return Robot::m_elevator->atLowerLimit() && !Robot::m_elevator->isRetracted(); } // Called once after isFinished returns true void ElevatorCalibrate::End() { Robot::m_elevator->stop(); // This is now done in the elevator periodic // if (Robot::m_elevator->atLowerLimit()) { Robot::m_elevator->setHomePosition(); // } Robot::m_elevator->disableReverseLimitSwitch(); Robot::m_elevator->disableForwardLimitSwitch(); } // Called when another command which requires one or more of the same // subsystems is scheduled to run void ElevatorCalibrate::Interrupted() { End(); }
35.175439
80
0.64788
NorthernForce
3ebfa308b44bd8a4d3895e4629214ed2b078eeb7
4,775
hh
C++
src/dev/i2cbus.hh
alianmohammad/pd-gem5-latest
cfcf6aa004c168d6abdfedcd595de4b30f5e88ee
[ "BSD-3-Clause" ]
1
2019-01-26T10:34:02.000Z
2019-01-26T10:34:02.000Z
src/dev/i2cbus.hh
alianmohammad/pd-gem5-latest
cfcf6aa004c168d6abdfedcd595de4b30f5e88ee
[ "BSD-3-Clause" ]
null
null
null
src/dev/i2cbus.hh
alianmohammad/pd-gem5-latest
cfcf6aa004c168d6abdfedcd595de4b30f5e88ee
[ "BSD-3-Clause" ]
1
2021-07-06T10:40:34.000Z
2021-07-06T10:40:34.000Z
/* * Copyright (c) 2012 ARM Limited * All rights reserved * * The license below extends only to copyright in the software and shall * not be construed as granting a license to any other intellectual * property including but not limited to intellectual property relating * to a hardware implementation of the functionality of the software * licensed hereunder. You may use the software subject to the license * terms below provided that you ensure that this notice is replicated * unmodified and in its entirety in all distributions of the software, * modified or unmodified, in source code or in binary form. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Authors: Peter Enns */ /** @file * Implementiation of an i2c bus */ #ifndef __DEV_I2CBUS__ #define __DEV_I2CBUS__ #include <map> #include "dev/i2cdev.hh" #include "dev/io_device.hh" #include "params/I2CBus.hh" class I2CBus : public BasicPioDevice { protected: enum I2CState { IDLE, RECEIVING_ADDR, RECEIVING_DATA, SENDING_DATA, }; /** * Read [and Set] serial control bits: * Bit [0] is SCL * Bit [1] is SDA * * http://infocenter.arm.com/help/topic/com.arm.doc.dui0440b/Bbajdjeg.html */ static const int SB_CONTROLS = 0x0; /** Clear control bits. Analogous to SB_CONTROLS */ static const int SB_CONTROLC = 0x4; /** I2C clock wire (0, 1). */ uint8_t scl; /** I2C data wire (0, 1) */ uint8_t sda; /** * State used by I2CBus::write to determine what stage of an i2c * transmission it is currently in. */ enum I2CState state; /** * Order of the bit of the current message that is being sent or * received (0 - 7). */ int currBit; /** * Key used to access a device in the slave devices map. This * is the same address that is specified in kernel board * initialization code (e.g., arch/arm/mach-realview/core.c). */ uint8_t i2cAddr; /** 8-bit buffer used to send and receive messages bit by bit. */ uint8_t message; /** * All the slave i2c devices that are connected to this * bus. Each device has an address that points to the actual * device. */ std::map<uint8_t, I2CDevice*> devices; /** * Update data (sda) and clock (scl) to match any transitions * specified by pkt. * * @param pkt memory request packet */ void updateSignals(PacketPtr pkt); /** * Clock set check * * @param pkt memory request packet * @return true if pkt indicates that scl transition from 0 to 1 */ bool isClockSet(PacketPtr pkt) const; /** * i2c start signal check * * @param pkt memory request packet * @return true if pkt indicates a new transmission */ bool isStart(PacketPtr pkt) const; /** * i2c end signal check * * @param pkt memory request packet * @return true if pkt indicates stopping the current transmission */ bool isEnd(PacketPtr pkt) const; public: I2CBus(const I2CBusParams* p); virtual Tick read(PacketPtr pkt); virtual Tick write(PacketPtr pkt); void serialize(CheckpointOut &cp) const M5_ATTR_OVERRIDE; void unserialize(CheckpointIn &cp) M5_ATTR_OVERRIDE; }; #endif //__DEV_I2CBUS
31.006494
78
0.693194
alianmohammad
3ec63a1fde71f47b2fb21825c682d2e1656e24ee
907
hpp
C++
TGEngine/util/Math.hpp
ThePixly/TGEngine
aff5d5f42c3094dcc37253f4a3f5e09db560a4eb
[ "Apache-2.0" ]
null
null
null
TGEngine/util/Math.hpp
ThePixly/TGEngine
aff5d5f42c3094dcc37253f4a3f5e09db560a4eb
[ "Apache-2.0" ]
null
null
null
TGEngine/util/Math.hpp
ThePixly/TGEngine
aff5d5f42c3094dcc37253f4a3f5e09db560a4eb
[ "Apache-2.0" ]
null
null
null
#pragma once #include "Annotations.hpp" #include <cstdint> #include <cmath> #include "glm/glm.hpp" #include "TGVertex.hpp" #define PI 3.14159265358979323846 #define PIx2 6.28318530717958647692 #define SQRT_PIx2 2.506628274631 #define EULER 2.71828182845904523536 namespace math { SINCE(0, 0, 4) TGVertex midpoint(TGVertex a, TGVertex b, float t = 0.5f); SINCE(0, 0, 4) glm::vec4 mixColor(glm::vec4 a, glm::vec4 b, float t = 0.5f); SINCE(0, 0, 4) float calculateNormalDistribution(float x, float mu = 0.0f, float sigma = 1.0f); SINCE(0, 0, 1) float f_max(float val1, float val2); SINCE(0, 0, 1) int i_max(int val1, int val2); SINCE(0, 0, 1) float f_min(float val1, float val2); SINCE(0, 0, 1) int i_min(int val1, int val2); SINCE(0, 0, 1) std::uint32_t u_max(std::uint32_t val1, std::uint32_t val2); SINCE(0, 0, 1) std::uint32_t u_min(std::uint32_t val1, std::uint32_t val2); }
21.093023
81
0.696803
ThePixly
3ec9ff88e59abe6a310b2da6722b4dfcd01dcd8f
10,043
cxx
C++
proto/modbuscpp.cxx
trotill/11parts_CPP
53a69d516fdcb5c92b591b5dadc49dfdd2a3b26b
[ "MIT" ]
null
null
null
proto/modbuscpp.cxx
trotill/11parts_CPP
53a69d516fdcb5c92b591b5dadc49dfdd2a3b26b
[ "MIT" ]
null
null
null
proto/modbuscpp.cxx
trotill/11parts_CPP
53a69d516fdcb5c92b591b5dadc49dfdd2a3b26b
[ "MIT" ]
null
null
null
/* * modbuscpp.cxx * * Created on: 14.11.2018 * Author: root */ #include "modbuscpp.h" eErrorTp modbuscpp_client::ReadHoldingReg(u8 slave_addr,u32 addr,u32 countItem,buffer & buf,u8 try_count){ buf.create(countItem*2); eErrorTp err= Read(slave_addr,addr,countItem,(u16*)buf.p(),MBUS_REGISTER,try_count); if (err==ERROR){ buf.clear(); } return err; } eErrorTp modbuscpp_client::ReadInputReg(u8 slave_addr,u32 addr,u32 countItem,buffer & buf,u8 try_count){ buf.create(countItem*2); eErrorTp err=Read(slave_addr,addr,countItem,(u16*)buf.p(),MBUS_INPUT_REGISTER,try_count); if (err==ERROR){ buf.clear(); } return err; } eErrorTp modbuscpp_client::ReadCoil(u8 slave_addr,u32 addr,u32 countItem,buffer & buf,u8 try_count){ buf.create(countItem); eErrorTp err= Read(slave_addr,addr,countItem,(u16*)buf.p(),MBUS_BITS,try_count); if (err==ERROR){ buf.clear(); } return err; } eErrorTp modbuscpp_client::ReadDiscreteInput(u8 slave_addr,u32 addr,u32 countItem,buffer & buf,u8 try_count){ buf.create(countItem); eErrorTp err= Read(slave_addr,addr,countItem,(u16*)buf.p(),MBUS_INPUT_BITS,try_count); if (err==ERROR){ buf.clear(); } return err; } eErrorTp modbuscpp_client::Read(u8 slave_addr,u32 addr,u32 countItem,u16 * dest,tpModBusData type,u8 try_count){ if (ctx==NULL) return ERROR; int rc=-1; modbus_flush(ctx); modbus_set_slave(ctx, slave_addr); // u8 * buf8=(u8*)calloc(1,count_regs); //u16 size8=count_regs; //for (u32 j=0;j<count_regs;j++) // buf8[j]=(u8)dest[j]; for (u8 z=0;z<try_count;z++){ switch (type){ case MBUS_REGISTERS: case MBUS_REGISTER: //3 (0x03) — чтение значений из нескольких регистров хранения (Read Holding Registers) rc = modbus_read_registers(ctx, addr, countItem, dest); break; case MBUS_BITS: //1 (0x01) — чтение значений из нескольких регистров флагов (Read Coil Status). rc = modbus_read_bits(ctx, addr, countItem,(u8*)dest); break; case MBUS_INPUT_BITS: //2 (0x02) — чтение значений из нескольких дискретных входов (Read Discrete Inputs). rc = modbus_read_input_bits(ctx, addr, countItem, (u8*)dest); break; case MBUS_INPUT_REGISTER: //4 (0x04) — чтение значений из нескольких регистров ввода (Read Input Registers). rc = modbus_read_input_registers(ctx, addr, countItem, dest); break; default: mbp.GPRINT(NORMAL_LEVEL,"Incorrect MBUS type\n"); } if (rc != -1) break; mbp.GPRINT(NORMAL_LEVEL,"Addr 0x%02x read error, try again, delay %dmS\n",slave_addr,sw_delay); mdelay(sw_delay); } // free(buf8); if (rc == -1) { mbp.GPRINT(NORMAL_LEVEL,"Error %d while reading: %s, addr 0x%02x\n", errno, modbus_strerror(errno),slave_addr); return ERROR; } return NO_ERROR; } eErrorTp modbuscpp_client::WriteMultipleReg(u8 slave_addr,u32 addr,u32 countItem,buffer & buf){ if (buf.size()<(countItem*2)){ mbp.GPRINT(NORMAL_LEVEL,"Incorrect write buffer size\n"); return ERROR; } return Write(slave_addr,addr,countItem,(u16*)buf.p(),MBUS_REGISTERS); } eErrorTp modbuscpp_client::WriteSingleReg(u8 slave_addr,u32 addr,buffer & buf){ if (buf.size()<2){ mbp.GPRINT(NORMAL_LEVEL,"Incorrect write buffer size\n"); return ERROR; } return Write(slave_addr,addr,1,(u16*)buf.p(),MBUS_REGISTER); } eErrorTp modbuscpp_client::WriteMultipleCoil(u8 slave_addr,u32 addr,u32 countItem,buffer & buf){ if (buf.size()<(countItem)){ mbp.GPRINT(NORMAL_LEVEL,"Incorrect write buffer size\n"); return ERROR; } return Write(slave_addr,addr,countItem,(u16*)buf.p(),MBUS_BITS); } eErrorTp modbuscpp_client::WriteSingleCoil(u8 slave_addr,u32 addr,buffer & buf){ if (buf.size()<1){ mbp.GPRINT(NORMAL_LEVEL,"Incorrect write buffer size\n"); return ERROR; } return Write(slave_addr,addr,1,(u16*)buf.p(),MBUS_BIT); } eErrorTp modbuscpp_client::Write(u8 slave_addr,u32 addr,u32 size16,u16 * buf,tpModBusData type){ if (ctx==NULL) return ERROR; int rc=-1; //printf("modbus_flush(ctx);\n"); modbus_flush(ctx); //printf("modbus_set_slave(ctx, slave_addr);\n"); modbus_set_slave(ctx, slave_addr); //printf("u8 * buf8=(u8*)calloc(1,size16);\n"); //u8 * buf8=(u8*)calloc(1,size16); //u16 size8=size16; //for (u32 j=0;j<size16;j++) // buf8[j]=(u8)buf[j]; switch (type){ case MBUS_INPUT_REGISTER: case MBUS_REGISTER:{ //6 (0x06) — запись значения в один регистр хранения (Preset Single Register). u32 reg=0; memcpy(&reg,(u8*)buf,2); //printf("Write 0x%02x reg 0x%04x\n",addr,reg); rc = modbus_write_register(ctx, addr,reg); //printf("MBUS_REGISTER rc %d\n",rc); } break; case MBUS_REGISTERS:{ //16 (0x10) — запись значений в несколько регистров хранения (Preset Multiple Registers) rc = modbus_write_registers(ctx, addr,size16,buf); } break; case MBUS_BIT:{ //5 (0x05) — запись значения одного флага (Force Single Coil). u32 status=0; memcpy(&status,(u8*)buf,1); rc = modbus_write_bit(ctx, addr, status); } break; case MBUS_INPUT_BITS: case MBUS_BITS:{ //The buf array must contains bytes set to TRUE or FALSE. //15 (0x0F) — запись значений в несколько регистров флагов (Force Multiple Coils) //printhex(buf8,size8,16); rc = modbus_write_bits(ctx, addr, size16,(u8*)buf); } break; default:{ mbp.GPRINT(NORMAL_LEVEL,"Incorrect MBUS type\n"); } } // free(buf8); if (rc == -1) { mbp.GPRINT(NORMAL_LEVEL,"Error %d while write: %s\n", errno, modbus_strerror(errno)); return ERROR; } return NO_ERROR; } modbuscpp_client::modbuscpp_client(eDebugTp debugLevel) { mbp.SourceStr="modbus"; mbp.ObjPref="modbus"; mbp.debug_level=debugLevel; } modbuscpp_client::modbuscpp_client(void) { mbp.SourceStr="modbus"; mbp.ObjPref="modbus"; mbp.debug_level=NORMAL_LEVEL; } modbuscpp_client::~modbuscpp_client(void){ if (ctx!=NULL){ modbus_close(ctx); modbus_free(ctx); } if (__gpio_RTS_MODBUS!=NULL){ delete __gpio_RTS_MODBUS; __gpio_RTS_MODBUS=NULL; } } // eErrorTp modbuscpp_client::InitMaster(string ttyport,u32 baudrate,char parity, int data_bit, int stop_bit){ /* * The baud argument specifies the baud rate of the communication, eg. 9600, 19200, 57600, 115200, etc. The parity argument can have one of the following values N for none E for even O for odd The data_bits argument specifies the number of bits of data, the allowed values are 5, 6, 7 and 8. The stop_bits argument specifies the bits of stop, the allowed values are 1 and 2. */ if (ctx!=NULL) return ERROR; ctx = modbus_new_rtu(ttyport.c_str(), baudrate, parity, data_bit, stop_bit); modbus_rtu_set_serial_mode(ctx, MODBUS_RTU_RS485); //modbus_set_slave(ctx, SERVER_ID); if (modbus_connect(ctx) == -1) { mbp.GPRINT(NORMAL_LEVEL,"Connection failed: %s\n",modbus_strerror(errno)); modbus_free(ctx); ctx=NULL; return ERROR; } else return NO_ERROR; } eErrorTp modbuscpp_client::reconnect(){ if (netMode){ mbp.GPRINT(NORMAL_LEVEL,"Do reconnect\n"); modbus_close(ctx); modbus_free(ctx); ctx=NULL; ctx = modbus_new_tcp(slaveip.c_str(), port); if (modbus_connect(ctx) == -1) { mbp.GPRINT(NORMAL_LEVEL,"reconnect failed: %s\n",modbus_strerror(errno)); modbus_close(ctx); modbus_free(ctx); ctx=NULL; return ERROR; } else{ mbp.GPRINT(NORMAL_LEVEL,"Reconnect success\n"); return NO_ERROR; } } else return ERROR; } eErrorTp modbuscpp_client::InitMaster(string slaveip,u16 port){ if (ctx!=NULL) return ERROR; netMode=true; this->slaveip=slaveip; this->port=port; ctx = modbus_new_tcp(slaveip.c_str(), port); //modbus_set_slave(ctx, SERVER_ID); if (modbus_connect(ctx) == -1) { mbp.GPRINT(NORMAL_LEVEL,"Connection failed: %s\n",modbus_strerror(errno)); modbus_free(ctx); ctx=NULL; return ERROR; } else return NO_ERROR; } eErrorTp modbuscpp_client::EnableDebug(void){ if (ctx==NULL) return ERROR; modbus_set_debug(ctx, true); return NO_ERROR; } eErrorTp modbuscpp_client::DisableDebug(void){ if (ctx==NULL) return ERROR; modbus_set_debug(ctx, false); return NO_ERROR; } //sw_delay void modbuscpp_client::SetSwDelay(u32 timeout_msec){ sw_delay=timeout_msec; } eErrorTp modbuscpp_client::SetTimeout(u32 timeout_sec,u32 timeout_usec){ if (ctx==NULL) return ERROR; //modbus_set_byte_timeout(ctx, byte_timeout); modbus_set_response_timeout(ctx, timeout_sec,timeout_usec); return NO_ERROR; } eErrorTp modbuscpp_client::SetupLevelRTS(u32 mode){ if (ctx==NULL) return ERROR; //MODBUS_RTU_RTS_DOWN //MODBUS_RTU_RTS_UP //MODBUS_RTU_RTS_NONE modbus_rtu_set_rts(ctx, mode); return NO_ERROR; } void modbuscpp_client::rts_sw (modbus_t * ctx, int on){ //if (RTS_GP==0) //return; if (on){ __gpio_RTS_MODBUS->set("1"); //system("echo 1 > /sys/class/gpio/gpio23/value"); //GpioOnOff(23,1); //printf("RTS on\n"); } else{ __gpio_RTS_MODBUS->set("0"); //system("echo 0 > /sys/class/gpio/gpio23/value"); //GpioOnOff(23,0); //printf("RTS off\n"); } } eErrorTp modbuscpp_client::SetupSoftwareRTS(int rts_gpio,int us){ if (ctx==NULL) return ERROR; if (__gpio_RTS_MODBUS==NULL){ //GpioOutInit(rts_gpio,0); //RTS_GP=rts_gpio; //string num,string direct,string value) __gpio_RTS_MODBUS=new gpio(IntToStr(rts_gpio),"out","0"); } modbus_rtu_set_custom_rts(ctx, rts_sw); modbus_rtu_set_rts_delay(ctx,us); return NO_ERROR; } eErrorTp modbuscpp_client::ReportSlaveID(u8 slave_addr,u8 * dest) { /* int rc=-1; modbus_flush(ctx); modbus_set_slave(ctx, slave_addr); rc=modbus_report_slave_id(ctx,dest); if (rc > 1) { mbp.GPRINT(NORMAL_LEVEL,"Run Status Indicator: %s\n", dest[1] ? "ON" : "OFF"); return NO_ERROR; } else mbp.GPRINT(NORMAL_LEVEL,"Error report slave %s\n"); */ return ERROR; }
26.852941
115
0.683859
trotill
a793348f214ca91b580846531917c1fe86847081
643
hpp
C++
src/org/apache/poi/poifs/filesystem/Entry.hpp
pebble2015/cpoi
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
[ "Apache-2.0" ]
null
null
null
src/org/apache/poi/poifs/filesystem/Entry.hpp
pebble2015/cpoi
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
[ "Apache-2.0" ]
null
null
null
src/org/apache/poi/poifs/filesystem/Entry.hpp
pebble2015/cpoi
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
[ "Apache-2.0" ]
null
null
null
// Generated from /POI/java/org/apache/poi/poifs/filesystem/Entry.java #pragma once #include <fwd-POI.hpp> #include <java/lang/fwd-POI.hpp> #include <org/apache/poi/poifs/filesystem/fwd-POI.hpp> #include <java/lang/Object.hpp> struct poi::poifs::filesystem::Entry : public virtual ::java::lang::Object { virtual ::java::lang::String* getName() = 0; virtual bool isDirectoryEntry() = 0; virtual bool isDocumentEntry() = 0; virtual DirectoryEntry* getParent() = 0; virtual bool delete_() = 0; virtual bool renameTo(::java::lang::String* newName) = 0; // Generated static ::java::lang::Class *class_(); };
27.956522
70
0.681182
pebble2015
a794963a552a3ead31fa6f4b00eb7fda25e2cf2a
1,155
cpp
C++
src/SoundManager.cpp
StianAndreOlsen/ColorVario
c10dbf13dcef09121bf1817a6d07606ef5a89da4
[ "MIT" ]
1
2021-05-05T21:37:55.000Z
2021-05-05T21:37:55.000Z
src/SoundManager.cpp
StianAndreOlsen/ColorVario
c10dbf13dcef09121bf1817a6d07606ef5a89da4
[ "MIT" ]
null
null
null
src/SoundManager.cpp
StianAndreOlsen/ColorVario
c10dbf13dcef09121bf1817a6d07606ef5a89da4
[ "MIT" ]
4
2019-11-06T06:25:47.000Z
2021-05-05T21:39:12.000Z
#include "SoundManager.h" #include "dlog.h" #include "TizenError.h" Kystsoft::SoundManager::~SoundManager() noexcept { try { setVolume(initialVolume); } catch (std::exception& e) { dlog(DLOG_ERROR) << e.what(); } } double Kystsoft::SoundManager::volume() const { int ivolume = 0; int error = sound_manager_get_volume(soundType, &ivolume); if (error != SOUND_MANAGER_ERROR_NONE) throw TizenError("sound_manager_get_volume", error); return double(ivolume) / maxVolume(); } void Kystsoft::SoundManager::setVolume(double volume) { if (volume < 0) return; if (volume > 1) volume = 1; if (initialVolume < 0) initialVolume = this->volume(); int ivolume = int(volume * maxVolume() + 0.5); int error = sound_manager_set_volume(soundType, ivolume); if (error != SOUND_MANAGER_ERROR_NONE) throw TizenError("sound_manager_set_volume", error); } int Kystsoft::SoundManager::maxVolume() const { int maxVolume = 0; int error = sound_manager_get_max_volume(soundType, &maxVolume); if (error != SOUND_MANAGER_ERROR_NONE) throw TizenError("sound_manager_get_max_volume", error); return maxVolume; }
27.5
66
0.707359
StianAndreOlsen
a795e580fe7c436cfa6e66c50ccf996b6e7590d7
709
cpp
C++
src/MintFunction.cpp
ice-bit/Mint
20622a0acc278cf732f7e8bfa293a6ca2af265e0
[ "MIT" ]
null
null
null
src/MintFunction.cpp
ice-bit/Mint
20622a0acc278cf732f7e8bfa293a6ca2af265e0
[ "MIT" ]
null
null
null
src/MintFunction.cpp
ice-bit/Mint
20622a0acc278cf732f7e8bfa293a6ca2af265e0
[ "MIT" ]
1
2022-03-26T13:29:18.000Z
2022-03-26T13:29:18.000Z
#include "MintFunction.h" #include "Environment.h" #include "Interpreter.h" std::string MintFunction::to_string() { return std::string("<fn " + declaration->name.lexeme + ">"); } unsigned short MintFunction::arity() { return declaration->params.size(); } std::any MintFunction::call(Interpreter &interpreter, std::vector<std::any> arguments) { auto env = std::make_shared<Environment>(closure); for(auto i = 0UL; i < declaration->params.size(); i++) env->define(declaration->params[i].lexeme, arguments[i]); try { interpreter.execute_block(declaration->body, env); } catch(MintReturn& returnValue) { return returnValue.value; } return nullptr; }
25.321429
88
0.667137
ice-bit
a79708b48b309ba70208147c72f08cf2057126e7
10,561
cpp
C++
src/mongo/s/write_ops/batched_insert_request.cpp
fjonath1/mongodb-ros-osx
31a58cab426b68ce85ef231200ff45d4bd691d32
[ "Apache-2.0" ]
null
null
null
src/mongo/s/write_ops/batched_insert_request.cpp
fjonath1/mongodb-ros-osx
31a58cab426b68ce85ef231200ff45d4bd691d32
[ "Apache-2.0" ]
null
null
null
src/mongo/s/write_ops/batched_insert_request.cpp
fjonath1/mongodb-ros-osx
31a58cab426b68ce85ef231200ff45d4bd691d32
[ "Apache-2.0" ]
null
null
null
/** * Copyright (C) 2013 10gen Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, version 3, * as published by the Free Software Foundation. * * 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "mongo/s/write_ops/batched_insert_request.h" #include "mongo/db/field_parser.h" #include "mongo/util/mongoutils/str.h" namespace mongo { using mongoutils::str::stream; const std::string BatchedInsertRequest::BATCHED_INSERT_REQUEST = "insert"; const BSONField<std::string> BatchedInsertRequest::collName("insert"); const BSONField<std::vector<BSONObj> > BatchedInsertRequest::documents("documents"); const BSONField<BSONObj> BatchedInsertRequest::writeConcern("writeConcern"); const BSONField<bool> BatchedInsertRequest::ordered("ordered", true); const BSONField<string> BatchedInsertRequest::shardName("shardName"); const BSONField<ChunkVersion> BatchedInsertRequest::shardVersion("shardVersion"); const BSONField<long long> BatchedInsertRequest::session("session"); BatchedInsertRequest::BatchedInsertRequest() { clear(); } BatchedInsertRequest::~BatchedInsertRequest() { } bool BatchedInsertRequest::isValid(std::string* errMsg) const { std::string dummy; if (errMsg == NULL) { errMsg = &dummy; } // All the mandatory fields must be present. if (!_isCollNameSet) { *errMsg = stream() << "missing " << collName.name() << " field"; return false; } if (!_isDocumentsSet) { *errMsg = stream() << "missing " << documents.name() << " field"; return false; } return true; } BSONObj BatchedInsertRequest::toBSON() const { BSONObjBuilder builder; if (_isCollNameSet) builder.append(collName(), _collName); if (_isDocumentsSet) { BSONArrayBuilder documentsBuilder(builder.subarrayStart(documents())); for (std::vector<BSONObj>::const_iterator it = _documents.begin(); it != _documents.end(); ++it) { documentsBuilder.append(*it); } documentsBuilder.done(); } if (_isWriteConcernSet) builder.append(writeConcern(), _writeConcern); if (_isOrderedSet) builder.append(ordered(), _ordered); if (_isShardNameSet) builder.append(shardName(), _shardName); if (_shardVersion.get()) { // ChunkVersion wants to be an array. builder.append(shardVersion(), static_cast<BSONArray>(_shardVersion->toBSON())); } if (_isSessionSet) builder.append(session(), _session); return builder.obj(); } bool BatchedInsertRequest::parseBSON(const BSONObj& source, string* errMsg) { clear(); std::string dummy; if (!errMsg) errMsg = &dummy; FieldParser::FieldState fieldState; fieldState = FieldParser::extract(source, collName, &_collName, errMsg); if (fieldState == FieldParser::FIELD_INVALID) return false; _isCollNameSet = fieldState == FieldParser::FIELD_SET; fieldState = FieldParser::extract(source, documents, &_documents, errMsg); if (fieldState == FieldParser::FIELD_INVALID) return false; _isDocumentsSet = fieldState == FieldParser::FIELD_SET; fieldState = FieldParser::extract(source, writeConcern, &_writeConcern, errMsg); if (fieldState == FieldParser::FIELD_INVALID) return false; _isWriteConcernSet = fieldState == FieldParser::FIELD_SET; fieldState = FieldParser::extract(source, ordered, &_ordered, errMsg); if (fieldState == FieldParser::FIELD_INVALID) return false; _isOrderedSet = fieldState == FieldParser::FIELD_SET; fieldState = FieldParser::extract(source, shardName, &_shardName, errMsg); if (fieldState == FieldParser::FIELD_INVALID) return false; _isShardNameSet = fieldState == FieldParser::FIELD_SET; ChunkVersion* tempChunkVersion = NULL; fieldState = FieldParser::extract(source, shardVersion, &tempChunkVersion, errMsg); if (fieldState == FieldParser::FIELD_INVALID) return false; if (fieldState == FieldParser::FIELD_SET) _shardVersion.reset(tempChunkVersion); fieldState = FieldParser::extract(source, session, &_session, errMsg); if (fieldState == FieldParser::FIELD_INVALID) return false; _isSessionSet = fieldState == FieldParser::FIELD_SET; return true; } void BatchedInsertRequest::clear() { _collName.clear(); _isCollNameSet = false; _documents.clear(); _isDocumentsSet =false; _writeConcern = BSONObj(); _isWriteConcernSet = false; _ordered = false; _isOrderedSet = false; _shardName.clear(); _isShardNameSet = false; _shardVersion.reset(); _session = 0; _isSessionSet = false; } void BatchedInsertRequest::cloneTo(BatchedInsertRequest* other) const { other->clear(); other->_collName = _collName; other->_isCollNameSet = _isCollNameSet; for(std::vector<BSONObj>::const_iterator it = _documents.begin(); it != _documents.end(); ++it) { other->addToDocuments(*it); } other->_isDocumentsSet = _isDocumentsSet; other->_writeConcern = _writeConcern; other->_isWriteConcernSet = _isWriteConcernSet; other->_ordered = _ordered; other->_isOrderedSet = _isOrderedSet; other->_shardName = _shardName; other->_isShardNameSet = _isShardNameSet; if (other->_shardVersion.get()) _shardVersion->cloneTo(other->_shardVersion.get()); other->_session = _session; other->_isSessionSet = _isSessionSet; } std::string BatchedInsertRequest::toString() const { return toBSON().toString(); } void BatchedInsertRequest::setCollName(const StringData& collName) { _collName = collName.toString(); _isCollNameSet = true; } void BatchedInsertRequest::unsetCollName() { _isCollNameSet = false; } bool BatchedInsertRequest::isCollNameSet() const { return _isCollNameSet; } const std::string& BatchedInsertRequest::getCollName() const { dassert(_isCollNameSet); return _collName; } void BatchedInsertRequest::setDocuments(const std::vector<BSONObj>& documents) { for (std::vector<BSONObj>::const_iterator it = documents.begin(); it != documents.end(); ++it) { addToDocuments((*it).getOwned()); } _isDocumentsSet = documents.size() > 0; } void BatchedInsertRequest::addToDocuments(const BSONObj& documents) { _documents.push_back(documents); _isDocumentsSet = true; } void BatchedInsertRequest::unsetDocuments() { _documents.clear(); _isDocumentsSet = false; } bool BatchedInsertRequest::isDocumentsSet() const { return _isDocumentsSet; } size_t BatchedInsertRequest::sizeDocuments() const { return _documents.size(); } const std::vector<BSONObj>& BatchedInsertRequest::getDocuments() const { dassert(_isDocumentsSet); return _documents; } const BSONObj& BatchedInsertRequest::getDocumentsAt(size_t pos) const { dassert(_isDocumentsSet); dassert(_documents.size() > pos); return _documents.at(pos); } void BatchedInsertRequest::setWriteConcern(const BSONObj& writeConcern) { _writeConcern = writeConcern.getOwned(); _isWriteConcernSet = true; } void BatchedInsertRequest::unsetWriteConcern() { _isWriteConcernSet = false; } bool BatchedInsertRequest::isWriteConcernSet() const { return _isWriteConcernSet; } const BSONObj& BatchedInsertRequest::getWriteConcern() const { dassert(_isWriteConcernSet); return _writeConcern; } void BatchedInsertRequest::setOrdered(bool ordered) { _ordered = ordered; _isOrderedSet = true; } void BatchedInsertRequest::unsetOrdered() { _isOrderedSet = false; } bool BatchedInsertRequest::isOrderedSet() const { return _isOrderedSet; } bool BatchedInsertRequest::getOrdered() const { if (_isOrderedSet) { return _ordered; } else { return ordered.getDefault(); } } void BatchedInsertRequest::setShardName( const StringData& shardName ) { _shardName = shardName.toString(); _isShardNameSet = true; } void BatchedInsertRequest::unsetShardName() { _isShardNameSet = false; } bool BatchedInsertRequest::isShardNameSet() const { return _isShardNameSet; } const string& BatchedInsertRequest::getShardName() const { dassert( _isShardNameSet ); return _shardName; } void BatchedInsertRequest::setShardVersion(const ChunkVersion& shardVersion) { auto_ptr<ChunkVersion> temp(new ChunkVersion); shardVersion.cloneTo(temp.get()); _shardVersion.reset(temp.release()); } void BatchedInsertRequest::unsetShardVersion() { _shardVersion.reset(); } bool BatchedInsertRequest::isShardVersionSet() const { return _shardVersion.get() != NULL; } const ChunkVersion& BatchedInsertRequest::getShardVersion() const { dassert(_shardVersion.get()); return *_shardVersion; } void BatchedInsertRequest::setSession(long long session) { _session = session; _isSessionSet = true; } void BatchedInsertRequest::unsetSession() { _isSessionSet = false; } bool BatchedInsertRequest::isSessionSet() const { return _isSessionSet; } long long BatchedInsertRequest::getSession() const { dassert(_isSessionSet); return _session; } } // namespace mongo
31.061765
92
0.646908
fjonath1
a79857f6640f9bccb3d865e51d1730d80a9300d2
15,716
cpp
C++
src/ves/Testing/TestDrawPlane.cpp
Eduardop/VES
1d4163989a734f273d46af3b2f88339121d2bfee
[ "Apache-2.0" ]
3
2016-07-21T19:48:47.000Z
2022-03-16T11:19:07.000Z
src/ves/Testing/TestDrawPlane.cpp
Eduardop/VES
1d4163989a734f273d46af3b2f88339121d2bfee
[ "Apache-2.0" ]
1
2021-04-07T08:05:47.000Z
2021-04-07T08:05:47.000Z
src/ves/Testing/TestDrawPlane.cpp
Eduardop/VES
1d4163989a734f273d46af3b2f88339121d2bfee
[ "Apache-2.0" ]
2
2016-03-16T15:36:54.000Z
2018-01-07T07:23:30.000Z
/*======================================================================== VES --- VTK OpenGL ES Rendering Toolkit http://www.kitware.com/ves Copyright 2011 Kitware, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ========================================================================*/ #include <iostream> #include <sstream> #include <fstream> #include <cassert> #include <cstdlib> #include <cstdio> #include <cstring> #include <vesActor.h> #include <vesCamera.h> #include <vesMapper.h> #include <vesMaterial.h> #include <vesModelViewUniform.h> #include <vesProjectionUniform.h> #include <vesRenderer.h> #include <vesShader.h> #include <vesShaderProgram.h> #include <vesUniform.h> #include <vesVertexAttribute.h> #include <vesVertexAttributeKeys.h> #include <vesViewport.h> #include <X11/Xlib.h> #include <X11/Xutil.h> #include <X11/keysym.h> #include <GLES2/gl2.h> #include <EGL/egl.h> //---------------------------------------------------------------------------- namespace { class vesTestDrawPlane { public: vesTestDrawPlane() : m_modelViewUniform(new vesModelViewUniform()), m_projectionUniform(new vesProjectionUniform()), m_positionVertexAttribute(new vesPositionVertexAttribute()), m_normalVertexAttribute(new vesNormalVertexAttribute()), m_colorVertexAttribute(new vesColorVertexAttribute()), m_vertexShader(new vesShader(vesShader::Vertex)), m_fragmentShader(new vesShader(vesShader::Fragment)), m_shaderProgram(vesShaderProgram::Ptr(new vesShaderProgram())), m_material(vesMaterial::Ptr(new vesMaterial())), m_mapper(vesMapper::Ptr(new vesMapper())), m_actor(vesActor::Ptr(new vesActor())), m_renderer(vesRenderer::Ptr(new vesRenderer())) { } ~vesTestDrawPlane() { } std::string sourceDirectory() { return this->SourceDirectory; } void setSourceDirectory(std::string dir) { this->SourceDirectory = dir; } std::string dataDirectory() { return this->DataDirectory; } void setDataDirectory(std::string dir) { this->DataDirectory = dir; } bool isTesting() { return this->IsTesting; } void setTesting(bool testing) { this->IsTesting = testing; } void init() { const std::string vertexShaderSource = "uniform highp mat4 modelViewMatrix;\n \ uniform highp mat4 projectionMatrix;\n \ attribute highp vec4 vertexPosition;\n \ attribute mediump vec4 vertexColor;\n \ varying mediump vec4 varColor;\n \ void main()\n \ {\n \ gl_Position = projectionMatrix * modelViewMatrix * vertexPosition;\n \ varColor = vertexColor;\n \ }"; const std::string fragmentShaderSource = "varying mediump vec4 varColor;\n \ void main()\n \ {\n \ gl_FragColor = varColor;\n \ }"; this->m_vertexShader->setShaderSource(vertexShaderSource); this->m_fragmentShader->setShaderSource(fragmentShaderSource); this->m_shaderProgram->addShader(this->m_vertexShader); this->m_shaderProgram->addShader(this->m_fragmentShader); this->m_shaderProgram->addUniform(this->m_modelViewUniform); this->m_shaderProgram->addUniform(this->m_projectionUniform); this->m_shaderProgram->addVertexAttribute(this->m_positionVertexAttribute, vesVertexAttributeKeys::Position); this->m_shaderProgram->addVertexAttribute(this->m_normalVertexAttribute, vesVertexAttributeKeys::Normal); this->m_shaderProgram->addVertexAttribute(this->m_colorVertexAttribute, vesVertexAttributeKeys::Color); this->m_material->addAttribute(this->m_shaderProgram); this->m_mapper->setGeometryData(this->createPlane()); this->m_actor->setMapper(this->m_mapper); this->m_actor->setMaterial(this->m_material); this->m_renderer->addActor(this->m_actor); this->m_renderer->camera()->setParallelProjection(false); this->m_renderer->setBackgroundColor(0.0, 0.2, 0.8); } vesSharedPtr<vesGeometryData> createPlane() { vesGeometryData::Ptr geometryData (new vesGeometryData()); vesSourceDataP3N3C3f::Ptr sourceData(new vesSourceDataP3N3C3f()); vesVector4f topLeftColor = vesVector4f(0.5f, 0.0f, 0.0f, 1.0f); vesVector4f bottomRightColor = vesVector4f(0.0f, 0.0f, 0.5f, 1.0f); vesVector4f color = vesVector4f(0.5f, 0.5f, 0.5f, 1.0f); // Points. vesVertexDataP3N3C3f v1; v1.m_position = vesVector3f(-1.0f, -1.0f, 0.0f); v1.m_normal = vesVector3f(0.0f, 0.0f, 1.0f); v1.m_color = vesVector3f(color[0], color[1], color[2]); vesVertexDataP3N3C3f v2; v2.m_position = vesVector3f(1.0f, -1.0f, 0.0f); v2.m_normal = vesVector3f(0.0f, 0.0f, 1.0f); v2.m_color = vesVector3f(bottomRightColor[0], bottomRightColor[1], bottomRightColor[2]); vesVertexDataP3N3C3f v3; v3.m_position = vesVector3f(1.0f, 1.0f, 0.0f); v3.m_normal = vesVector3f(0.0f, 0.0f, 1.0f); v3.m_color = vesVector3f(color[0], color[1], color[2]); vesVertexDataP3N3C3f v4; v4.m_position = vesVector3f(-1.0f, 1.0f, 0.0f); v4.m_normal = vesVector3f(0.0f, 0.0f, 1.0f); v4.m_color = vesVector3f(topLeftColor[0], topLeftColor[1], topLeftColor[2]); sourceData->pushBack(v1); sourceData->pushBack(v2); sourceData->pushBack(v3); sourceData->pushBack(v4); // Triangle cells. vesPrimitive::Ptr triangles (new vesPrimitive()); vesSharedPtr< vesIndices<unsigned short> > indices (new vesIndices<unsigned short>()); indices->pushBackIndices(0, 3, 2); indices->pushBackIndices(1, 0, 2); triangles->setVesIndices(indices); triangles->setPrimitiveType(vesPrimitiveRenderType::Triangles); triangles->setIndexCount(3); triangles->setIndicesValueType(vesPrimitiveIndicesValueType::UnsignedShort); geometryData->setName("PlaneGeometryData"); geometryData->addSource(sourceData); geometryData->addPrimitive(triangles); return geometryData; } void render() { this->m_renderer->render(); } void resizeView(int winWidth, int winHeight) { this->m_renderer->resize(winWidth, winHeight, 1.0f); } void resetView() { // dolly so that scene fits window this->m_renderer->resetCamera(); } void toggleVisibility() { this->m_actor->setVisible(!this->m_actor->isVisible()); this->render(); } void toggleColorVisibility() { this->m_material->enableVertexColor(!this->m_material->isEnabledVertexColor()); this->render(); } private: std::string SourceDirectory; std::string DataDirectory; bool IsTesting; vesSharedPtr<vesModelViewUniform> m_modelViewUniform; vesSharedPtr<vesProjectionUniform> m_projectionUniform; vesSharedPtr<vesPositionVertexAttribute> m_positionVertexAttribute; vesSharedPtr<vesNormalVertexAttribute> m_normalVertexAttribute; vesSharedPtr<vesColorVertexAttribute> m_colorVertexAttribute; vesSharedPtr<vesTextureCoordinateVertexAttribute> m_textureCoodinateAttribute; vesSharedPtr<vesGeometryData> m_backgroundPlaneData; vesShader::Ptr m_vertexShader; vesShader::Ptr m_fragmentShader; vesShaderProgram::Ptr m_shaderProgram; vesMaterial::Ptr m_material; vesMapper::Ptr m_mapper; vesActor::Ptr m_actor; vesRenderer::Ptr m_renderer; }; //---------------------------------------------------------------------------- vesTestDrawPlane* testDrawPlane; //---------------------------------------------------------------------------- bool DoTesting() { testDrawPlane->render(); return true; } //---------------------------------------------------------------------------- void InitRendering() { testDrawPlane->init(); } //---------------------------------------------------------------------------- bool InitTest(int argc, char* argv[]) { if (argc < 2) { printf("Usage: %s <path to VES source directory> [path to testing data directory]\n", argv[0]); return false; } testDrawPlane = new vesTestDrawPlane(); testDrawPlane->setSourceDirectory(argv[1]); if (argc == 3) { testDrawPlane->setDataDirectory(argv[2]); testDrawPlane->setTesting(true); } return true; } //---------------------------------------------------------------------------- void FinalizeTest() { delete testDrawPlane; } }; // end namespace //---------------------------------------------------------------------------- /* * Create an RGB, double-buffered X window. * Return the window and context handles. */ static void make_x_window(Display *x_dpy, EGLDisplay egl_dpy, const char *name, int x, int y, int width, int height, Window *winRet, EGLContext *ctxRet, EGLSurface *surfRet) { static const EGLint attribs[] = { EGL_RED_SIZE, 1, EGL_GREEN_SIZE, 1, EGL_BLUE_SIZE, 1, EGL_DEPTH_SIZE, 1, EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT, EGL_NONE }; static const EGLint ctx_attribs[] = { EGL_CONTEXT_CLIENT_VERSION, 2, EGL_NONE }; int scrnum; XSetWindowAttributes attr; unsigned long mask; Window root; Window win; XVisualInfo *visInfo, visTemplate; int num_visuals; EGLContext ctx; EGLConfig config; EGLint num_configs; EGLint vid; scrnum = DefaultScreen( x_dpy ); root = RootWindow( x_dpy, scrnum ); if (!eglChooseConfig( egl_dpy, attribs, &config, 1, &num_configs)) { printf("Error: couldn't get an EGL visual config\n"); exit(1); } assert(config); assert(num_configs > 0); if (!eglGetConfigAttrib(egl_dpy, config, EGL_NATIVE_VISUAL_ID, &vid)) { printf("Error: eglGetConfigAttrib() failed\n"); exit(1); } /* The X window visual must match the EGL config */ visTemplate.visualid = vid; visInfo = XGetVisualInfo(x_dpy, VisualIDMask, &visTemplate, &num_visuals); if (!visInfo) { printf("Error: couldn't get X visual\n"); exit(1); } /* window attributes */ attr.background_pixel = 0; attr.border_pixel = 0; attr.colormap = XCreateColormap( x_dpy, root, visInfo->visual, AllocNone); attr.event_mask = StructureNotifyMask | ExposureMask | KeyPressMask | ButtonPressMask | ButtonReleaseMask | ButtonMotionMask; mask = CWBackPixel | CWBorderPixel | CWColormap | CWEventMask; win = XCreateWindow( x_dpy, root, 0, 0, width, height, 0, visInfo->depth, InputOutput, visInfo->visual, mask, &attr ); /* set hints and properties */ { XSizeHints sizehints; sizehints.x = x; sizehints.y = y; sizehints.width = width; sizehints.height = height; sizehints.flags = USSize | USPosition; XSetNormalHints(x_dpy, win, &sizehints); XSetStandardProperties(x_dpy, win, name, name, None, (char **)NULL, 0, &sizehints); } #if USE_FULL_GL /* XXX fix this when eglBindAPI() works */ eglBindAPI(EGL_OPENGL_API); #else eglBindAPI(EGL_OPENGL_ES_API); #endif ctx = eglCreateContext(egl_dpy, config, EGL_NO_CONTEXT, ctx_attribs ); if (!ctx) { printf("Error: eglCreateContext failed\n"); exit(1); } /* test eglQueryContext() */ { EGLint val; eglQueryContext(egl_dpy, ctx, EGL_CONTEXT_CLIENT_VERSION, &val); assert(val == 2); } *surfRet = eglCreateWindowSurface(egl_dpy, config, win, NULL); if (!*surfRet) { printf("Error: eglCreateWindowSurface failed\n"); exit(1); } /* sanity checks */ { EGLint val; eglQuerySurface(egl_dpy, *surfRet, EGL_WIDTH, &val); assert(val == width); eglQuerySurface(egl_dpy, *surfRet, EGL_HEIGHT, &val); assert(val == height); assert(eglGetConfigAttrib(egl_dpy, config, EGL_SURFACE_TYPE, &val)); assert(val & EGL_WINDOW_BIT); } XFree(visInfo); *winRet = win; *ctxRet = ctx; } bool haveLastMotion = false; int lastMotionX = 0; int lastMotionY = 0; int currentX = 0; int currentY = 0; static void event_loop(Display *dpy, Window win, EGLDisplay egl_dpy, EGLSurface egl_surf) { vesNotUsed(win); while (1) { int redraw = 1; XEvent event; XNextEvent(dpy, &event); switch (event.type) { case Expose: redraw = 1; break; case ConfigureNotify: testDrawPlane->resizeView(event.xconfigure.width, event.xconfigure.height); break; case ButtonPress: testDrawPlane->toggleVisibility(); break; case ButtonRelease: // Do nothing break; case MotionNotify: // Do nothing break; case KeyPress: testDrawPlane->toggleColorVisibility(); break; default: ; /*no-op*/ } if (redraw) { testDrawPlane->render(); eglSwapBuffers(egl_dpy, egl_surf); } } } int main(int argc, char *argv[]) { const int winWidth = 800, winHeight = 600; Display *x_dpy; Window win; EGLSurface egl_surf; EGLContext egl_ctx; EGLDisplay egl_dpy; char *dpyName = NULL; GLboolean printInfo = GL_FALSE; EGLint egl_major, egl_minor; const char *s; if (!InitTest(argc, argv)) { return -1; } x_dpy = XOpenDisplay(dpyName); if (!x_dpy) { printf("Error: couldn't open display %s\n", dpyName ? dpyName : getenv("DISPLAY")); return -1; } egl_dpy = eglGetDisplay(x_dpy); if (!egl_dpy) { printf("Error: eglGetDisplay() failed\n"); return -1; } if (!eglInitialize(egl_dpy, &egl_major, &egl_minor)) { printf("Error: eglInitialize() failed\n"); return -1; } s = eglQueryString(egl_dpy, EGL_VERSION); printf("EGL_VERSION = %s\n", s); s = eglQueryString(egl_dpy, EGL_VENDOR); printf("EGL_VENDOR = %s\n", s); s = eglQueryString(egl_dpy, EGL_EXTENSIONS); printf("EGL_EXTENSIONS = %s\n", s); s = eglQueryString(egl_dpy, EGL_CLIENT_APIS); printf("EGL_CLIENT_APIS = %s\n", s); make_x_window(x_dpy, egl_dpy, "OpenGL ES 2.x tri", 0, 0, winWidth, winHeight, &win, &egl_ctx, &egl_surf); XMapWindow(x_dpy, win); if (!eglMakeCurrent(egl_dpy, egl_surf, egl_surf, egl_ctx)) { printf("Error: eglMakeCurrent() failed\n"); return -1; } if (printInfo) { printf("GL_RENDERER = %s\n", (char *) glGetString(GL_RENDERER)); printf("GL_VERSION = %s\n", (char *) glGetString(GL_VERSION)); printf("GL_VENDOR = %s\n", (char *) glGetString(GL_VENDOR)); printf("GL_EXTENSIONS = %s\n", (char *) glGetString(GL_EXTENSIONS)); } InitRendering(); // render once testDrawPlane->resizeView(winWidth, winHeight); testDrawPlane->resetView(); testDrawPlane->render(); eglSwapBuffers(egl_dpy, egl_surf); // begin the event loop if not in testing mode bool testPassed = true; if (!testDrawPlane->isTesting()) { event_loop(x_dpy, win, egl_dpy, egl_surf); } else { testPassed = DoTesting(); } FinalizeTest(); eglDestroyContext(egl_dpy, egl_ctx); eglDestroySurface(egl_dpy, egl_surf); eglTerminate(egl_dpy); XDestroyWindow(x_dpy, win); XCloseDisplay(x_dpy); return testPassed ? 0 : 1; }
27.57193
128
0.63833
Eduardop
a79c04e33fcd9f4875515c9d5c272e2713de807b
2,647
cpp
C++
src/lib/codegen/builtin/datatypes.cpp
foozea/isana-lang
14f931552d9416005a95a8e7fd76682b8b7dfa74
[ "BSD-3-Clause" ]
1
2015-11-07T11:55:50.000Z
2015-11-07T11:55:50.000Z
src/lib/codegen/builtin/datatypes.cpp
foozea/isana-lang
14f931552d9416005a95a8e7fd76682b8b7dfa74
[ "BSD-3-Clause" ]
null
null
null
src/lib/codegen/builtin/datatypes.cpp
foozea/isana-lang
14f931552d9416005a95a8e7fd76682b8b7dfa74
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) 2012-, Tetsuo Fujii * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * - Neither the name of the author 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 "codegen/llvm.hpp" #include "env/resolver.hpp" namespace { isana::env::resolver_ref r = isana::env::resolver::get_instance(); void def_sexpr(void) { using namespace llvm; using namespace isana::codegen; type_list ms; ms.push_back(i8_ptr_type()); StructType *attr = defstruct::create(ms, "struct.sexpr.meta.attr"); ms.clear(); ms.push_back(i32_type()); ms.push_back(attr); StructType *meta = defstruct::create(ms, "struct.sexpr.meta"); ms.clear(); ms.push_back(i8_ptr_type()); StructType *as = defstruct::create(ms, "struct.sexpr.as"); ms.clear(); ms.push_back(meta); ms.push_back(as); StructType *sexpr = defstruct::create(ms, "struct.sexpr"); ms.clear(); ms.push_back(sexpr->getPointerTo()); ms.push_back(sexpr->getPointerTo()); defstruct::create(ms, "struct.sexpr.as.cell"); } } namespace isana { namespace codegen { namespace builtin { void init_datatypes(module_ref &m) { def_sexpr(); } } /* end of builtin */ } /* end of codegen */ } /* end of isana */
31.891566
78
0.715905
foozea
a79de9153ef882d450f75595f2691ad08c0a3729
4,032
cpp
C++
modules/galaxy/tasks/milkywaypointsconversiontask.cpp
hedbergj/OpenSpace
0125fb7a3be4d6e6529781522f5d9e9a826241fb
[ "MIT" ]
null
null
null
modules/galaxy/tasks/milkywaypointsconversiontask.cpp
hedbergj/OpenSpace
0125fb7a3be4d6e6529781522f5d9e9a826241fb
[ "MIT" ]
null
null
null
modules/galaxy/tasks/milkywaypointsconversiontask.cpp
hedbergj/OpenSpace
0125fb7a3be4d6e6529781522f5d9e9a826241fb
[ "MIT" ]
null
null
null
/***************************************************************************************** * * * OpenSpace * * * * Copyright (c) 2014-2020 * * * * 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 <modules/galaxy/tasks/milkywaypointsconversiontask.h> #include <openspace/documentation/documentation.h> #include <fstream> #include <iostream> #include <vector> namespace openspace { /*MilkywayPointsConversionTask::MilkywayPointsConversionTask( const std::string& inFilename, const std::string& outFilename) : _inFilename(inFilename) , _outFilename(outFilename) {}*/ MilkywayPointsConversionTask::MilkywayPointsConversionTask(const ghoul::Dictionary&) {} std::string MilkywayPointsConversionTask::description() { return std::string(); } void MilkywayPointsConversionTask::perform(const Task::ProgressCallback& progressCallback) { std::ifstream in(_inFilename, std::ios::in); std::ofstream out(_outFilename, std::ios::out | std::ios::binary); std::string format; int64_t nPoints; in >> format >> nPoints; size_t nFloats = nPoints * 7; std::vector<float> pointData(nFloats); float x; float y; float z; float r; float g; float b; float a; for (int64_t i = 0; i < nPoints; ++i) { in >> x >> y >> z >> r >> g >> b >> a; if (in.good()) { pointData[i * 7 + 0] = x; pointData[i * 7 + 1] = y; pointData[i * 7 + 2] = z; pointData[i * 7 + 3] = r; pointData[i * 7 + 4] = g; pointData[i * 7 + 5] = b; pointData[i * 7 + 6] = a; progressCallback(static_cast<float>(i + 1) / nPoints); } else { std::cout << "Failed to convert point data."; return; } } out.write(reinterpret_cast<char*>(&nPoints), sizeof(int64_t)); out.write(reinterpret_cast<char*>(pointData.data()), nFloats * sizeof(float)); in.close(); out.close(); } documentation::Documentation MilkywayPointsConversionTask::documentation() { return documentation::Documentation(); } } // namespace openspace
41.142857
90
0.506944
hedbergj
a79f1f8cd9775cf047c2b4e58c6a3971c470ef6a
5,680
cpp
C++
adapters-stk/test/periodic_bcs/periodic_mesh_nosubcells.cpp
hillyuan/Tianxin
57c7a5ed2466dda99471dec41cd85878335774d7
[ "BSD-3-Clause" ]
1
2022-03-22T03:49:50.000Z
2022-03-22T03:49:50.000Z
adapters-stk/test/periodic_bcs/periodic_mesh_nosubcells.cpp
hillyuan/Tianxin
57c7a5ed2466dda99471dec41cd85878335774d7
[ "BSD-3-Clause" ]
null
null
null
adapters-stk/test/periodic_bcs/periodic_mesh_nosubcells.cpp
hillyuan/Tianxin
57c7a5ed2466dda99471dec41cd85878335774d7
[ "BSD-3-Clause" ]
null
null
null
// @HEADER // *********************************************************************** // // Panzer: A partial differential equation assembly // engine for strongly coupled complex multiphysics systems // Copyright (2011) Sandia Corporation // // Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, // the U.S. Government retains certain rights in this software. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // 3. Neither the name of the Corporation nor the names of the // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY SANDIA CORPORATION "AS IS" AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SANDIA CORPORATION OR THE // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Questions? Contact Roger P. Pawlowski (rppawlo@sandia.gov) and // Eric C. Cyr (eccyr@sandia.gov) // *********************************************************************** // @HEADER #include <Teuchos_ConfigDefs.hpp> #include <Teuchos_UnitTestHarness.hpp> #include <Teuchos_RCP.hpp> #include <Teuchos_TimeMonitor.hpp> #include "Teuchos_DefaultComm.hpp" #include "Teuchos_GlobalMPISession.hpp" #include "Teuchos_Tuple.hpp" #include "PanzerAdaptersSTK_config.hpp" #include "Panzer_STK_Interface.hpp" #include "Panzer_STK_SquareQuadMeshFactory.hpp" #include "Panzer_STK_CubeHexMeshFactory.hpp" #include "Panzer_STK_Utilities.hpp" #include "Panzer_STK_PeriodicBC_Matcher.hpp" #include "Panzer_STK_PeriodicBC_Parser.hpp" #include "Panzer_STK_PeriodicBC_MatchConditions.hpp" #include "Panzer_STKConnManager.hpp" #include "Panzer_IntrepidFieldPattern.hpp" #include "Panzer_PauseToAttach.hpp" #include "Panzer_DOFManager.hpp" #include "Epetra_MpiComm.h" #include "Kokkos_DynRankView.hpp" #include "Intrepid2_HGRAD_QUAD_C1_FEM.hpp" #include "Intrepid2_HGRAD_HEX_C1_FEM.hpp" #include <string> typedef Kokkos::DynRankView<double,PHX::Device> FieldContainer; using Teuchos::RCP; using Teuchos::rcp; namespace panzer_stk { template <typename Intrepid2Type> RCP<const panzer::FieldPattern> buildFieldPattern() { // build a geometric pattern from a single basis RCP<Intrepid2::Basis<PHX::exec_space,double,double> > basis = rcp(new Intrepid2Type); RCP<const panzer::FieldPattern> pattern = rcp(new panzer::Intrepid2FieldPattern(basis)); return pattern; } TEUCHOS_UNIT_TEST(periodic_mesh_nosubcells, serial) { using Teuchos::RCP; Epetra_MpiComm Comm(MPI_COMM_WORLD); TEUCHOS_ASSERT(Comm.NumProc()==1); // panzer::pauseToAttach(); panzer_stk::CubeHexMeshFactory mesh_factory; // setup mesh ///////////////////////////////////////////// RCP<panzer_stk::STK_Interface> mesh; { RCP<Teuchos::ParameterList> pl = rcp(new Teuchos::ParameterList); pl->set("X Blocks",1); pl->set("Y Blocks",1); pl->set("Z Blocks",1); pl->set("X Elements",2); pl->set("Y Elements",2); pl->set("Z Elements",2); pl->set("X Procs",1); pl->set("Y Procs",1); pl->set("Z Procs",1); pl->set("X0",0.0); pl->set("Y0",0.0); pl->set("Z0",0.0); pl->set("Xf",6.0); pl->set("Yf",3.0); pl->set("Zf",4.0); mesh_factory.setParameterList(pl); mesh_factory.buildSubcells(false); mesh = mesh_factory.buildMesh(MPI_COMM_WORLD); } panzer_stk::PlaneMatcher side_matcher(1,2); panzer_stk::PlaneMatcher front_matcher(0,1); mesh->addPeriodicBC(panzer_stk::buildPeriodicBC_Matcher("right","left",side_matcher)); mesh->addPeriodicBC(panzer_stk::buildPeriodicBC_Matcher("front","back",front_matcher)); mesh->writeToExodus("file.exo"); // connection manager ///////////////////////////////////////////// RCP<const panzer::FieldPattern> fp = buildFieldPattern<Intrepid2::Basis_HGRAD_HEX_C1_FEM<PHX::exec_space,double,double> >(); Teuchos::RCP<panzer::ConnManager> connMngr = Teuchos::rcp(new panzer_stk::STKConnManager(mesh)); Teuchos::RCP<panzer::DOFManager> dofManager = Teuchos::rcp(new panzer::DOFManager(connMngr,MPI_COMM_WORLD)); dofManager->addField("VAR",fp); dofManager->buildGlobalUnknowns(); std::vector<panzer::GlobalOrdinal> owned; dofManager->getOwnedIndices(owned); std::size_t unkCount = owned.size(); std::size_t nodeCount = mesh->getEntityCounts(mesh->getNodeRank()); out << "Unknown Count = " << unkCount << ", Node Count = " << nodeCount << std::endl; TEST_ASSERT(unkCount < nodeCount); } }
36.178344
98
0.689437
hillyuan
a7aa5ff4bd5cac47b4390d829efc5c2e899ac3d5
873
hpp
C++
src/geometry/include/geometry/point.hpp
snailbaron/rooms
03496c3cd30e2020e1b0f1ad7d96bfba4e000eaa
[ "MIT" ]
null
null
null
src/geometry/include/geometry/point.hpp
snailbaron/rooms
03496c3cd30e2020e1b0f1ad7d96bfba4e000eaa
[ "MIT" ]
null
null
null
src/geometry/include/geometry/point.hpp
snailbaron/rooms
03496c3cd30e2020e1b0f1ad7d96bfba4e000eaa
[ "MIT" ]
null
null
null
#pragma once #include "geometry/vector.hpp" #include <ostream> #include <type_traits> #include <utility> namespace geometry { template <class T> struct Point { Point() : x(), y() {} Point(T x, T y) : x(std::move(x)), y(std::move(y)) {} template <class U, class = std::enable_if_t<std::is_convertible_v<U, T>>> Point& operator+=(const Vector<U>& rhs) { x += rhs.x; y += rhs.y; return *this; } T x; T y; }; template <class U, class V, class = internals::enable_if_have_common_type_t<U, V>> auto operator+(const Point<U>& lhs, const Vector<V>& rhs) { return Point<std::common_type_t<U, V>>{lhs.x + rhs.x, lhs.y + rhs.y}; } template <class T> std::ostream& operator<<(std::ostream& output, const Point<T>& point) { return output << "(" << point.x << ", " << point.y << ")"; } } // namespace geometry
20.785714
77
0.592211
snailbaron
a7aa92dd2ae44577d3019d8539a6a1b4836d5afb
1,281
cpp
C++
tests/basic_formatting.cpp
nscooling/embedded-fmt
1773fb9b0ff3e2c5883a0566cd678b541c0a4734
[ "MIT" ]
null
null
null
tests/basic_formatting.cpp
nscooling/embedded-fmt
1773fb9b0ff3e2c5883a0566cd678b541c0a4734
[ "MIT" ]
null
null
null
tests/basic_formatting.cpp
nscooling/embedded-fmt
1773fb9b0ff3e2c5883a0566cd678b541c0a4734
[ "MIT" ]
null
null
null
#include <cassert> #include <iostream> #include <string> std::string test_string{}; auto Putstr = [&str = test_string](auto c) { str += c; }; [[maybe_unused]] auto print_test_string = [](auto &str) { for (auto c : str) { putchar('.'), putchar(c); } }; #define Putchar(x) Putstr(x) #include "efmt.hpp" using namespace embedded; namespace { void basic_formatting() { puts(">>> Basic Format Arguments"); // case 1 fmt::print("int: {}\n", 42); std::cout << test_string; assert(test_string == "int: 42\n"); test_string.clear(); // case 2 fmt::print("int: {: }\n", 42); std::cout << test_string; assert(test_string == "int: 42\n"); test_string.clear(); // case 3 fmt::print("int: {: }\n", 42U); std::cout << test_string; assert(test_string == "int: 42\n"); test_string.clear(); // case 4 fmt::print("int: { }\n", -42); std::cout << test_string; assert(test_string == "int: -42\n"); test_string.clear(); // case 5 fmt::print("int: {: }\n", -42); std::cout << test_string; assert(test_string == "int: -42\n"); test_string.clear(); // case 6 fmt::print("float: {}\n", 1.2); std::cout << test_string; assert(test_string == "float: 1.20\n"); test_string.clear(); } } // namespace int main() { basic_formatting(); }
23.290909
57
0.59719
nscooling
a7ad259cba03629312907ea529c87ce975df8d36
6,204
cpp
C++
src/main.cpp
Erriez/ESP8266UbidotsSensors
498d932aca5c0a4d9f3f2a701e60f22ee068669d
[ "MIT" ]
null
null
null
src/main.cpp
Erriez/ESP8266UbidotsSensors
498d932aca5c0a4d9f3f2a701e60f22ee068669d
[ "MIT" ]
null
null
null
src/main.cpp
Erriez/ESP8266UbidotsSensors
498d932aca5c0a4d9f3f2a701e60f22ee068669d
[ "MIT" ]
2
2020-01-30T18:35:58.000Z
2021-12-02T14:22:53.000Z
/* * MIT License * * Copyright (c) 2018 Erriez * * 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 ESP8166 low power example * \details * This example configures the ESP8266 in low power. Default power is ~70mA. * * Bootloader takes about 350ms before setup() is reached. * * Connect pin D0 to RST to wakeup. Disconnect this pin before flashing. */ #include <Wire.h> #include <ESP8266WiFi.h> extern "C" { #include "user_interface.h" } #include <ErriezDS3231.h> #include "Config.h" #include "Diagnostics.h" #include "Flash.h" #include "NTP.h" #include "RTCRAM.h" #include "RTC.h" #include "Sensors.h" #include "WiFi.h" // RTC RAM data extern RTCRamData ramData; // Current RTC date/time static DS3231_DateTime dt; // Set ADC mode to read VCC ADC_MODE(ADC_VCC); static void initializeDevices(); static void powerOnReset(); static void awake(); static void powerDown(); void setup() { rst_info *rstInfo; // Initialize devices initializeDevices(); #if 0 sensorsInit(); while (1) { sensorsStartConversion(); delay(2000); sensorsRead(); } #endif Serial.print(F("Reset reason: ")); // Get reset info rstInfo = ESP.getResetInfoPtr(); // Disable or enable WiFi at startup which takes stome time switch (rstInfo->reason) { case REASON_DEFAULT_RST: Serial.println(F("DEFAULT_RST")); break; case REASON_EXT_SYS_RST: Serial.println(F("EXT_SYS_RST")); powerOnReset(); break; case REASON_DEEP_SLEEP_AWAKE: Serial.println(F("DEEP_SLEEP_AWAKE")); awake(); break; case REASON_SOFT_WDT_RST: Serial.println(F("WATCHDOG RESET")); break; default: Serial.println(F("UNKNOWN")); break; } // Set in power down powerDown(); } void loop() { // This line will not be reached } static void initializeDevices() { // Turn LED on pinMode(LED_PIN, OUTPUT); digitalWrite(LED_PIN, LOW); // Initialize serial port Serial.begin(115200); Serial.println(); // Initialize TWI Wire.begin(TWI_SDA, TWI_SCL); Wire.setClock(100000); // Initialize RTC rtcInitialize(); // Initialize flash flashInit(); // Initialize sensors sensorsInit(); } static void powerOnReset() { uint32_t epoch; // Initialize WiFi Serial.println(F("Initialize WiFi...")); wifiInit(); wifiConnect(); // Get NTP epoch time Serial.print(F("Get NTP epoch...")); epoch = getNTPEpoch(); if (epoch > 0) { Serial.println(epoch); } else { Serial.println(F("FAILED")); } // Program external RTC Serial.println(F("Program RTC data/time from epoch...")); rtcSetGMT(epoch); Serial.println(F("Program RTC alarms...")); rtcSetAlarms(); // Get and print RTC date time Serial.print(F("RTC date/time: ")); rtcGetDateTime(&dt); rtcPrintDateTimeShort(&dt); // Print diagnostics //printDiagnostics(); // Upload sensor data from flash storage if (getNumFiles()) { Serial.println(F("Upload sensors data...")); sensorsUpload(); } // Reset count ramData.wakeCount = 0; } static void awake() { // Read Serial.println(F("Read RTC RAM...")); readRTCRam(); // Increment reset count ramData.wakeCount++; // Print reset count Serial.print(F("Wake count: ")); Serial.println(ramData.wakeCount); // Get and print RTC date time Serial.print(F("RTC date/time: ")); rtcGetDateTime(&dt); rtcPrintDateTimeShort(&dt); // Start sensor conversions if (((dt.minute % 4) == 0) && (dt.second == 58)) { // Start sensors conversion Serial.println(F("Start sensor conversions...")); sensorsStartConversion(); } // Read sensor data if (((dt.minute % 5) == 0) && (dt.second == 0)) { // Read sensors Serial.println(F("Read sensors...")); sensorsRead(); } // Uplaod sensor data if (((dt.minute % 30) == 0) && (dt.second == 0)) { if (getNumFiles()) { // Initialize WiFi Serial.println(F("Initialize WiFi...")); wifiInit(); wifiConnect(); // Check if already connected if (WiFi.status() == WL_CONNECTED) { Serial.println(F("Upload sensors data...")); sensorsUpload(); } else { Serial.println(F("WiFi connect failed")); } } } } static void powerDown() { // Save variables to RTC RAM Serial.println(F("Write RTC RAM...")); writeRTCRam(); // Deep sleep generates external reset after wake Serial.print(F("Deep sleep ")); if (((dt.minute % 29) == 0) && (dt.second == 58)) { Serial.println(F("(RF default)...")); ESP.deepSleep(0 * 1000000UL, WAKE_RF_DEFAULT); } else { Serial.println(F("(RF disabled)...")); //wifiDisable(); ESP.deepSleep(0 * 1000000UL, WAKE_RF_DISABLED); } Serial.println(""); }
24.619048
81
0.613314
Erriez
a7aed24972d8209b2100978b046af873c65481ec
1,137
cpp
C++
GameEngine/GameEngine/main.cpp
MrMaguila/SelfMadeGameEngine
c941ea122ec25c1130f113e64c05b2a6a90e9f65
[ "Apache-2.0" ]
null
null
null
GameEngine/GameEngine/main.cpp
MrMaguila/SelfMadeGameEngine
c941ea122ec25c1130f113e64c05b2a6a90e9f65
[ "Apache-2.0" ]
null
null
null
GameEngine/GameEngine/main.cpp
MrMaguila/SelfMadeGameEngine
c941ea122ec25c1130f113e64c05b2a6a90e9f65
[ "Apache-2.0" ]
null
null
null
//############################################################################################# /* Copyright[2020][Gabriel G. Fernandes] 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 permissionsand limitations under the License. by Gabriel G. Fernandes 19/12/2020 gabrielgf6000@gmail.com */ //############################################################################################# #include "Game.h" #include "stb_image.h" #include <exception> #include <iostream> int main() try { Game game; //game.handleMultiplayer(); game.initializeWindow(); game.initializeGame(); game.gameLoop(); return 0; } catch (std::exception& e) { std::cerr << e.what(); {char ch; std::cin >> ch; } exit(-1); }
25.266667
95
0.614776
MrMaguila
a7b04a57fe77237e60c0588c93e941445d071e98
22,834
cpp
C++
tests/A32/fuzz_thumb.cpp
liushuyu/dynarmic
40afbe19279820e59382b7460643c62398ba0fb8
[ "0BSD" ]
77
2021-09-03T09:40:01.000Z
2022-03-30T05:18:36.000Z
tests/A32/fuzz_thumb.cpp
xerpi/dynarmic
bcfe377aaa5138af740e90af5be7a7dff7b62a52
[ "0BSD" ]
16
2021-09-03T13:13:54.000Z
2022-03-30T20:07:38.000Z
tests/A32/fuzz_thumb.cpp
xerpi/dynarmic
bcfe377aaa5138af740e90af5be7a7dff7b62a52
[ "0BSD" ]
15
2021-09-01T11:19:26.000Z
2022-03-27T09:19:14.000Z
/* This file is part of the dynarmic project. * Copyright (c) 2016 MerryMage * SPDX-License-Identifier: 0BSD */ #include <algorithm> #include <array> #include <cinttypes> #include <cstdio> #include <cstring> #include <functional> #include <string_view> #include <tuple> #include <catch2/catch.hpp> #include "../rand_int.h" #include "../unicorn_emu/a32_unicorn.h" #include "./testenv.h" #include "dynarmic/common/bit_util.h" #include "dynarmic/common/common_types.h" #include "dynarmic/frontend/A32/FPSCR.h" #include "dynarmic/frontend/A32/PSR.h" #include "dynarmic/frontend/A32/a32_location_descriptor.h" #include "dynarmic/frontend/A32/disassembler/disassembler.h" #include "dynarmic/frontend/A32/translate/a32_translate.h" #include "dynarmic/interface/A32/a32.h" #include "dynarmic/ir/basic_block.h" #include "dynarmic/ir/opt/passes.h" using namespace Dynarmic; static A32::UserConfig GetUserConfig(ThumbTestEnv* testenv) { A32::UserConfig user_config; user_config.optimizations &= ~OptimizationFlag::FastDispatch; user_config.callbacks = testenv; return user_config; } using WriteRecords = std::map<u32, u8>; struct ThumbInstGen final { public: ThumbInstGen( std::string_view format, std::function<bool(u32)> is_valid = [](u32) { return true; }) : is_valid(is_valid) { REQUIRE((format.size() == 16 || format.size() == 32)); const auto bit_size = format.size(); for (size_t i = 0; i < bit_size; i++) { const u32 bit = 1U << (bit_size - 1 - i); switch (format[i]) { case '0': mask |= bit; break; case '1': bits |= bit; mask |= bit; break; default: // Do nothing break; } } } u16 Generate16() const { u32 inst; do { const auto random = RandInt<u16>(0, 0xFFFF); inst = bits | (random & ~mask); } while (!is_valid(inst)); ASSERT((inst & mask) == bits); return static_cast<u16>(inst); } u32 Generate32() const { u32 inst; do { const auto random = RandInt<u32>(0, 0xFFFFFFFF); inst = bits | (random & ~mask); } while (!is_valid(inst)); ASSERT((inst & mask) == bits); return inst; } private: u32 bits = 0; u32 mask = 0; std::function<bool(u32)> is_valid; }; static bool DoesBehaviorMatch(const A32Unicorn<ThumbTestEnv>& uni, const A32::Jit& jit, const WriteRecords& interp_write_records, const WriteRecords& jit_write_records) { const auto interp_regs = uni.GetRegisters(); const auto jit_regs = jit.Regs(); return std::equal(interp_regs.begin(), interp_regs.end(), jit_regs.begin(), jit_regs.end()) && uni.GetCpsr() == jit.Cpsr() && interp_write_records == jit_write_records; } static void RunInstance(size_t run_number, ThumbTestEnv& test_env, A32Unicorn<ThumbTestEnv>& uni, A32::Jit& jit, const ThumbTestEnv::RegisterArray& initial_regs, size_t instruction_count, size_t instructions_to_execute_count) { uni.ClearPageCache(); jit.ClearCache(); // Setup initial state uni.SetCpsr(0x000001F0); uni.SetRegisters(initial_regs); jit.SetCpsr(0x000001F0); jit.Regs() = initial_regs; // Run interpreter test_env.modified_memory.clear(); test_env.ticks_left = instructions_to_execute_count; uni.SetPC(uni.GetPC() | 1); uni.Run(); const bool uni_code_memory_modified = test_env.code_mem_modified_by_guest; const auto interp_write_records = test_env.modified_memory; // Run jit test_env.code_mem_modified_by_guest = false; test_env.modified_memory.clear(); test_env.ticks_left = instructions_to_execute_count; jit.Run(); const bool jit_code_memory_modified = test_env.code_mem_modified_by_guest; const auto jit_write_records = test_env.modified_memory; test_env.code_mem_modified_by_guest = false; REQUIRE(uni_code_memory_modified == jit_code_memory_modified); if (uni_code_memory_modified) { return; } // Compare if (!DoesBehaviorMatch(uni, jit, interp_write_records, jit_write_records)) { printf("Failed at execution number %zu\n", run_number); printf("\nInstruction Listing: \n"); for (size_t i = 0; i < instruction_count; i++) { printf("%04x %s\n", test_env.code_mem[i], A32::DisassembleThumb16(test_env.code_mem[i]).c_str()); } printf("\nInitial Register Listing: \n"); for (size_t i = 0; i < initial_regs.size(); i++) { printf("%4zu: %08x\n", i, initial_regs[i]); } printf("\nFinal Register Listing: \n"); printf(" unicorn jit\n"); const auto uni_registers = uni.GetRegisters(); for (size_t i = 0; i < uni_registers.size(); i++) { printf("%4zu: %08x %08x %s\n", i, uni_registers[i], jit.Regs()[i], uni_registers[i] != jit.Regs()[i] ? "*" : ""); } printf("CPSR: %08x %08x %s\n", uni.GetCpsr(), jit.Cpsr(), uni.GetCpsr() != jit.Cpsr() ? "*" : ""); printf("\nUnicorn Write Records:\n"); for (const auto& record : interp_write_records) { printf("[%08x] = %02x\n", record.first, record.second); } printf("\nJIT Write Records:\n"); for (const auto& record : jit_write_records) { printf("[%08x] = %02x\n", record.first, record.second); } A32::PSR cpsr; cpsr.T(true); size_t num_insts = 0; while (num_insts < instructions_to_execute_count) { A32::LocationDescriptor descriptor = {u32(num_insts * 4), cpsr, A32::FPSCR{}}; IR::Block ir_block = A32::Translate(descriptor, &test_env, {}); Optimization::A32GetSetElimination(ir_block); Optimization::DeadCodeElimination(ir_block); Optimization::A32ConstantMemoryReads(ir_block, &test_env); Optimization::ConstantPropagation(ir_block); Optimization::DeadCodeElimination(ir_block); Optimization::VerificationPass(ir_block); printf("\n\nIR:\n%s", IR::DumpBlock(ir_block).c_str()); printf("\n\nx86_64:\n"); jit.DumpDisassembly(); num_insts += ir_block.CycleCount(); } #ifdef _MSC_VER __debugbreak(); #endif FAIL(); } } void FuzzJitThumb16(const size_t instruction_count, const size_t instructions_to_execute_count, const size_t run_count, const std::function<u16()> instruction_generator) { ThumbTestEnv test_env; // Prepare memory. test_env.code_mem.resize(instruction_count + 1); test_env.code_mem.back() = 0xE7FE; // b +#0 // Prepare test subjects A32Unicorn uni{test_env}; A32::Jit jit{GetUserConfig(&test_env)}; for (size_t run_number = 0; run_number < run_count; run_number++) { ThumbTestEnv::RegisterArray initial_regs; std::generate_n(initial_regs.begin(), initial_regs.size() - 1, [] { return RandInt<u32>(0, 0xFFFFFFFF); }); initial_regs[15] = 0; std::generate_n(test_env.code_mem.begin(), instruction_count, instruction_generator); RunInstance(run_number, test_env, uni, jit, initial_regs, instruction_count, instructions_to_execute_count); } } void FuzzJitThumb32(const size_t instruction_count, const size_t instructions_to_execute_count, const size_t run_count, const std::function<u32()> instruction_generator) { ThumbTestEnv test_env; // Prepare memory. // A Thumb-32 instruction is 32-bits so we multiply our count test_env.code_mem.resize(instruction_count * 2 + 1); test_env.code_mem.back() = 0xE7FE; // b +#0 // Prepare test subjects A32Unicorn uni{test_env}; A32::Jit jit{GetUserConfig(&test_env)}; for (size_t run_number = 0; run_number < run_count; run_number++) { ThumbTestEnv::RegisterArray initial_regs; std::generate_n(initial_regs.begin(), initial_regs.size() - 1, [] { return RandInt<u32>(0, 0xFFFFFFFF); }); initial_regs[15] = 0; for (size_t i = 0; i < instruction_count; i++) { const auto instruction = instruction_generator(); const auto first_halfword = static_cast<u16>(Common::Bits<0, 15>(instruction)); const auto second_halfword = static_cast<u16>(Common::Bits<16, 31>(instruction)); test_env.code_mem[i * 2 + 0] = second_halfword; test_env.code_mem[i * 2 + 1] = first_halfword; } RunInstance(run_number, test_env, uni, jit, initial_regs, instruction_count, instructions_to_execute_count); } } TEST_CASE("Fuzz Thumb instructions set 1", "[JitX64][Thumb][Thumb16]") { const std::array instructions = { ThumbInstGen("00000xxxxxxxxxxx"), // LSL <Rd>, <Rm>, #<imm5> ThumbInstGen("00001xxxxxxxxxxx"), // LSR <Rd>, <Rm>, #<imm5> ThumbInstGen("00010xxxxxxxxxxx"), // ASR <Rd>, <Rm>, #<imm5> ThumbInstGen("000110oxxxxxxxxx"), // ADD/SUB_reg ThumbInstGen("000111oxxxxxxxxx"), // ADD/SUB_imm ThumbInstGen("001ooxxxxxxxxxxx"), // ADD/SUB/CMP/MOV_imm ThumbInstGen("010000ooooxxxxxx"), // Data Processing ThumbInstGen("010001000hxxxxxx"), // ADD (high registers) ThumbInstGen("0100010101xxxxxx", // CMP (high registers) [](u32 inst) { return Common::Bits<3, 5>(inst) != 0b111; }), // R15 is UNPREDICTABLE ThumbInstGen("0100010110xxxxxx", // CMP (high registers) [](u32 inst) { return Common::Bits<0, 2>(inst) != 0b111; }), // R15 is UNPREDICTABLE ThumbInstGen("010001100hxxxxxx"), // MOV (high registers) ThumbInstGen("10110000oxxxxxxx"), // Adjust stack pointer ThumbInstGen("10110010ooxxxxxx"), // SXT/UXT ThumbInstGen("1011101000xxxxxx"), // REV ThumbInstGen("1011101001xxxxxx"), // REV16 ThumbInstGen("1011101011xxxxxx"), // REVSH ThumbInstGen("01001xxxxxxxxxxx"), // LDR Rd, [PC, #] ThumbInstGen("0101oooxxxxxxxxx"), // LDR/STR Rd, [Rn, Rm] ThumbInstGen("011xxxxxxxxxxxxx"), // LDR(B)/STR(B) Rd, [Rn, #] ThumbInstGen("1000xxxxxxxxxxxx"), // LDRH/STRH Rd, [Rn, #offset] ThumbInstGen("1001xxxxxxxxxxxx"), // LDR/STR Rd, [SP, #] ThumbInstGen("1011010xxxxxxxxx", // PUSH [](u32 inst) { return Common::Bits<0, 7>(inst) != 0; }), // Empty reg_list is UNPREDICTABLE ThumbInstGen("10111100xxxxxxxx", // POP (P = 0) [](u32 inst) { return Common::Bits<0, 7>(inst) != 0; }), // Empty reg_list is UNPREDICTABLE ThumbInstGen("1100xxxxxxxxxxxx", // STMIA/LDMIA [](u32 inst) { // Ensure that the architecturally undefined case of // the base register being within the list isn't hit. const u32 rn = Common::Bits<8, 10>(inst); return (inst & (1U << rn)) == 0 && Common::Bits<0, 7>(inst) != 0; }), // TODO: We should properly test against swapped // endianness cases, however Unicorn doesn't // expose the intended endianness of a load/store // operation to memory through its hooks. #if 0 ThumbInstGen("101101100101x000"), // SETEND #endif }; const auto instruction_select = [&]() -> u16 { const auto inst_index = RandInt<size_t>(0, instructions.size() - 1); return instructions[inst_index].Generate16(); }; SECTION("single instructions") { FuzzJitThumb16(1, 2, 10000, instruction_select); } SECTION("short blocks") { FuzzJitThumb16(5, 6, 3000, instruction_select); } // TODO: Test longer blocks when Unicorn can consistently // run these without going into an infinite loop. #if 0 SECTION("long blocks") { FuzzJitThumb16(1024, 1025, 1000, instruction_select); } #endif } TEST_CASE("Fuzz Thumb instructions set 2 (affects PC)", "[JitX64][Thumb][Thumb16]") { const std::array instructions = { // TODO: We currently can't test BX/BLX as we have // no way of preventing the unpredictable // condition from occurring with the current interface. // (bits zero and one within the specified register // must not be address<1:0> == '10'. #if 0 ThumbInstGen("01000111xmmmm000", // BLX/BX [](u32 inst){ const u32 Rm = Common::Bits<3, 6>(inst); return Rm != 15; }), #endif ThumbInstGen("1010oxxxxxxxxxxx"), // add to pc/sp ThumbInstGen("11100xxxxxxxxxxx"), // B ThumbInstGen("01000100h0xxxxxx"), // ADD (high registers) ThumbInstGen("01000110h0xxxxxx"), // MOV (high registers) ThumbInstGen("1101ccccxxxxxxxx", // B<cond> [](u32 inst) { const u32 c = Common::Bits<9, 12>(inst); return c < 0b1110; // Don't want SWI or undefined instructions. }), ThumbInstGen("1011o0i1iiiiinnn"), // CBZ/CBNZ ThumbInstGen("10110110011x0xxx"), // CPS // TODO: We currently have no control over the generated // values when creating new pages, so we can't // reliably test this yet. #if 0 ThumbInstGen("10111101xxxxxxxx"), // POP (R = 1) #endif }; const auto instruction_select = [&]() -> u16 { const auto inst_index = RandInt<size_t>(0, instructions.size() - 1); return instructions[inst_index].Generate16(); }; FuzzJitThumb16(1, 1, 10000, instruction_select); } TEST_CASE("Fuzz Thumb32 instructions set", "[JitX64][Thumb][Thumb32]") { const auto three_reg_not_r15 = [](u32 inst) { const auto d = Common::Bits<8, 11>(inst); const auto m = Common::Bits<0, 3>(inst); const auto n = Common::Bits<16, 19>(inst); return d != 15 && m != 15 && n != 15; }; const std::array instructions = { ThumbInstGen("111110101011nnnn1111dddd1000mmmm", // CLZ [](u32 inst) { const auto d = Common::Bits<8, 11>(inst); const auto m = Common::Bits<0, 3>(inst); const auto n = Common::Bits<16, 19>(inst); return m == n && d != 15 && m != 15; }), ThumbInstGen("111110101000nnnn1111dddd1000mmmm", // QADD three_reg_not_r15), ThumbInstGen("111110101000nnnn1111dddd0001mmmm", // QADD8 three_reg_not_r15), ThumbInstGen("111110101001nnnn1111dddd0001mmmm", // QADD16 three_reg_not_r15), ThumbInstGen("111110101010nnnn1111dddd0001mmmm", // QASX three_reg_not_r15), ThumbInstGen("111110101000nnnn1111dddd1001mmmm", // QDADD three_reg_not_r15), ThumbInstGen("111110101000nnnn1111dddd1011mmmm", // QDSUB three_reg_not_r15), ThumbInstGen("111110101110nnnn1111dddd0001mmmm", // QSAX three_reg_not_r15), ThumbInstGen("111110101000nnnn1111dddd1010mmmm", // QSUB three_reg_not_r15), ThumbInstGen("111110101100nnnn1111dddd0001mmmm", // QSUB8 three_reg_not_r15), ThumbInstGen("111110101101nnnn1111dddd0001mmmm", // QSUB16 three_reg_not_r15), ThumbInstGen("111110101001nnnn1111dddd1010mmmm", // RBIT [](u32 inst) { const auto d = Common::Bits<8, 11>(inst); const auto m = Common::Bits<0, 3>(inst); const auto n = Common::Bits<16, 19>(inst); return m == n && d != 15 && m != 15; }), ThumbInstGen("111110101001nnnn1111dddd1000mmmm", // REV [](u32 inst) { const auto d = Common::Bits<8, 11>(inst); const auto m = Common::Bits<0, 3>(inst); const auto n = Common::Bits<16, 19>(inst); return m == n && d != 15 && m != 15; }), ThumbInstGen("111110101001nnnn1111dddd1001mmmm", // REV16 [](u32 inst) { const auto d = Common::Bits<8, 11>(inst); const auto m = Common::Bits<0, 3>(inst); const auto n = Common::Bits<16, 19>(inst); return m == n && d != 15 && m != 15; }), ThumbInstGen("111110101001nnnn1111dddd1011mmmm", // REVSH [](u32 inst) { const auto d = Common::Bits<8, 11>(inst); const auto m = Common::Bits<0, 3>(inst); const auto n = Common::Bits<16, 19>(inst); return m == n && d != 15 && m != 15; }), ThumbInstGen("111110101000nnnn1111dddd0000mmmm", // SADD8 three_reg_not_r15), ThumbInstGen("111110101001nnnn1111dddd0000mmmm", // SADD16 three_reg_not_r15), ThumbInstGen("111110101010nnnn1111dddd0000mmmm", // SASX three_reg_not_r15), ThumbInstGen("111110101010nnnn1111dddd1000mmmm", // SEL three_reg_not_r15), ThumbInstGen("111110101000nnnn1111dddd0010mmmm", // SHADD8 three_reg_not_r15), ThumbInstGen("111110101001nnnn1111dddd0010mmmm", // SHADD16 three_reg_not_r15), ThumbInstGen("111110101010nnnn1111dddd0010mmmm", // SHASX three_reg_not_r15), ThumbInstGen("111110101110nnnn1111dddd0010mmmm", // SHSAX three_reg_not_r15), ThumbInstGen("111110101100nnnn1111dddd0010mmmm", // SHSUB8 three_reg_not_r15), ThumbInstGen("111110101101nnnn1111dddd0010mmmm", // SHSUB16 three_reg_not_r15), ThumbInstGen("111110101110nnnn1111dddd0000mmmm", // SSAX three_reg_not_r15), ThumbInstGen("111110101100nnnn1111dddd0000mmmm", // SSUB8 three_reg_not_r15), ThumbInstGen("111110101101nnnn1111dddd0000mmmm", // SSUB16 three_reg_not_r15), ThumbInstGen("111110101000nnnn1111dddd0100mmmm", // UADD8 three_reg_not_r15), ThumbInstGen("111110101001nnnn1111dddd0100mmmm", // UADD16 three_reg_not_r15), ThumbInstGen("111110101010nnnn1111dddd0100mmmm", // UASX three_reg_not_r15), ThumbInstGen("111110101000nnnn1111dddd0110mmmm", // UHADD8 three_reg_not_r15), ThumbInstGen("111110101001nnnn1111dddd0110mmmm", // UHADD16 three_reg_not_r15), ThumbInstGen("111110101010nnnn1111dddd0110mmmm", // UHASX three_reg_not_r15), ThumbInstGen("111110101110nnnn1111dddd0110mmmm", // UHSAX three_reg_not_r15), ThumbInstGen("111110101100nnnn1111dddd0110mmmm", // UHSUB8 three_reg_not_r15), ThumbInstGen("111110101101nnnn1111dddd0110mmmm", // UHSUB16 three_reg_not_r15), ThumbInstGen("111110101000nnnn1111dddd0101mmmm", // UQADD8 three_reg_not_r15), ThumbInstGen("111110101001nnnn1111dddd0101mmmm", // UQADD16 three_reg_not_r15), ThumbInstGen("111110101010nnnn1111dddd0101mmmm", // UQASX three_reg_not_r15), ThumbInstGen("111110101110nnnn1111dddd0101mmmm", // UQSAX three_reg_not_r15), ThumbInstGen("111110101100nnnn1111dddd0101mmmm", // UQSUB8 three_reg_not_r15), ThumbInstGen("111110101101nnnn1111dddd0101mmmm", // UQSUB16 three_reg_not_r15), ThumbInstGen("111110101110nnnn1111dddd0100mmmm", // USAX three_reg_not_r15), ThumbInstGen("111110101100nnnn1111dddd0100mmmm", // USUB8 three_reg_not_r15), ThumbInstGen("111110101101nnnn1111dddd0100mmmm", // USUB16 three_reg_not_r15), }; const auto instruction_select = [&]() -> u32 { const auto inst_index = RandInt<size_t>(0, instructions.size() - 1); return instructions[inst_index].Generate32(); }; SECTION("single instructions") { FuzzJitThumb32(1, 2, 10000, instruction_select); } SECTION("short blocks") { FuzzJitThumb32(5, 6, 3000, instruction_select); } } TEST_CASE("Verify fix for off by one error in MemoryRead32 worked", "[Thumb][Thumb16]") { ThumbTestEnv test_env; // Prepare test subjects A32Unicorn<ThumbTestEnv> uni{test_env}; A32::Jit jit{GetUserConfig(&test_env)}; constexpr ThumbTestEnv::RegisterArray initial_regs{ 0xe90ecd70, 0x3e3b73c3, 0x571616f9, 0x0b1ef45a, 0xb3a829f2, 0x915a7a6a, 0x579c38f4, 0xd9ffe391, 0x55b6682b, 0x458d8f37, 0x8f3eb3dc, 0xe18c0e7d, 0x6752657a, 0x00001766, 0xdbbf23e3, 0x00000000, }; test_env.code_mem = { 0x40B8, // lsls r0, r7, #0 0x01CA, // lsls r2, r1, #7 0x83A1, // strh r1, [r4, #28] 0x708A, // strb r2, [r1, #2] 0xBCC4, // pop {r2, r6, r7} 0xE7FE, // b +#0 }; RunInstance(1, test_env, uni, jit, initial_regs, 5, 5); }
42.207024
227
0.565954
liushuyu
a7b1a21036ce1199fb62765ff60e6fe749008b02
5,224
cpp
C++
src/main/MessageConsumer.cpp
jane3030/pyactivemq
5525cb0b849483a304b550d8884fed445a93c1b1
[ "Apache-2.0" ]
5
2015-04-02T11:46:52.000Z
2020-12-31T07:44:13.000Z
src/main/MessageConsumer.cpp
jane3030/pyactivemq
5525cb0b849483a304b550d8884fed445a93c1b1
[ "Apache-2.0" ]
null
null
null
src/main/MessageConsumer.cpp
jane3030/pyactivemq
5525cb0b849483a304b550d8884fed445a93c1b1
[ "Apache-2.0" ]
5
2017-06-21T03:40:06.000Z
2020-02-17T07:21:53.000Z
/* Copyright 2007 Albert Strasheim <fullung@gmail.com> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "pyactivemq.h" #include <boost/python/class.hpp> #include <cms/MessageConsumer.h> #include <cms/TextMessage.h> #include <cms/BytesMessage.h> #include <cms/MapMessage.h> #include <cms/StreamMessage.h> #include <cms/ObjectMessage.h> namespace py = boost::python; using cms::MessageConsumer; using cms::Closeable; using cms::Message; template<class T> struct to_python_Message { template <class U> inline PyObject* operator()(U const* ref) const { if (ref == 0) { return py::incref(boost::python::detail::none()); } U* const p = const_cast<U*>(ref); if (dynamic_cast<cms::BytesMessage*>(p) != 0) { return make_owning_holder::execute(dynamic_cast<cms::BytesMessage*>(p)); } else if (dynamic_cast<cms::TextMessage*>(p) != 0) { return make_owning_holder::execute(dynamic_cast<cms::TextMessage*>(p)); } else if (dynamic_cast<cms::MapMessage*>(p) != 0) { return make_owning_holder::execute(dynamic_cast<cms::MapMessage*>(p)); } else if (dynamic_cast<cms::StreamMessage*>(p) != 0) { return make_owning_holder::execute(dynamic_cast<cms::StreamMessage*>(p)); } else if (dynamic_cast<cms::ObjectMessage*>(p) != 0) { return make_owning_holder::execute(dynamic_cast<cms::ObjectMessage*>(p)); } else if (dynamic_cast<cms::Message*>(p) != 0) { return make_owning_holder::execute(dynamic_cast<cms::Message*>(p)); } Py_FatalError("Invalid Message type encountered in to_python_Message"); return 0; } }; struct manage_new_Message { template<class T> struct apply { typedef to_python_Message<T> type; }; }; static const char* MessageConsumer_docstring = "A client uses a C{MessageConsumer} to receive messages from a destination.\n\n" "A client may either synchronously receive a message consumer's messages or have " "the consumer asynchronously deliver them as they arrive.\n\nFor synchronous receipt, " "a client can request the next message from a message consumer using one of its receive " "methods. There are several variations of receive that allow a client to poll or wait " "for the next message.\n\nFor asynchronous delivery, a client can register a " "L{MessageListener} object with a message consumer. As messages arrive at the message " "consumer, it delivers them by calling the L{MessageListener}'s C{onMessage} method."; static const char* MessageConsumer_receive0_docstring = "Synchronously receive a L{Message}."; static const char* MessageConsumer_receive1_docstring = "Synchronously receive a L{Message}, time out after defined interval.\n\n" "Returns null if nothing read."; static const char* MessageConsumer_receiveNoWait_docstring = "Receive a L{Message}, does not wait if there isn't a new message to " "read, returns C{NULL} if nothing read."; static const char* MessageConsumer_messageListener_docstring = "The L{MessageListener} that this class will send notifications on."; static const char* MessageConsumer_messageSelector_docstring = "This message consumer's message selector expression."; void export_MessageConsumer() { Message* (MessageConsumer::*MessageConsumer_receive0)() = &MessageConsumer::receive; Message* (MessageConsumer::*MessageConsumer_receive1)(int) = &MessageConsumer::receive; py::class_<MessageConsumer, py::bases<Closeable>, boost::noncopyable>("MessageConsumer", MessageConsumer_docstring, py::no_init) .def("receive", MessageConsumer_receive0, py::return_value_policy<manage_new_Message>(), MessageConsumer_receive0_docstring) .def("receive", MessageConsumer_receive1, py::return_value_policy<manage_new_Message>(), py::arg("timeout"), MessageConsumer_receive1_docstring) .def("receiveNoWait", &MessageConsumer::receiveNoWait, py::return_value_policy<manage_new_Message>(), MessageConsumer_receiveNoWait_docstring) .add_property("messageListener", make_function(&MessageConsumer::getMessageListener, py::return_internal_reference<>()), make_function(&MessageConsumer::setMessageListener, py::with_custodian_and_ward<1,2>()), MessageConsumer_messageListener_docstring) .add_property("messageSelector", &MessageConsumer::getMessageSelector, MessageConsumer_messageSelector_docstring) ; }
42.471545
132
0.694678
jane3030
a7b288a24dc2931580aec2350cf01e91ed44152e
4,363
cpp
C++
CtrlLib/TrayIconWin32.cpp
koz4k/soccer
7bceea654b50c5c0e18effd38e79249bd295e0a4
[ "MIT" ]
1
2018-09-28T17:04:11.000Z
2018-09-28T17:04:11.000Z
CtrlLib/TrayIconWin32.cpp
koz4k/soccer
7bceea654b50c5c0e18effd38e79249bd295e0a4
[ "MIT" ]
1
2021-04-06T21:57:39.000Z
2021-04-06T21:57:39.000Z
CtrlLib/TrayIconWin32.cpp
koz4k/soccer
7bceea654b50c5c0e18effd38e79249bd295e0a4
[ "MIT" ]
3
2017-08-26T12:06:05.000Z
2019-11-22T16:57:47.000Z
#include "CtrlLib.h" #ifdef GUI_WIN #ifndef PLATFORM_WINCE #include <commdlg.h> #include <cderr.h> #include <shellapi.h> #endif #endif namespace Upp { #ifdef GUI_WIN #ifndef PLATFORM_WINCE #define LLOG(x) enum { UM_TASKBAR_ = WM_USER + 1024, NIN_BALLOONSHOW_ = WM_USER + 2, NIN_BALLOONHIDE_ = WM_USER + 3, NIN_BALLOONTIMEOUT_ = WM_USER + 4, NIN_BALLOONUSERCLICK_ = WM_USER + 5, }; TrayIcon::TrayIcon() { Create(NULL, WS_POPUP, 0, false, 0, 0); Ctrl::Hide(); Zero(nid); nid.sz = IsWin2K() ? sizeof(NotifyIconNew) : sizeof(NotifyIconOld); nid.message = UM_TASKBAR_; nid.hwnd = GetHWND(); static int id; nid.id = ++id; visible = false; Show(); } TrayIcon::~TrayIcon() { Hide(); if(nid.icon) DestroyIcon(nid.icon); } void TrayIcon::Notify(dword msg) { if(visible) { nid.flags = NIF_ICON|NIF_MESSAGE|NIF_TIP; if(nid.icon) DestroyIcon(nid.icon); nid.icon = SystemDraw::IconWin32(icon); String stip = ToSystemCharset(tip); int len = min(stip.GetLength(), 125); memcpy(nid.tip, stip, len); nid.tip[len] = 0; BOOL Status = Shell_NotifyIcon(msg, (NOTIFYICONDATA *)&nid); // To prevent from Shell_NotifyIcon bugs... // discussed here : http://msdn.microsoft.com/en-us/library/bb762159(v=vs.85).aspx // and here : http://issuetracker.delphi-jedi.org/bug_view_advanced_page.php?bug_id=3747 if (Status == FALSE) { // The status of Shell_NotifyIcon is FALSE, in the case of NIM_ADD/NIM_MODIFY, we will try to Modify // If the modify is OK then we cas consider that the add was worked. // Same, case with delete, we can try modify and if KO then we can consider that is icon // was deleted correctly. In other cases, we will retry after 50ms DWORD ErrorCode = GetLastError(); if(ErrorCode == ERROR_SUCCESS || ErrorCode == ERROR_TIMEOUT) { for(int retry = 0; retry < 60; retry++) { Sleep(50); if(Shell_NotifyIcon(NIM_MODIFY, (NOTIFYICONDATA *)&nid) == (msg != NIM_DELETE)) break; } } } } } void TrayIcon::Message(int type, const char *title, const char *text, int timeout) { if(!IsWin2K()) return; nid.flags = 0x10; *nid.info = *nid.title = 0; if(text) { String h = ToSystemCharset(text); memcpy(nid.info, h, min(h.GetLength(), 255) + 1); nid.info[255] = 0; } if(title) { String h = ToSystemCharset(title); memcpy(nid.title, h, min(h.GetLength(), 63) + 1); nid.title[63] = 0; } nid.infoflags = type; nid.timeout = minmax(timeout, 10, 30) * 1000; Shell_NotifyIcon(NIM_MODIFY, (NOTIFYICONDATA *)&nid); } void TrayIcon::Show(bool b) { if(b == visible) return; if(visible) Notify(NIM_DELETE); visible = b; if(visible) Notify(NIM_ADD); } TrayIcon& TrayIcon::Icon(const Image &img) { icon = img; Notify(NIM_MODIFY); return *this; } TrayIcon& TrayIcon::Tip(const char *text) { tip = text; Notify(NIM_MODIFY); return *this; } void TrayIcon::Menu(Bar& bar) { WhenBar(bar); } void TrayIcon::LeftDown() { WhenLeftDown(); } void TrayIcon::LeftUp() { WhenLeftUp(); } void TrayIcon::LeftDouble() { WhenLeftDouble(); } void TrayIcon::DoMenu(Bar& bar) { Menu(bar); } void TrayIcon::BalloonLeftDown() { WhenBalloonLeftDown(); } void TrayIcon::BalloonShow() { WhenBalloonShow(); } void TrayIcon::BalloonHide() { WhenBalloonHide(); } void TrayIcon::BalloonTimeout() { WhenBalloonTimeout(); } LRESULT TrayIcon::WindowProc(UINT message, WPARAM wParam, LPARAM lParam) { if(message == WM_QUERYENDSESSION) { Shutdown(); return true; } if(message == UM_TASKBAR_) switch(lParam) { case WM_LBUTTONDOWN: LeftDown(); return TRUE; case WM_LBUTTONUP: LeftUp(); return TRUE; case WM_LBUTTONDBLCLK: ::SetForegroundWindow(nid.hwnd); LeftDouble(); return TRUE; case WM_RBUTTONDOWN: ::SetForegroundWindow(nid.hwnd); MenuBar::Execute(NULL, THISBACK(DoMenu), GetMousePos()); return TRUE; case NIN_BALLOONSHOW_: BalloonShow(); return TRUE; case NIN_BALLOONHIDE_: BalloonHide(); return TRUE; case NIN_BALLOONTIMEOUT_: BalloonTimeout(); return TRUE; case NIN_BALLOONUSERCLICK_: BalloonLeftDown(); return TRUE; } static UINT WM_TASKBARCREATED = RegisterWindowMessageA("TaskbarCreated"); if(message == WM_TASKBARCREATED) { LLOG("TrayIcon::WM_TASKBARCREATED"); visible = false; Show(); } return Ctrl::WindowProc(message, wParam, lParam); } #endif #endif }
19.742081
103
0.682558
koz4k
a7b5d5ed71a92ed79e022f2642eebf9d79c3855a
1,946
cpp
C++
test/main.cpp
lydiazoghbi/Project-X---EcoBot
81d53383634dccdf6e5c82655ca53ccf3c65fda0
[ "Apache-2.0" ]
null
null
null
test/main.cpp
lydiazoghbi/Project-X---EcoBot
81d53383634dccdf6e5c82655ca53ccf3c65fda0
[ "Apache-2.0" ]
1
2019-12-09T20:44:47.000Z
2019-12-09T20:44:47.000Z
test/main.cpp
lydiazoghbi/project_x_ecobot
81d53383634dccdf6e5c82655ca53ccf3c65fda0
[ "Apache-2.0" ]
null
null
null
/* * * Copyright 2019 Lydia Zoghbi and Ryan Bates. * * 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. * */ /** * @file main.cpp * @author Lydia Zoghbi and Ryan Bates * @copyright Copyright Apache 2.0 License * @date 12/09/2019 * @version 1.0 * * @brief Main function for running all tests * */ #include <math.h> #include <gtest/gtest.h> #include <cv_bridge/cv_bridge.h> #include <tf/transform_datatypes.h> #include <image_transport/image_transport.h> #include <cmath> #include <vector> #include <string> #include <memory> #include <utility> #include <iostream> #include <algorithm> #include "ros/ros.h" #include "sensor_msgs/Image.h" #include "nav_msgs/Odometry.h" #include "geometry_msgs/Twist.h" #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/imgcodecs/imgcodecs.hpp> #include "Point.hpp" #include "LowXAlg.hpp" #include "GreedyAlg.hpp" #include "StateMachine.hpp" #include "IPlanningAlg.hpp" #include "ImageAnalysis.hpp" /* * @brief main function which runs all test results. * @param This function takes the commandline arguments as input. * @return This function returns a 0 just to avoid error. */ int main(int argc, char** argv) { // Initialize a ROS node ros::init(argc, argv, "allTests"); // Initialize Google Test ::testing::InitGoogleTest(&argc, argv); // Run all tests return RUN_ALL_TESTS(); }
25.605263
76
0.709147
lydiazoghbi
a7b64a11725b6cb0e3071b9dc90270e195de4598
1,884
cpp
C++
mastermind/util.cpp
MartinMSPedersen/Cplusplus-snippets
ae34e7afff40456cea6dc0ecd3d4729d19fcebe3
[ "BSD-2-Clause" ]
null
null
null
mastermind/util.cpp
MartinMSPedersen/Cplusplus-snippets
ae34e7afff40456cea6dc0ecd3d4729d19fcebe3
[ "BSD-2-Clause" ]
null
null
null
mastermind/util.cpp
MartinMSPedersen/Cplusplus-snippets
ae34e7afff40456cea6dc0ecd3d4729d19fcebe3
[ "BSD-2-Clause" ]
null
null
null
/* Mon Jan 2 01:58:29 CET 2017 version 0.1 All source under GPL version 3 (GNU General Public License - http://www.gnu.org/) contact traxplayer@gmail.com for more information about this code */ #include <vector> #include <string> #include <iostream> #include <cassert> #include <cstdlib> #include <unistd.h> #include "util.h" #include "RandMT.h" using namespace std; vector<string> Util::getInput(istream &in) { vector<string> result; string aString; long unsigned int start,end,i; getline(in, aString); if (in.eof()==1) { //clearerr(stdin); in.clear(); } start=aString.find_first_not_of(' '); if (start==string::npos) return result; end=aString.find_last_not_of(' '); for (i=start+1; i<end; i++) { if (aString.at(i)==' ') { result.push_back(aString.substr(start,i-start)); start=i+1; } } result.push_back(aString.substr(start,end-start+1)); return result; } unsigned int Util::getAPrimeNumber(const unsigned int &num) { int i; static const unsigned int primes[] = { 11, 19, 37, 73, 109, 163, 251, 367, 557, 823, 1237, 1861, 2777, 4177, 6247, 9371, 14057, 21089, 31627, 47431, 71143, 106721, 160073, 240101, 360163, 540217, 810343, 1215497, 1823231, 2734867, 4102283, 6153409, 9230113, 13845163, }; static const int numOfPrimes=sizeof(primes)/sizeof(primes[0]); for (i = 0; i < numOfPrimes; i++) if (primes[i] > num) return primes[i]; return primes[numOfPrimes-1]; } unsigned long int Util::getRandom(unsigned long int i) { static bool first_time=true; static RandMT r; if (first_time) { first_time=false; //#ifdef DEBUG r=RandMT(1+2*getpid()); /* odds numbers are best */ /* should be replaced with reads to /dev/random */ //#endif } return (r.randomMT()%i); // return (int)(i*rand()/(RAND_MAX+1.0)); }
16.972973
103
0.640127
MartinMSPedersen
a7b8f763b4fdfb7b9b10b098cdaa0ed63745f72c
5,602
cpp
C++
projects/luabot/bot.cpp
JackSAE/SaltBot
0e3cce557daadd224d6120e98ef7b7bdce38cdfc
[ "MIT" ]
null
null
null
projects/luabot/bot.cpp
JackSAE/SaltBot
0e3cce557daadd224d6120e98ef7b7bdce38cdfc
[ "MIT" ]
null
null
null
projects/luabot/bot.cpp
JackSAE/SaltBot
0e3cce557daadd224d6120e98ef7b7bdce38cdfc
[ "MIT" ]
null
null
null
#include "bot.h" #include "time.h" #include "kf/kf_log.h" extern "C" { BotInterface BOT_API *CreateBot() { return new LuaBot(); } } int luaPrint(lua_State *l) { const char *temp=lua_tostring(l, -1); kf_log("Lua:"<<temp); return 0; } LuaBot::LuaBot() { kf::LogSystem::getDefault().addCout(); m_rand(time(0)+(int)this); m_lua = luaL_newstate(); luaL_openlibs(m_lua); lua_register(m_lua, "print", luaPrint); } LuaBot::~LuaBot() { } void LuaBot::init(const BotInitialData &initialData, BotAttributes &attrib) { attrib.health=1.0; attrib.motor=1.0; attrib.weaponSpeed=1.0; attrib.weaponStrength=1.0; std::string script = "data/bots/luabot.lua"; for (int i = 0; i < initialData.properties.size(); ++i) { if (initialData.properties[i].first == "script") { script = initialData.properties[i].second; } } luaL_dofile(m_lua, script.c_str()); lua_getglobal(m_lua, "init"); if(lua_isfunction(m_lua, -1)) { lua_newtable(m_lua); lua_pushstring(m_lua, initialData.mapName.c_str()); lua_setfield(m_lua, -2, "mapName"); lua_pushnumber(m_lua, initialData.scanFOV); lua_setfield(m_lua, -2, "fov"); lua_pushnumber(m_lua, initialData.mapData.width); lua_setfield(m_lua, -2, "width"); lua_pushnumber(m_lua, initialData.mapData.height); lua_setfield(m_lua, -2, "height"); lua_newtable(m_lua); for (int i = 0; i < initialData.properties.size(); ++i) { lua_pushstring(m_lua, initialData.properties[i].second.c_str()); lua_setfield(m_lua, -2, initialData.properties[i].first.c_str()); } lua_setfield(m_lua, -2, "properties"); lua_call(m_lua, 1, 1); if(lua_istable(m_lua,-1)) { lua_getfield(m_lua, -1, "health"); attrib.health = lua_tonumber(m_lua, -1); lua_pop(m_lua, 1); lua_getfield(m_lua, -1, "motor"); attrib.motor = lua_tonumber(m_lua, -1); lua_pop(m_lua, 1); lua_getfield(m_lua, -1, "weaponSpeed"); attrib.weaponSpeed = lua_tonumber(m_lua, -1); lua_pop(m_lua, 1); lua_getfield(m_lua, -1, "weaponStrength"); attrib.weaponStrength = lua_tonumber(m_lua, -1); lua_pop(m_lua, 1); } } lua_settop(m_lua, 0); } void LuaBot::update(const BotInput &input, BotOutput &output) { int stack = lua_gettop(m_lua); lua_getglobal(m_lua, "step"); if(lua_isfunction(m_lua, -1)) { lua_newtable(m_lua); lua_pushnumber(m_lua, input.health); lua_setfield(m_lua, -2, "health"); lua_pushnumber(m_lua, input.healthMax); lua_setfield(m_lua, -2, "healthMax"); lua_pushnumber(m_lua, input.bulletSpeed); lua_setfield(m_lua, -2, "bulletSpeed"); lua_newtable(m_lua); lua_pushnumber(m_lua, input.position.x); lua_setfield(m_lua, -2, "x"); lua_pushnumber(m_lua, input.position.y); lua_setfield(m_lua, -2, "y"); lua_setfield(m_lua, -2, "position"); lua_newtable(m_lua); lua_pushnumber(m_lua, input.velocity.x); lua_setfield(m_lua, -2, "x"); lua_pushnumber(m_lua, input.velocity.y); lua_setfield(m_lua, -2, "y"); lua_setfield(m_lua, -2, "velocity"); lua_newtable(m_lua); for(int i=0;i<input.scanResult.size();i++) { lua_newtable(m_lua); lua_pushstring(m_lua, input.scanResult[i].name.c_str()); lua_setfield(m_lua, -2, "name"); if(input.scanResult[i].type==VisibleThing::e_bullet) { lua_pushstring(m_lua, "bullet"); } else if(input.scanResult[i].type==VisibleThing::e_robot) { lua_pushstring(m_lua, "robot"); } else { lua_pushstring(m_lua, "unknown"); } lua_setfield(m_lua, -2, "type"); lua_newtable(m_lua); lua_pushnumber(m_lua, input.scanResult[i].position.x); lua_setfield(m_lua, -2, "x"); lua_pushnumber(m_lua, input.scanResult[i].position.y); lua_setfield(m_lua, -2, "y"); lua_setfield(m_lua, -2, "position"); lua_rawseti(m_lua,-2, i+1); } lua_setfield(m_lua, -2, "scanResult"); lua_newtable(m_lua); lua_pushnumber(m_lua, output.motor); lua_setfield(m_lua, -2, "motor"); lua_pushstring(m_lua, output.action==BotOutput::shoot?"shoot":"scan"); lua_setfield(m_lua, -2, "action"); lua_newtable(m_lua); lua_pushnumber(m_lua, output.lookDirection.x); lua_setfield(m_lua, -2, "x"); lua_pushnumber(m_lua, output.lookDirection.y); lua_setfield(m_lua, -2, "y"); lua_setfield(m_lua, -2, "lookDirection"); lua_newtable(m_lua); lua_pushnumber(m_lua, output.moveDirection.x); lua_setfield(m_lua, -2, "x"); lua_pushnumber(m_lua, output.moveDirection.y); lua_setfield(m_lua, -2, "y"); lua_setfield(m_lua, -2, "moveDirection"); lua_call(m_lua, 2, 1); if(lua_istable(m_lua,-1)) { lua_getfield(m_lua, -1, "motor"); output.motor = lua_tonumber(m_lua, -1); lua_pop(m_lua, 1); lua_getfield(m_lua, -1, "lookDirection"); lua_getfield(m_lua, -1, "x"); output.lookDirection.x = lua_tonumber(m_lua, -1); lua_pop(m_lua, 1); lua_getfield(m_lua, -1, "y"); output.lookDirection.y = lua_tonumber(m_lua, -1); lua_pop(m_lua, 1); lua_pop(m_lua, 1); lua_getfield(m_lua, -1, "moveDirection"); lua_getfield(m_lua, -1, "x"); output.moveDirection.x = lua_tonumber(m_lua, -1); lua_pop(m_lua, 1); lua_getfield(m_lua, -1, "y"); output.moveDirection.y = lua_tonumber(m_lua, -1); lua_pop(m_lua, 1); lua_pop(m_lua, 1); lua_getfield(m_lua, -1, "action"); const char *temp=lua_tostring(m_lua, -1); output.action = (strcmp("shoot", lua_tostring(m_lua, -1))==0)?BotOutput::shoot:BotOutput::scan; lua_pop(m_lua, 1); lua_pop(m_lua, 1); } } lua_settop(m_lua, 0); } void LuaBot::result(bool won) { lua_getglobal(m_lua, "result"); if(lua_isfunction(m_lua, -1)) { lua_pushboolean(m_lua, won); lua_call(m_lua, 1, 0); } }
26.932692
98
0.675295
JackSAE
a7bee457f1a216aa908a80525b520c3712d323ea
2,415
cpp
C++
test/Temple/Cache.cpp
Dom1L/molassembler
dafc656b1aa846b65b1fd1e06f3740ceedcf22db
[ "BSD-3-Clause" ]
17
2020-11-27T14:59:34.000Z
2022-03-28T10:31:25.000Z
test/Temple/Cache.cpp
Dom1L/molassembler
dafc656b1aa846b65b1fd1e06f3740ceedcf22db
[ "BSD-3-Clause" ]
null
null
null
test/Temple/Cache.cpp
Dom1L/molassembler
dafc656b1aa846b65b1fd1e06f3740ceedcf22db
[ "BSD-3-Clause" ]
6
2020-12-09T09:21:53.000Z
2021-08-22T15:42:21.000Z
/*!@file * @copyright This code is licensed under the 3-clause BSD license. * Copyright ETH Zurich, Laboratory of Physical Chemistry, Reiher Group. * See LICENSE.txt for details. */ #include <boost/test/unit_test.hpp> #include "Molassembler/Temple/Cache.h" using namespace Scine::Molassembler; unsigned int ackermann(unsigned int m, unsigned int n) { if (m == 0) { return n + 1; } if (n == 0) { return ackermann(m - 1, 1); } return ackermann(m - 1, ackermann(m, n - 1)); } /* Sample class with mutable Cache member and a generatable cache object * Also includes an example of how to modify a cache object */ class Foo { private: /* 2 */ mutable Temple::Cache<std::string> cache_ { std::make_pair( "bigNumber", [this]() { return (this -> determineMe_()); } ) }; unsigned determineMe_() { return ackermann(3, 2); } public: unsigned getAckermann() const { /* 4 */ return cache_.getGeneratable<unsigned>("bigNumber"); } void changeCacheValue() { /* 5 */ cache_.changeGeneratable<unsigned>( "bigNumber", [](unsigned* value) { *value = 4; } ); } }; BOOST_AUTO_TEST_CASE(SimpleCacheTest, *boost::unit_test::label("Temple")) { using namespace std::string_literals; /* 1 */ Temple::Cache<std::string> cache; /* 3 */ std::vector<std::string> keys {"number", "string", "vector"}; cache.add("number", 5); cache.add("string", "fsldkf"s); cache.add("vector", std::vector<unsigned>({4, 9})); /* 8 */ if(auto number = cache.getOption<int>("number")) { // op (bool) is true BOOST_CHECK(number.value() == 5); } if(auto number = cache.getOption<int>("non-existent number")) { // op (bool) is false // this should not be executed BOOST_REQUIRE(false); } /* 9 */ BOOST_CHECK( std::all_of( keys.begin(), keys.end(), [&cache](const std::string& key) { return cache.has(key); } ) ); /* 6 */ cache.invalidate("number"); BOOST_CHECK(!cache.has("number")); /* 7 */ cache.invalidate(); BOOST_CHECK( std::none_of( keys.begin(), keys.end(), [&cache](const std::string& key) { return cache.has(key); } ) ); /* 2, 4, 5 */ Foo bar; bar.getAckermann(); // test modification of the cache bar.changeCacheValue(); BOOST_CHECK(bar.getAckermann() == 4); }
20.818966
87
0.595031
Dom1L
a7c04f702e2f96b193ecaa49cc3b9d8a57417ee5
1,713
cpp
C++
src/playerDriver.cpp
jacobrs/risk-game
29ed2a58a9d5cf2fd28881876e1fabe4ed0e8ee5
[ "MIT" ]
null
null
null
src/playerDriver.cpp
jacobrs/risk-game
29ed2a58a9d5cf2fd28881876e1fabe4ed0e8ee5
[ "MIT" ]
null
null
null
src/playerDriver.cpp
jacobrs/risk-game
29ed2a58a9d5cf2fd28881876e1fabe4ed0e8ee5
[ "MIT" ]
null
null
null
#include "headers/Country.h" #include "headers/Player.h" #include <stdio.h> #include <iostream> #include <stdlib.h> #include <time.h> using namespace std; int main(int args, char** argv){ srand (time(NULL)); string name = ""; int numberOfDice = 0; int player1NumberOfDice = 0; int numberOfAttempts = 0; cout<<"Welcome Player please enter your name: "; cin>> name; while(numberOfAttempts < 3 && (player1NumberOfDice > 3 || player1NumberOfDice < 1)){ if (numberOfAttempts > 0) cout<<"\nYou made an error while entering values integers between 1 and 3 only!\n"; cout<< name <<" choose how many dice you would like: 1, 2 or 3? "; cin>> player1NumberOfDice; numberOfAttempts++; } Player *player1 = new Player(1, name, "red", player1NumberOfDice); printf("Player with name %s was created with diceRollingFacility containing %d dice.\n", player1->name.c_str(), player1->diceRollingFacility->number); if(player1NumberOfDice < 4 && player1NumberOfDice > 0){ cout << "Drawing 2 cards from the deck to the hand of " << name << "\n"; Deck gameDeck = Deck(15); Card drawn1 = gameDeck.draw(); cout <<"\nCard drawn: "<< drawn1.printCard() <<endl; player1->hand->addCard(drawn1); Card drawn2 = gameDeck.draw(); cout <<"\nCard drawn: "<< drawn2.printCard() <<endl; player1->hand->addCard(drawn2); player1->hand->printHand(); } Country* canada = new Country("Canada"); canada->owner = player1; printf("%s is owned by %s\n", canada->name.c_str(), canada->owner->name.c_str()); delete player1; }
33.588235
155
0.611208
jacobrs
a7c140b163443b78c5b1557c8da80952dece5eb7
9,328
cpp
C++
source/rpgss/TokenParser.cpp
kyuu/dynrpg-rpgss
ee534373b41728e282fc20691b6c94279df5e4c9
[ "MIT" ]
5
2015-10-07T15:09:59.000Z
2021-12-16T06:15:23.000Z
source/rpgss/TokenParser.cpp
kyuu/dynrpg-rpgss
ee534373b41728e282fc20691b6c94279df5e4c9
[ "MIT" ]
null
null
null
source/rpgss/TokenParser.cpp
kyuu/dynrpg-rpgss
ee534373b41728e282fc20691b6c94279df5e4c9
[ "MIT" ]
2
2016-12-09T10:06:28.000Z
2018-10-05T01:42:43.000Z
/* The MIT License (MIT) Copyright (c) 2014 Anatoli Steinmark 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 <cstdlib> #include <cstring> #define NOT_MAIN_MODULE #include <DynRPG/DynRPG.h> #include "TokenParser.hpp" namespace rpgss { //--------------------------------------------------------- bool TokenParser::parse(const char* token) { ParsedType = ParsedUndefined; State = Start; int token_len = std::strlen(token); int vlu_depth = 0; int i = -1; next: if (++i == token_len) { // either empty or invalid token return false; } switch (State) { case Start: { switch (token[i]) { case 'V': case 'v': State = ParsingVariable; goto next; case 'S': case 's': State = ParsingSwitch; goto next; case 'C': case 'c': State = ParsingColor; goto next; case 'A': case 'a': State = ParsingActorName; goto next; default: return false; } } case ParsingVariable: { switch (token[i]) { case 'V': case 'v': vlu_depth++; goto next; case 'S': case 's': case 'C': case 'c': case 'A': case 'a': return false; default: { // convert rest of token to base 10 number, the first lookup index char* endptr = 0; int n = (int)std::strtoul((const char*)(token + i), &endptr, 10); if ((n == 0 && endptr == token) || (endptr != token + token_len)) { // either conversion error or not all characters consumed return false; } // flatten variable lookup nesting, if any while (vlu_depth-- > 0) { if (n < 1 || n > RPG::system->variables.size) { return false; // index out of bounds } n = RPG::variables[n]; } // one last obstacle if (n < 1 || n > RPG::system->variables.size) { return false; // index out of bounds } // success! ParsedType = ParsedNumber; Number = RPG::variables[n]; return true; } } } case ParsingSwitch: { switch (token[i]) { case 'V': case 'v': vlu_depth++; goto next; case 'S': case 's': case 'C': case 'c': case 'A': case 'a': return false; default: { // convert rest of token to base 10 number, the first lookup index char* endptr = 0; int n = (int)std::strtoul((const char*)(token + i), &endptr, 10); if ((n == 0 && endptr == token) || (endptr != token + token_len)) { // either conversion error or not all characters consumed return false; } // flatten variable lookup nesting, if any while (vlu_depth-- > 0) { if (n < 1 || n > RPG::system->variables.size) { return false; // index out of bounds } n = RPG::variables[n]; } // one last obstacle if (n < 1 || n > RPG::system->switches.size) { return false; // index out of bounds } // success! ParsedType = ParsedBoolean; Boolean = RPG::switches[n]; return true; } } } case ParsingColor: { switch (token[i]) { case 'V': case 'v': case 'S': case 's': case 'C': case 'c': case 'A': case 'a': return false; default: { // a valid color literal consists of exactly 8 hex characters if (token_len - i != 8) { return false; } // read rest of token as base 16 number, the color literal in RRGGBBAA format char* endptr = 0; unsigned long n = std::strtoul((const char*)(token + i), &endptr, 16); if ((n == 0 && endptr == token) || (endptr != token + token_len)) { // either conversion error or not all characters consumed return false; } // success! ParsedType = ParsedColor; Color = n; return true; } } } case ParsingActorName: { switch (token[i]) { case 'V': case 'v': vlu_depth++; goto next; case 'S': case 's': case 'C': case 'c': case 'A': case 'a': return false; default: { // convert rest of token to base 10 number, the first lookup index char* endptr = 0; int n = (int)std::strtoul((const char*)(token + i), &endptr, 10); if ((n == 0 && endptr == token) || (endptr != token + token_len)) { // either conversion error or not all characters consumed return false; } // flatten variable lookup nesting, if any while (vlu_depth-- > 0) { if (n < 1 || n > RPG::system->variables.size) { return false; // index out of bounds } n = RPG::variables[n]; } // one last obstacle if (n < 1 || n > RPG::actors.count()) { return false; // index out of bounds } // success! ParsedType = ParsedString; String = RPG::actors[n]->getName(); return true; } } } default: { break; // shut up compiler } } // switch (State) return false; // shut up compiler } } // namespace rpgss
38.229508
101
0.37039
kyuu
a7c156e5df68ae9aff1a6b49a3208ae16caf7c63
2,364
cpp
C++
Source/AllProjects/CQCMEng/CQCMEng_ThisFacility.cpp
MarkStega/CQC
c1d0e01ec2abcaa5b8eb1899b9f0522fecee4b07
[ "MIT" ]
51
2020-12-26T18:17:16.000Z
2022-03-15T04:29:35.000Z
Source/AllProjects/CQCMEng/CQCMEng_ThisFacility.cpp
MarkStega/CQC
c1d0e01ec2abcaa5b8eb1899b9f0522fecee4b07
[ "MIT" ]
null
null
null
Source/AllProjects/CQCMEng/CQCMEng_ThisFacility.cpp
MarkStega/CQC
c1d0e01ec2abcaa5b8eb1899b9f0522fecee4b07
[ "MIT" ]
4
2020-12-28T07:24:39.000Z
2021-12-29T12:09:37.000Z
// // FILE NAME: CQCMEng_ThisFacility.cpp // // AUTHOR: Dean Roddey // // CREATED: 06/24/2015 // // COPYRIGHT: Charmed Quark Systems, Ltd @ 2020 // // This software is copyrighted by 'Charmed Quark Systems, Ltd' and // the author (Dean Roddey.) It is licensed under the MIT Open Source // license: // // https://opensource.org/licenses/MIT // // DESCRIPTION: // // This is the implementation file for the facility class. // // CAVEATS/GOTCHAS: // // LOG: // // --------------------------------------------------------------------------- // Includes // --------------------------------------------------------------------------- #include "CQCMEng_.hpp" // --------------------------------------------------------------------------- // Magic macros // --------------------------------------------------------------------------- RTTIDecls(TFacCQCMEng,TFacility) // --------------------------------------------------------------------------- // CLASS: TFacCQCMEng // PREFIX: fac // --------------------------------------------------------------------------- // --------------------------------------------------------------------------- // TFacCQCMEng: Constructors and Destructor // --------------------------------------------------------------------------- TFacCQCMEng::TFacCQCMEng() : TFacility ( L"CQCMEng" , tCIDLib::EModTypes::SharedLib , kCQCKit::c4MajVersion , kCQCKit::c4MinVersion , kCQCKit::c4Revision , tCIDLib::EModFlags::HasMsgFile ) { } TFacCQCMEng::~TFacCQCMEng() { } // --------------------------------------------------------------------------- // TFacCQCMEng: Public, non-virtual methods // --------------------------------------------------------------------------- // // Client apps have to call this to get our CML runtime classes registered // with the macro engine facility, so that these classes are available to // any macros they might load. We just allocate one of our standard runtime // class loader objects and install it on the macro engine. // // Unfortunately there is no way to have this fault in, so containing apps // must call this during init, before they start up other threads. // tCIDLib::TVoid TFacCQCMEng::InitCMLRuntime(const TCQCSecToken& sectUser) { facCIDMacroEng().AddClassLoader(new TCQCRTClassLoader(sectUser)); }
27.811765
78
0.460237
MarkStega
a7c45e68a2cdc5c8955d5628893eecc69ea0f9b3
365
cpp
C++
LectureCode/Review/review.cpp
wsun23/ncstate_ece566_spring2022
419d05720622d9886ebb32bb1ed41c4036913d5b
[ "MIT" ]
5
2022-01-27T21:11:55.000Z
2022-02-16T03:35:40.000Z
LectureCode/Review/review.cpp
wsun23/ncstate_ece566_spring2022
419d05720622d9886ebb32bb1ed41c4036913d5b
[ "MIT" ]
null
null
null
LectureCode/Review/review.cpp
wsun23/ncstate_ece566_spring2022
419d05720622d9886ebb32bb1ed41c4036913d5b
[ "MIT" ]
13
2022-01-13T22:48:48.000Z
2022-03-18T21:56:00.000Z
// review #include <stdio.h> enum Opcode { ADD = 0, SUB = 1 }; enum Register { R0 = 0, R1 = 1, R2 = 2 }; typedef struct { Opcode opcode; Register dest; // int means the register number Register src1; Register src2; } Instruction; int main() { Instruction add = { ADD, R0, R1, R2 }; Instruction sub = { SUB, R1, R2, R1 }; return 0; }
11.774194
49
0.589041
wsun23
a7c6eb53b9d9e041c6d01efd7a5c55684cd5bc6b
32,076
cpp
C++
src/elektronika/websrv.cpp
aestesis/elektronika
870f72ca7f64942f8316b3cd8f733f43c7d2d117
[ "Apache-2.0" ]
14
2016-05-09T01:14:03.000Z
2021-10-12T21:41:02.000Z
src/elektronika/websrv.cpp
aestesis/elektronika
870f72ca7f64942f8316b3cd8f733f43c7d2d117
[ "Apache-2.0" ]
null
null
null
src/elektronika/websrv.cpp
aestesis/elektronika
870f72ca7f64942f8316b3cd8f733f43c7d2d117
[ "Apache-2.0" ]
6
2015-08-19T01:28:54.000Z
2020-10-25T05:17:08.000Z
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // WEBSRV.CPP (c) YoY'01 WEB: www.aestesis.org // ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //#include <windows.h> //#include <process.h> //#include <iostream.h> //#include <fstream.h> #include <stdio.h> //#include <math.h> #include <winsock2.h> #include "websrv.h" #include "resource.h" ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ACI AwebsrvInfo::CI = ACI("AwebsrvInfo", GUID(0x11111112,0x00000060), &AeffectInfo::CI, 0, NULL); ACI Awebsrv::CI = ACI("Awebsrv", GUID(0x11111112,0x00000061), &Aeffect::CI, 0, NULL); ACI AwebsrvFront::CI = ACI("AwebsrvFront", GUID(0x11111112,0x00000062), &AeffectFront::CI, 0, NULL); ACI AwebsrvBack::CI = ACI("AwebsrvBack", GUID(0x11111112,0x00000063), &AeffectBack::CI, 0, NULL); ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// static int count=0; static bool initOK=false; static char wwwroot[ALIB_PATH]; static char hostname[1024]=""; static word port=80; static int jpegquality=80; static bool useftp=false; static char ftpsrv[1024]=""; static char ftplog[1024]=""; static char ftppwd[1024]=""; static char ftpfile[1024]=""; ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #define COMM_BUFFER_SIZE 1024 #define SMALL_BUFFER_SIZE 10 ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// struct HTTPRequestHeader { char method[SMALL_BUFFER_SIZE]; char url[ALIB_PATH]; char filepathname[ALIB_PATH]; char httpversion[SMALL_BUFFER_SIZE]; IN_ADDR client_ip; }; struct MimeAssociation { char *file_ext; char *mime; }; ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// static MimeAssociation mimetypes[] = { { ".txt", "text/plain" }, { ".html", "text/html" }, { ".htm", "text/html" }, { ".gif", "image/gif" }, { ".jpg", "image/jpeg" } }; ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// static const int nbmimetype=sizeof(mimetypes)/sizeof(MimeAssociation); ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// static SOCKET StartWebServer() { SOCKET s; s=socket(AF_INET, SOCK_STREAM, 0); if(s!=INVALID_SOCKET) { SOCKADDR_IN si; si.sin_family=AF_INET; si.sin_port=htons(port); si.sin_addr.s_addr=htonl(INADDR_ANY); if(bind(s,(struct sockaddr *) &si,sizeof(SOCKADDR_IN))!=SOCKET_ERROR) return s; } return 0; } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// static int SocketRead(SOCKET client_socket, char *receivebuffer, int buffersize) { int size=0; int totalsize=0; do { size=recv(client_socket, receivebuffer+totalsize, buffersize-totalsize, 0); if((size!=0)&&(size!=SOCKET_ERROR)) { totalsize+=size; // are we done reading the http header? if(strstr(receivebuffer,"\r\n\r\n")) break; } else return size; // error state } while((size!=0)&&(size!=SOCKET_ERROR)); return totalsize; } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// static bool ParseHTTPHeader(char *receivebuffer, HTTPRequestHeader &requestheader) { // http request header format // method uri httpversion char *pos=strtok(receivebuffer," ");; if(pos==NULL ) return FALSE; strncpy(requestheader.method, pos, SMALL_BUFFER_SIZE); pos=strtok(NULL, " "); if(pos==NULL) return FALSE; strncpy(requestheader.url, pos, ALIB_PATH); pos=strtok(NULL, "\r"); if(pos==NULL ) return FALSE; strncpy(requestheader.httpversion, pos, SMALL_BUFFER_SIZE); // based on the url lets figure out the filename + path strncpy(requestheader.filepathname, wwwroot, ALIB_PATH); strncat(requestheader.filepathname, requestheader.url, ALIB_PATH); // because the filepathname can have relative references ../ ./=20 // call _fullpath to get the absolute 'real' filepath // _fullpath seems to handle '/' and '\'=20 _fullpath(requestheader.filepathname, requestheader.filepathname, ALIB_PATH); return TRUE; } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// static int findMimeType(const char *filename) { const char *pos=strrchr(filename,'.'); if(pos) { int x; for(x=0; x<nbmimetype; x++) { if(stricmp(mimetypes[x].file_ext,pos)==0) return x; } } return 0; // return default mimetype 'text/plain'=20 } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// static void OutputHTTPError(SOCKET client_socket, int statuscode) { char headerbuffer[COMM_BUFFER_SIZE]; char htmlbuffer[COMM_BUFFER_SIZE]; sprintf(headerbuffer,"HTTP/1.0 %d\r\nContent-Type: text/html\r\nContent-Length: %ld\r\n\r\n",statuscode,strlen(htmlbuffer)); sprintf(htmlbuffer,"<html><body><h3>elektronika webServer<br><br><h2>Error: %d</h2></body></html>",statuscode); send(client_socket,headerbuffer,strlen(headerbuffer),0); send(client_socket,htmlbuffer,strlen(htmlbuffer),0); } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// static void OutputHTTPRedirect(SOCKET client_socket, const char *defaulturl) { char headerbuffer[COMM_BUFFER_SIZE]; char htmlbuffer[COMM_BUFFER_SIZE]; char hosturl[ALIB_PATH]; if(port==80) sprintf(hosturl,"http://%s",hostname); else sprintf(hosturl,"http://%s:%d",hostname, port); strncat(hosturl,defaulturl,COMM_BUFFER_SIZE); if(hosturl[strlen(hosturl)-1]!='/') strncat(hosturl,"/",ALIB_PATH); strncat(hosturl,"index.html",ALIB_PATH); sprintf(htmlbuffer,"<html><body><a href=3D\"%s\">%s</a></body></html>",hosturl,hosturl); sprintf(headerbuffer,"HTTP/1.0 301\r\nContent-Type: text/html\r\nContent-Length: %ld\r\nLocation: %s\r\n\r\n",strlen(htmlbuffer),hosturl); send(client_socket,headerbuffer,strlen(headerbuffer),0); send(client_socket,htmlbuffer,strlen(htmlbuffer),0); } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// static void init(char *rootdir) { if(!count) { WSADATA wd; if(WSAStartup(MAKEWORD(2, 2), &wd)==0) { strcpy(wwwroot, rootdir); strcat(wwwroot, "\\wwwroot"); { char fn[ALIB_PATH]; strcpy(fn, rootdir); strcat(fn, "\\www.ini"); { FILE *f=fopen(fn, "r"); char str[1024]; hostname[0]=0; if(f) { while(fgets(str, sizeof(str)-1, f)) { { char *s=str; while(*s) { if((*s==10)||(*s==13)) { *s=0; break; } s++; } } switch(str[0]) { case '#': break; default: if(strncmp("hostname=", str, 9)==0) { strcpy(hostname, str+9); } else if(strncmp("useftp=true", str, 11)==0) { useftp=true; } else if(strncmp("ftpsrv=", str, 7)==0) { strcpy(ftpsrv, str+7); } else if(strncmp("ftplog=", str, 7)==0) { strcpy(ftplog, str+7); } else if(strncmp("ftppwd=", str, 7)==0) { strcpy(ftppwd, str+7); } else if(strncmp("ftpfile=", str, 8)==0) { strcpy(ftpfile, str+8); } break; } } fclose(f); } if(!hostname[0]) gethostname(hostname, 1023); } } initOK=true; } } count++; } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// static void end() { count--; if(count==0) { if(initOK) { WSACleanup(); initOK=false; } } } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// class Aclient : public Athread { public: Aclient (Awebsrv *websrv, SOCKET socket, IN_ADDR ip); virtual ~Aclient (); virtual void run (); Awebsrv *websrv; SOCKET socket; IN_ADDR ip; bool bRun; bool bStop; Aclient *next; }; ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// Aclient::Aclient(Awebsrv *websrv, SOCKET socket, IN_ADDR ip) { this->websrv=websrv; this->socket=socket; this->ip=ip; next=NULL; bStop=false; bRun=true; start(); } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// Aclient::~Aclient() { } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void Aclient::run() { { HTTPRequestHeader requestheader; int size; char receivebuffer[COMM_BUFFER_SIZE]; char sendbuffer[COMM_BUFFER_SIZE]; requestheader.client_ip=ip; size=SocketRead(socket, receivebuffer, COMM_BUFFER_SIZE); if((size!=SOCKET_ERROR )&&(size!=0)) { receivebuffer[size]=NULL; if(ParseHTTPHeader(receivebuffer, requestheader)) { if(strstr(requestheader.method, "GET")) { if(strnicmp(requestheader.filepathname, wwwroot, strlen(wwwroot))==0) // else security violation! { char *pt=requestheader.filepathname+strlen(wwwroot); if(strncmp(pt, "\\serverpush320", 14)==0) { byte buffer[128000]; int size,r; strcpy(sendbuffer, "HTTP/1.0 200 OK\r\n"); strncat(sendbuffer, "Content-Type: multipart/x-mixed-replace\r\n", COMM_BUFFER_SIZE); strncat(sendbuffer, "boundary=magicalboundarystring\r\n", COMM_BUFFER_SIZE); strncat(sendbuffer,"\r\n", COMM_BUFFER_SIZE); strncat(sendbuffer, "--magicalboundarystring\r\n", COMM_BUFFER_SIZE); size=strlen(sendbuffer); r=send(socket, sendbuffer, size, 0); if(r==size) { while(!bStop) { Afilemem *fm=new Afilemem("jpg file", buffer, sizeof(buffer)); websrv->section.enter(__FILE__,__LINE__); websrv->snap320->save(fm, bitmapJPG, jpegquality); websrv->section.leave(); strcpy(sendbuffer, "Content-type: image/jpeg\r\n"); strncat(sendbuffer,"\r\n", COMM_BUFFER_SIZE); size=strlen(sendbuffer); r=send(socket, sendbuffer, size, 0); if(r==size) { int p=0; int filesize=(int)fm->getSize(); while((!bStop)&&filesize) { int n=mini(filesize, 2048); int r=send(socket, (char *)&buffer[p], n, 0); if(r!=n) { bStop=true; break; } p+=n; filesize-=n; } } else bStop=true; strcpy(sendbuffer, "\r\n--magicalboundarystring\r\n"); size=strlen(sendbuffer); r=send(socket, sendbuffer, size, 0); delete(fm); sleep(100); } } } else if(strncmp(pt, "\\serverpush160", 14)==0) { byte buffer[128000]; int size,r; strcpy(sendbuffer, "HTTP/1.0 200 OK\r\n"); strncat(sendbuffer, "Content-Type: multipart/x-mixed-replace\r\n", COMM_BUFFER_SIZE); strncat(sendbuffer, "boundary=magicalboundarystring\r\n", COMM_BUFFER_SIZE); strncat(sendbuffer,"\r\n", COMM_BUFFER_SIZE); strncat(sendbuffer, "--magicalboundarystring\r\n", COMM_BUFFER_SIZE); size=strlen(sendbuffer); r=send(socket, sendbuffer, size, 0); if(r==size) { while(!bStop) { Afilemem *fm=new Afilemem("jpg file", buffer, sizeof(buffer)); websrv->section.enter(__FILE__,__LINE__); websrv->snap160->save(fm, bitmapJPG, jpegquality); websrv->section.leave(); strcpy(sendbuffer, "Content-type: image/jpeg\r\n"); strncat(sendbuffer,"\r\n", COMM_BUFFER_SIZE); size=strlen(sendbuffer); r=send(socket, sendbuffer, size, 0); if(r==size) { int p=0; int filesize=(int)fm->getSize(); while((!bStop)&&filesize) { int n=mini(filesize, 2048); int r=send(socket, (char *)&buffer[p], n, 0); if(r!=n) { bStop=true; break; } p+=n; filesize-=n; } } else bStop=true; strcpy(sendbuffer, "\r\n--magicalboundarystring\r\n"); size=strlen(sendbuffer); r=send(socket, sendbuffer, size, 0); delete(fm); sleep(100); } } } else if(strncmp(pt, "\\thumbcamjpg320", 15)==0) { byte buffer[128000]; Afilemem *fm=new Afilemem("jpg file", buffer, sizeof(buffer)); websrv->section.enter(__FILE__,__LINE__); websrv->snap320->save(fm, bitmapJPG, jpegquality); websrv->section.leave(); strcpy(sendbuffer, "HTTP/1.0 200 OK\r\n"); strncat(sendbuffer, "Content-Type: ", COMM_BUFFER_SIZE); strncat(sendbuffer, "image/jpeg", COMM_BUFFER_SIZE); sprintf(sendbuffer+strlen(sendbuffer), "\r\nContent-Length: %ld\r\n", fm->getSize()); strncat(sendbuffer,"\r\n", COMM_BUFFER_SIZE); send(socket, sendbuffer, strlen(sendbuffer), 0); { int p=0; int filesize=(int)fm->getSize(); while((!bStop)&&filesize) { int n=mini(filesize, 2048); send(socket, (char *)&buffer[p], n, 0); p+=n; filesize-=n; } } delete(fm); } else if(strncmp(pt, "\\thumbcamjpg160", 15)==0) { byte buffer[64000]; Afilemem *fm=new Afilemem("jpg file", buffer, sizeof(buffer)); websrv->section.enter(__FILE__,__LINE__); websrv->snap160->save(fm, bitmapJPG, jpegquality); websrv->section.leave(); strcpy(sendbuffer, "HTTP/1.0 200 OK\r\n"); strncat(sendbuffer, "Content-Type: ", COMM_BUFFER_SIZE); strncat(sendbuffer, "image/jpeg", COMM_BUFFER_SIZE); sprintf(sendbuffer+strlen(sendbuffer), "\r\nContent-Length: %ld\r\n", fm->getSize()); strncat(sendbuffer,"\r\n", COMM_BUFFER_SIZE); send(socket, sendbuffer, strlen(sendbuffer), 0); { int p=0; int filesize=(int)fm->getSize(); while((!bStop)&&filesize) { int n=mini(filesize, 2048); send(socket, (char *)&buffer[p], n, 0); p+=n; filesize-=n; } } delete(fm); } else { long filesize; DWORD fileattrib=GetFileAttributes(requestheader.filepathname); if(!((fileattrib!=-1)&&(fileattrib&FILE_ATTRIBUTE_DIRECTORY))) { FILE *in=fopen(requestheader.filepathname,"rb"); // read binary if(!in) { OutputHTTPError(socket, 404); // 404 - not found } else { // determine file size fseek(in, 0, SEEK_END); filesize=ftell(in); fseek(in, 0, SEEK_SET); // send the http header and the file contents to the browser strcpy(sendbuffer, "HTTP/1.0 200 OK\r\n"); strncat(sendbuffer, "Content-Type: ", COMM_BUFFER_SIZE); strncat(sendbuffer, mimetypes[findMimeType(requestheader.filepathname)].mime, COMM_BUFFER_SIZE); sprintf(sendbuffer+strlen(sendbuffer), "\r\nContent-Length: %ld\r\n", filesize); strncat(sendbuffer,"\r\n", COMM_BUFFER_SIZE); send(socket, sendbuffer, strlen(sendbuffer), 0); { byte filebuffer[2048]; int n=1; while((!bStop)&&filesize&&n) { n=fread((char *)filebuffer, 1, mini(2048, filesize), in); send(socket, (char *)filebuffer, n, 0); filesize-=n; } } fclose(in); // log line } } else { OutputHTTPRedirect(socket, requestheader.url); } } } else { OutputHTTPError(socket, 403); // 403 - forbidden } } else { OutputHTTPError(socket, 501); // 501 not implemented } } else { OutputHTTPError(socket, 400); // 400 - bad request } } closesocket(socket); } bRun=false; } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// Awebsrv::Awebsrv(QIID qiid, char *name, AeffectInfo *info, Acapsule *capsule) : Aeffect(qiid, name, info, capsule) { init(getRootPath()); webrun=false; clients=NULL; front=new AwebsrvFront(qiid, "webserver front", this, 50); front->setTooltips("webserver"); back=new AwebsrvBack(qiid, "websrv back", this, 50); back->setTooltips("webserver"); snap320=new Abitmap(320, 240); snap160=new Abitmap(160, 120); if(!initOK) front->notify(this, nyERROR, (dword)"can't initialize winsock 2.2"); } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// Awebsrv::~Awebsrv() { stopServer(); end(); delete(snap320); delete(snap160); } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void Awebsrv::stopServer() { webstop=true; closesocket(socket); while(webrun) sleep(10); section.enter(__FILE__,__LINE__); stop(); { Aclient *c=clients; while(c) { Aclient *cn=c->next; c->bStop=true; while(c->bRun) sleep(10); delete(c); c=cn; } clients=NULL; } section.leave(); } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// bool Awebsrv::save(class Afile *f) { return true; } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// bool Awebsrv::load(class Afile *f) { return true; } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void Awebsrv::settings(bool emergency) { } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void Awebsrv::action(double time, double dtime, double beat, double dbeat) { Avideo *in=((AwebsrvBack *)back)->in; section.enter(__FILE__,__LINE__); in->enter(__FILE__,__LINE__); { Abitmap *b=in->getBitmap(); if(b) { snap320->set(0, 0, snap320->w, snap320->h, 0, 0, b->w, b->h, b, bitmapDEFAULT, bitmapDEFAULT); snap160->set(0, 0, snap160->w, snap160->h, 0, 0, b->w, b->h, b, bitmapDEFAULT, bitmapDEFAULT); nsnap++; } } in->leave(); section.leave(); } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void Awebsrv::run() { webstop=false; if(useftp) { Abuffer *f=new Abuffer("image", snap320->w*snap320->h*4+1024); // size max ftp=new AftpClient(ftpsrv, ftplog, ftppwd); webrun=true; while(!webstop) { if(nsnap) { if(ftp->getStatus()==AftpClient::statusCONNECTED) // et pas AftpClient::statusSTOR { section.enter(__FILE__,__LINE__); { f->clear(); snap320->save(f, bitmapJPG, jpegquality); ftp->sendFile(ftpfile, f); } nsnap=0; section.leave(); } } sleep(10); } delete(ftp); } else { socket=StartWebServer(); if(socket) { int ciplen=sizeof(SOCKADDR_IN); if(listen(socket,SOMAXCONN)!=SOCKET_ERROR) { webrun=true; while(!webstop) { SOCKADDR_IN cip; SOCKET csock=accept(socket,(struct sockaddr *)&cip, &ciplen); if(csock!=INVALID_SOCKET) { IN_ADDR ia; memcpy(&ia, &cip.sin_addr.s_addr, 4); Aclient *c=new Aclient(this, csock, ia); section.enter(__FILE__,__LINE__); c->next=clients; clients=c; section.leave(); } section.enter(__FILE__,__LINE__); { Aclient *c=clients; Aclient *oc=NULL; while(c) { Aclient *nc=c->next; if(!c->bRun) { if(oc==NULL) clients=c->next; else oc->next=c->next; delete(c); } else oc=c; c=nc; } } section.leave(); sleep(1); } } else front->notify(this, nyERROR, (dword)"can't start web server (can't listen)"); section.enter(__FILE__,__LINE__); { Aclient *c=clients; while(c) { Aclient *nc=c->next; c->bStop=true; while(c->bRun) sleep(10); delete(c); c=nc; } clients=NULL; } section.leave(); closesocket(socket); } else front->notify(this, nyERROR, (dword)"can't start web server"); } webrun=false; } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void AwebsrvFront::paint(Abitmap *b) { b->set(0, 0, back, bitmapDEFAULT, bitmapDEFAULT); } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// AwebsrvFront::AwebsrvFront(QIID qiid, char *name, Awebsrv *e, int h) : AeffectFront(qiid, name, e, h) { Aresobj o=resource.get(MAKEINTRESOURCE(PNG_WEBSRV), "PNG"); back=new Abitmap(&o); ehostname=new Aedit("hostname", this, 16, (pos.h-14)>>1, 218, 14); ehostname->setTooltips("host name"); ehostname->set(hostname); ehostname->show(true); eport=new Aedit("port", this, 240, (pos.h-14)>>1, 40, 14); eport->setTooltips("port"); eport->set("80"); eport->show(true); active=new Abutton("active", this, 300, (pos.h-14)>>1, 100, 14, "ACTIVE", Abutton::btCAPTION|Abutton::bt2STATES); active->setTooltips("active web server"); active->show(TRUE); jpegq=new Asegment("jpegquality", this, 420, (pos.h-14)>>1, 3, 1, 100, alib.getFont(fontSEGMENT10), 0xff000000, 0.5f); jpegq->setTooltips("jpeg quality"); jpegq->set(80); jpegq->show(true); } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// AwebsrvFront::~AwebsrvFront() { delete(back); delete(ehostname); delete(eport); delete(active); delete(jpegq); } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// bool AwebsrvFront::notify(Anode *o, int event, dword p) { switch(event) { case nyCHANGE: if(o==ehostname) { ((Awebsrv *)effect)->stopServer(); active->setChecked(false); ehostname->get(hostname, sizeof(hostname)-1); } else if(o==eport) { ((Awebsrv *)effect)->stopServer(); active->setChecked(false); char vp[10]; eport->get(vp, 9); vp[9]=0; port=(word)atoi(vp); } else if(o==active) { if(initOK) { if(active->isChecked()) ((Awebsrv *)effect)->start(); else ((Awebsrv *)effect)->stopServer(); } else { active->setChecked(false); } } else if(o==jpegq) { jpegquality=jpegq->get(); } break; case nyCLICK: break; } return AeffectFront::notify(o, event, p); } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void AwebsrvFront::pulse() { }; ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// AwebsrvBack::AwebsrvBack(QIID qiid, char *name, Awebsrv *e, int h) : AeffectBack(qiid, name, e, h) { Aresobj o=resource.get(MAKEINTRESOURCE(PNG_WEBSRV2), "PNG"); back=new Abitmap(&o); in=new Avideo(MKQIID(qiid, 0x75108d5c3cc47f00), "video input", this, pinIN|pinNOGFX, 16, 12); in->setTooltips("video input"); in->show(TRUE); } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// AwebsrvBack::~AwebsrvBack() { delete(in); delete(back); } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void AwebsrvBack::paint(Abitmap *b) { b->set(0, 0, back, bitmapDEFAULT, bitmapDEFAULT); } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// Aeffect * AwebsrvInfo::create(QIID qiid, char *name, Acapsule *capsule) { return new Awebsrv(qiid, name, this, capsule); } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// class Aplugz * websrvGetInfo() { return new AwebsrvInfo("websrvInfo", &Awebsrv::CI, "web server", "web server module - export video/picture for the web"); } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
32.269618
140
0.384587
aestesis
a7c7ab218b9e312f69f2058ff1f75db3d3bfc347
5,824
cpp
C++
src/compsys/MetaComponent.cpp
Oberon00/jd
0724e059cfa56615afb0a50c27ce9885faa54ed6
[ "BSD-2-Clause" ]
1
2015-10-10T14:05:56.000Z
2015-10-10T14:05:56.000Z
src/compsys/MetaComponent.cpp
Oberon00/jd
0724e059cfa56615afb0a50c27ce9885faa54ed6
[ "BSD-2-Clause" ]
null
null
null
src/compsys/MetaComponent.cpp
Oberon00/jd
0724e059cfa56615afb0a50c27ce9885faa54ed6
[ "BSD-2-Clause" ]
null
null
null
// Part of the Jade Engine -- Copyright (c) Christian Neumüller 2012--2013 // This file is subject to the terms of the BSD 2-Clause License. // See LICENSE.txt or http://opensource.org/licenses/BSD-2-Clause #include "compsys/MetaComponent.hpp" #include "ComponentRegistry.hpp" #include "compsys/Component.hpp" #include "Entity.hpp" #include "Logfile.hpp" #include "luaUtils.hpp" #include "svc/LuaVm.hpp" #include <boost/format.hpp> #include <luabind/adopt_policy.hpp> #include <luabind/class_info.hpp> #include <luabind/operator.hpp> #include <luabind/raw_policy.hpp> #include <ssig.hpp> #include <unordered_map> static char const libname[] = "ComponentSystem"; #include "luaexport/ExportThis.hpp" std::ostream& operator<< (std::ostream& os, Component const& c) { return os << "jd.Component (" << c.metaComponent().name() << " @" << &c << ')'; } namespace { static void registerMetaComponent(lua_State* L, std::string const& name) { static std::vector<std::unique_ptr<LuaMetaComponent>> components; components.push_back(std::unique_ptr<LuaMetaComponent>(new LuaMetaComponent(L, name))); } static std::string const& Component_componentName(Component const& c) { return c.metaComponent().name(); } static luabind::object Component_parent(Component const& c, lua_State* L) { if (c.parent()) return luabind::object(L, c.parent()->ref()); else return luabind::object(); } class wrap_Component: public Component, public luabind::wrap_base { public: wrap_Component(lua_State* L, Entity& parent, std::string const& classname) { m_metaComponent = ComponentRegistry::get(L)[classname]; if (!m_metaComponent) throw InvalidMetaComponentName(classname); parent.add(*this); assert(this->parent() == &parent); } void bindLuaPart() { luabind::wrapped_self_t& wrapper = luabind::detail::wrap_access::ref(*this); if (wrapper.m_strong_ref.is_valid()) { LOG_W("Double call to wrap_Component::bindLuaPart"); return; } wrapper.get(wrapper.state()); wrapper.m_strong_ref.pop(wrapper.state()); } virtual MetaComponent const& metaComponent() const { return *m_metaComponent; } virtual void initComponent() { luabind::wrapped_self_t& wrapper = luabind::detail::wrap_access::ref(*this); if (!wrapper.m_strong_ref.is_valid()) { LOG_W("wrap_Component::bindLuaPart was not called yet! Calling it now."); bindLuaPart(); } call<void>("initComponent"); } virtual void cleanupComponent() { luabind::wrapped_self_t& wrapper = luabind::detail::wrap_access::ref(*this); if (wrapper.m_strong_ref.is_valid()) { call<void>("cleanupComponent"); } else { LOG_W(boost::format("wrap_Component::cleanupComponent: cannot dispatch to Lua, because" " the lua_State is closing. (this=%1%; name=%2%)") % this % m_metaComponent->name()); } } static void nop(Component*) { /* NOP */ } private: MetaComponent const* m_metaComponent; }; class wrap_ConnectionBase: public ssig::ConnectionBase, public luabind::wrap_base { public: virtual void disconnect() { call<void>("disconnect"); } virtual bool isConnected() const { return call<bool>("getIsConnected"); } }; } // anonymous namespace static bool operator==(Component const& lhs, Component const* rhs) { return &lhs == rhs; } static void init(LuaVm& vm) { LUAU_BALANCED_STACK_DBG(vm.L()); LHMODULE [ // Component class // Note: metaComponent() is left out and implemented in wrap_Component class_<Component, wrap_Component, WeakRef<Component>>("Component") .def(constructor<lua_State*, Entity&, std::string const&>()) .def("initComponent", &Component::initComponent, &wrap_Component::nop) .def("cleanupComponent", &Component::cleanupComponent, &wrap_Component::nop) .property("parent", &Component_parent) .property("componentName", &Component_componentName) .def("_bindLuaPart", &wrap_Component::bindLuaPart) .def(const_self == other<Component*>()) .def(tostring(const_self)) .LHISREFVALID2(Component), def("registerComponent", &registerMetaComponent), class_<ssig::ConnectionBase, wrap_ConnectionBase>("ConnectionBase") .def(constructor<>()) .def("disconnect", &ssig::ConnectionBase::disconnect) .def("getIsConnected", &ssig::ConnectionBase::isConnected) .property("isConnected", &ssig::ConnectionBase::isConnected) ]; lua_getglobal(vm.L(), "jd"); luabind::object(vm.L(), static_cast<Component*>(nullptr)).push(vm.L()); lua_setfield(vm.L(), -2, "NIL_COMPONENT"); lua_pop(vm.L(), 1); } bool operator== (MetaComponent const& lhs, MetaComponent const& rhs) { if (&lhs == &rhs) { assert(&lhs.name() == &rhs.name()); return true; } assert(&lhs.name() != &rhs.name()); assert(lhs.name() != rhs.name()); return false; } bool operator!= (MetaComponent const& lhs, MetaComponent const& rhs) { return !(lhs == rhs); } bool operator< (MetaComponent const& lhs, MetaComponent const& rhs) { return lhs.name() < rhs.name(); } /////////////////////////////////////////////////////// LuaMetaComponent::LuaMetaComponent(lua_State* L, std::string const& name): m_name(name) { ComponentRegistry::get(L).registerComponent(this); } std::string const& LuaMetaComponent::name() const { return m_name; } void LuaMetaComponent::castDown(lua_State* L, Component* c) const { assert(dynamic_cast<wrap_Component*>(c)); luabind::object o(L, c->ref<wrap_Component>()); o.push(L); }
31.144385
102
0.648695
Oberon00
a7c8b1b07ffc4670b951bf8ee5e40dc286580097
16,425
ipp
C++
include/fvm/implementation/component/UVWKernels.ipp
thorbenlouw/CUP-CFD
d06f7673a1ed12bef24de4f1b828ef864fa45958
[ "MIT" ]
3
2021-06-24T10:20:12.000Z
2021-07-18T14:43:19.000Z
include/fvm/implementation/component/UVWKernels.ipp
thorbenlouw/CUP-CFD
d06f7673a1ed12bef24de4f1b828ef864fa45958
[ "MIT" ]
2
2021-07-22T15:31:03.000Z
2021-07-28T14:27:28.000Z
include/fvm/implementation/component/UVWKernels.ipp
thorbenlouw/CUP-CFD
d06f7673a1ed12bef24de4f1b828ef864fa45958
[ "MIT" ]
1
2021-07-22T15:24:24.000Z
2021-07-22T15:24:24.000Z
/* * @file * @author University of Warwick * @version 1.0 * * @section LICENSE * These kernels were ported to C++/derived from Dolfyn: * Copyright 2003-2009 Henk Krus, Cyclone Fluid Dynamics BV * All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.dolfyn.net/license.html * * 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. * * * @section DESCRIPTION * */ #ifndef CUPCFD_FVM_UVW_IPP_H #define CUPCFD_FVM_UVW_IPP_H #include <cmath> #include <algorithm> namespace cupcfd { namespace fvm { template <class M, class I, class T, class L> cupcfd::error::eCodes FluxUVWDolfynFaceLoop1(cupcfd::geometry::mesh::UnstructuredMeshInterface<M,I,T,L>& mesh, T gammaBlend, T small, // T large, T * uCell, I nUCell, T * vCell, I nVCell, T * wCell, I nWCell, T * uBoundary, I nUBoundary, T * vBoundary, I nVBoundary, T * wBoundary, I nWBoundary, T * visEffCell, I nVisEffCell, T * visEffBoundary, I nVisEffBoundary, T * massFlux, I nMassFlux, cupcfd::geometry::euclidean::EuclideanVector<T,3> * dudx, I nDudx, cupcfd::geometry::euclidean::EuclideanVector<T,3> * dvdx, I nDvdx, cupcfd::geometry::euclidean::EuclideanVector<T,3> * dwdx, I nDwdx, T * rFace, I nRFace, T * su, I nSu, T * sv, I nSv, T * sw, I nSw, T * au, I nAu, T * av, I nAv, T * aw, I nAw) { // T pe0 = 9999.0; // T pe1 = -9999.0; // T totalForce = 0.0; I ip, in, ib, ir; cupcfd::geometry::mesh::RType it; cupcfd::geometry::euclidean::EuclideanPoint<T,3> xac; T facn; T facp; // T uac, vac, wac; T visac; T visFace; T uFace, vFace, wFace; T fuce, fvce, fwce; T sx, sy, sz; T fude1, fvde1, fwde1; T fude, fvde, fwde; T fmin, fmax; T fuci, fvci, fwci; T fudi, fvdi, fwdi; T blendU, blendV, blendW; T f; // T rlencos; cupcfd::geometry::euclidean::EuclideanVector<T,3> dudxac; cupcfd::geometry::euclidean::EuclideanVector<T,3> dvdxac; cupcfd::geometry::euclidean::EuclideanVector<T,3> dwdxac; cupcfd::geometry::euclidean::EuclideanVector<T,3> xpn; cupcfd::geometry::euclidean::EuclideanVector3D<T> norm; cupcfd::geometry::euclidean::EuclideanPoint<T,3> center1; cupcfd::geometry::euclidean::EuclideanPoint<T,3> center2; cupcfd::geometry::euclidean::EuclideanPoint<T,3> center3; for(I i = 0; i < mesh.properties.lFaces; i++) { #ifdef DEBUG if (i >= nMassFlux) { return cupcfd::error::E_INVALID_INDEX; } #endif // Get Cell 1 Index ip = mesh.getFaceCell1ID(i); // Get Cell 2 Index in = mesh.getFaceCell2ID(i); #ifdef DEBUG if (ip >= nUCell || in >= nUCell) { return cupcfd::error::E_INVALID_INDEX; } if (ip >= nVCell || in >= nVCell) { return cupcfd::error::E_INVALID_INDEX; } if (ip >= nWCell || in >= nWCell) { return cupcfd::error::E_INVALID_INDEX; } if (ip >= nVisEffCell || in >= nVisEffCell) { return cupcfd::error::E_INVALID_INDEX; } if (ip >= nDudx || in >= nDudx) { return cupcfd::error::E_INVALID_INDEX; } if (ip >= nDvdx || in >= nDvdx) { return cupcfd::error::E_INVALID_INDEX; } if (ip >= nDwdx || in >= nDwdx) { return cupcfd::error::E_INVALID_INDEX; } if (ip >= nSu || in >= nSu) { return cupcfd::error::E_INVALID_INDEX; } if (ip >= nSv || in >= nSv) { return cupcfd::error::E_INVALID_INDEX; } if (ip >= nSw || in >= nSw) { return cupcfd::error::E_INVALID_INDEX; } #endif bool isBoundary = mesh.getFaceIsBoundary(i); if(!isBoundary) { // Non-Boundary Face facn = mesh.getFaceLambda(i); facp = 1.0 - facn; xac = (mesh.getCellCenter(in) * facn) + (mesh.getCellCenter(ip) * facp); // uac = uCell[in] * facn + uCell[ip] * facp; // vac = vCell[in] * facn + vCell[ip] * facp; // wac = wCell[in] * facn + wCell[ip] * facp; dudxac = dudx[in] * facn + dudx[ip] * facp; dvdxac = dvdx[in] * facn + dvdx[ip] * facp; dwdxac = dwdx[in] * facn + dwdx[ip] * facp; visac = visEffCell[in] * facn + visEffCell[ip] * facp; xpn = mesh.getCellCenter(in) - mesh.getCellCenter(ip); visFace = visac * mesh.getFaceRLencos(i); // call SelectDiffSchemeVector(i,iScheme,iP,iN, & // U,V,W, & // dUdX,dVdX,dWdX, & // UFace,VFace,Wface) fuce = massFlux[i] * uFace; fvce = massFlux[i] * vFace; fwce = massFlux[i] * wFace; mesh.getFaceNorm(i, norm); sx = norm.cmp[0]; sy = norm.cmp[1]; sz = norm.cmp[2]; fude1 = (dudxac.cmp[0] + dudxac.cmp[0]) * sx + (dudxac.cmp[1] + dvdxac.cmp[0]) * sy + (dudxac.cmp[2] + dwdxac.cmp[0]) * sz; fvde1 = (dudxac.cmp[1] + dvdxac.cmp[0]) * sx + (dvdxac.cmp[1] + dvdxac.cmp[1]) * sy + (dvdxac.cmp[2] + dwdxac.cmp[1]) * sz; fwde1 = (dudxac.cmp[2] + dwdxac.cmp[0]) * sx + (dwdxac.cmp[1] + dvdxac.cmp[2]) * sy + (dwdxac.cmp[2] + dwdxac.cmp[2]) * sz; fude = visac * fude1; fvde = visac * fvde1; fwde = visac * fwde1; fmin = std::min(massFlux[i], T(0.0)); fmax = std::max(massFlux[i], T(0.0)); fuci = fmin * uCell[in] + fmax * uCell[ip]; fvci = fmin * vCell[in] + fmax * vCell[ip]; fwci = fmin * wCell[in] + fmax * wCell[ip]; fudi = visFace * dudxac.dotProduct(xpn); fvdi = visFace * dvdxac.dotProduct(xpn); fwdi = visFace * dwdxac.dotProduct(xpn); #ifndef NDEBUG if ((i*2)+1 >= nRFace) { return cupcfd::error::E_INVALID_INDEX; } #endif rFace[i*2] = -visFace - std::max(massFlux[i], T(0.0)); rFace[(i*2)+1] = -visFace + std::min(massFlux[i], T(0.0)); blendU = gammaBlend * (fuce - fuci); blendV = gammaBlend * (fvce - fvci); blendW = gammaBlend * (fwce - fwci); su[ip] = su[ip] - blendU + fude - fudi; su[in] = su[in] + blendU - fude + fudi; sv[ip] = sv[ip] - blendV + fvde - fvdi; sv[in] = sv[in] + blendV - fvde + fvdi; sw[ip] = sw[ip] - blendW + fwde - fwdi; sw[in] = sw[in] + blendW - fwde + fwdi; // T xpn_length = (T)xpn.length(); // Leave these off for now, may reenable at later point // T peclet; // peclet = massFlux[i]/mesh.getFaceArea(i) * xpn_length/(visac+small); //pe0 = min(pe0, peclet); //pe1 = max(pe1, peclet); } else { ib = mesh.getFaceBoundaryID(i); ir = mesh.getBoundaryRegionID(ib); it = mesh.getRegionType(ir); ip = mesh.getFaceCell1ID(i); #ifdef DEBUG if (ib >= nUBoundary) { return cupcfd::error::E_INVALID_INDEX; } if (ib >= nVBoundary) { return cupcfd::error::E_INVALID_INDEX; } if (ib >= nWBoundary) { return cupcfd::error::E_INVALID_INDEX; } if (ib >= nVisEffBoundary) { return cupcfd::error::E_INVALID_INDEX; } if (ip >= nAu) { return cupcfd::error::E_INVALID_INDEX; } if (ip >= nAv) { return cupcfd::error::E_INVALID_INDEX; } if (ip >= nAw) { return cupcfd::error::E_INVALID_INDEX; } #endif // Boundary Face if(it == cupcfd::geometry::mesh::RTYPE_INLET) { // Skip/Ignore User/UserInlet for now dudxac = dudx[ip]; dvdxac = dvdx[ip]; dwdxac = dwdx[ip]; xac = mesh.getFaceCenter(i); cupcfd::geometry::euclidean::EuclideanVector<T,3> uvw = mesh.getRegionUVW(ir); uFace = uvw.cmp[0]; vFace = uvw.cmp[1]; wFace = uvw.cmp[2]; visac = visEffBoundary[ib]; xpn = xac - mesh.getCellCenter(ip); visFace = visac * mesh.getFaceRLencos(i); fuce = massFlux[i] * uFace; fvce = massFlux[i] * vFace; fwce = massFlux[i] * wFace; norm = mesh.getFaceNorm(i); sx = norm.cmp[0]; sy = norm.cmp[1]; sz = norm.cmp[2]; fude = (dudxac.cmp[0] + dudxac.cmp[0]) * sx + (dudxac.cmp[1] + dvdxac.cmp[0]) * sy + (dudxac.cmp[2] + dwdxac.cmp[0]) * sz; fvde = (dudxac.cmp[1] + dvdxac.cmp[0]) * sx + (dvdxac.cmp[1] + dvdxac.cmp[1]) * sy + (dvdxac.cmp[2] + dwdxac.cmp[1]) * sz; fwde = (dudxac.cmp[2] + dwdxac.cmp[0]) * sx + (dwdxac.cmp[1] + dvdxac.cmp[2]) * sy + (dwdxac.cmp[2] + dwdxac.cmp[2]) * sz; fude = visac * fude; fvde = visac * fvde; fwde = visac * fwde; fmin = std::min(massFlux[i], T(0.0)); fmax = std::max(massFlux[i], T(0.0)); fuci = fmin * uFace + fmax * uCell[ip]; fvci = fmin * vFace + fmax * vCell[ip]; fwci = fmin * wFace + fmax * wCell[ip]; fudi = visFace * dudxac.dotProduct(xpn); fvdi = visFace * dvdxac.dotProduct(xpn); fwdi = visFace * dwdxac.dotProduct(xpn); f = -visFace + std::min(massFlux[i], T(0.0)); au[ip] = au[ip] - f; su[ip] = su[ip] - f * uFace + fude - fudi; uBoundary[ib] = uFace; av[ip] = av[ip] - f; sv[ip] = sv[ip] - f * vFace + fvde - fvdi; vBoundary[ib] = vFace; aw[ip] = aw[ip] - f; sw[ip] = sw[ip] - f * wFace + fwde - fwdi; wBoundary[ib] = wFace; } else if(it == cupcfd::geometry::mesh::RTYPE_OUTLET) { dudxac = dudx[ip]; dvdxac = dvdx[ip]; dwdxac = dwdx[ip]; xac = mesh.getFaceCenter(i); visac = visEffCell[ip]; xpn = xac - mesh.getCellCenter(ip); uFace = uCell[ip]; vFace = vCell[ip]; wFace = wCell[ip]; visFace = visac * mesh.getFaceRLencos(i); fuce = massFlux[i] * uFace; fvce = massFlux[i] * vFace; fwce = massFlux[i] * wFace; norm = mesh.getFaceNorm(i); sx = norm.cmp[0]; sy = norm.cmp[1]; sz = norm.cmp[2]; fude = (dudxac.cmp[0] + dudxac.cmp[0]) * sx + (dudxac.cmp[1] + dvdxac.cmp[0]) * sy + (dudxac.cmp[2] + dwdxac.cmp[0]) * sz; fvde = (dvdxac.cmp[0] + dudxac.cmp[1]) * sx + (dvdxac.cmp[1] + dvdxac.cmp[1]) * sy + (dvdxac.cmp[2] + dwdxac.cmp[1]) * sz; fwde = (dwdxac.cmp[0] + dudxac.cmp[2]) * sx + (dwdxac.cmp[1] + dvdxac.cmp[2]) * sy + (dwdxac.cmp[2] + dwdxac.cmp[2]) * sz; fude = visac * fude; fvde = visac * fvde; fwde = visac * fwde; fmin = std::min(massFlux[i], T(0.0)); fmax = std::max(massFlux[i], T(0.0)); fuci = fmin * uFace + fmax * uCell[ip]; fvci = fmin * vFace + fmax * vCell[ip]; fwci = fmin * wFace + fmax * wCell[ip]; fudi = visFace * dudxac.dotProduct(xpn); fvdi = visFace * dvdxac.dotProduct(xpn); fwdi = visFace * dwdxac.dotProduct(xpn); if(massFlux[i] < 0.0) { massFlux[i] = small; } f = -visFace + std::min(massFlux[i], T(0.0)); au[ip] = au[ip] - f; su[ip] = su[ip] -f * uFace + fude - fudi; uBoundary[ib] = uFace; av[ip] = av[ip] - f; sv[ip] = sv[ip] - f * vFace + fvde - fvdi; vBoundary[ib] = vFace; aw[ip] = aw[ip] - f; sw[ip] = sw[ip] - f * wFace + fwde - fwdi; wBoundary[ib] = wFace; } else if(it == cupcfd::geometry::mesh::RTYPE_SYMP) { cupcfd::geometry::euclidean::EuclideanVector<T,3> tmp; xac = mesh.getFaceCenter(i); xpn = xac - mesh.getCellCenter(ip); dudxac = dudx[ip]; dvdxac = dvdx[ip]; dwdxac = dwdx[ip]; visac = visEffCell[ip]; // T rDotProduct; T du, dv, dw, dp, dn; cupcfd::geometry::euclidean::EuclideanVector3D<T> xn; cupcfd::geometry::euclidean::EuclideanVector<T,3> un; cupcfd::geometry::euclidean::EuclideanVector<T,3> tauNN; cupcfd::geometry::euclidean::EuclideanVector<T,3> us; cupcfd::geometry::euclidean::EuclideanVector<T,3> force; du = dudxac.dotProduct(xpn); dv = dvdxac.dotProduct(xpn); dw = dwdxac.dotProduct(xpn); us.cmp[0] = uCell[ip] + du; us.cmp[1] = vCell[ip] + dv; us.cmp[2] = wCell[ip] + dw; xn = 0.0 - mesh.getFaceNorm(i); xn.normalise(); dp = us.dotProduct(xn); un = dp * xn; dn = mesh.getBoundaryDistance(ib); tauNN = 2.0 * visac * un/dn; force = tauNN * mesh.getFaceArea(i); // Assume not initialisation //if(!init) //{ au[ip] = au[ip] + visFace; av[ip] = av[ip] + visFace; aw[ip] = aw[ip] + visFace; su[ip] = su[ip] + visFace * uCell[ip] - force.cmp[0]; sv[ip] = sv[ip] + visFace * vCell[ip] - force.cmp[1]; sw[ip] = sw[ip] + visFace * wCell[ip] - force.cmp[2]; //} uBoundary[ib] = us.cmp[0]; vBoundary[ib] = us.cmp[1]; wBoundary[ib] = us.cmp[2]; } else if(it == cupcfd::geometry::mesh::RTYPE_WALL) { T coef; T dp, dn; T uvel; cupcfd::geometry::euclidean::EuclideanVector<T,3> uw; cupcfd::geometry::euclidean::EuclideanVector<T,3> un; cupcfd::geometry::euclidean::EuclideanVector3D<T> xn; cupcfd::geometry::euclidean::EuclideanVector<T,3> up; cupcfd::geometry::euclidean::EuclideanVector<T,3> ut; cupcfd::geometry::euclidean::EuclideanVector<T,3> tauNT; cupcfd::geometry::euclidean::EuclideanVector<T,3> force; cupcfd::geometry::euclidean::EuclideanVector<T,3> tmp; xac = mesh.getFaceCenter(i); uw = mesh.getRegionUVW(ir); dudxac = dudx[ip]; dvdxac = dvdx[ip]; dwdxac = dwdx[ip]; visac = visEffBoundary[ib]; xpn = mesh.getFaceCenter(i) - mesh.getCellCenter(ip); // ToDo: Do we want to force this to be a double here? // May also wish for it to just be a float - move out to template? T xpn_length = xpn.length(); coef = visac * mesh.getFaceArea(i) / xpn_length; xn = mesh.getFaceNorm(i); xn.normalise(); up.cmp[0] = uCell[ip]; up.cmp[1] = vCell[ip]; up.cmp[2] = wCell[ip]; up = up - uw; dp = up.dotProduct(xn); un = dp * xn; ut = up - un; uvel = fabs(ut.cmp[0]) + fabs(ut.cmp[1]) + fabs(ut.cmp[2]); if(uvel > small) { dn = mesh.getBoundaryDistance(ib); tauNT = visac * ut/dn; force = tauNT * mesh.getFaceArea(i); mesh.setBoundaryShear(ib, force); } else { force.cmp[0] = 0.0; force.cmp[1] = 0.0; force.cmp[2] = 0.0; mesh.setBoundaryShear(ib, force); } // Assume not initialisation? //if(!init) //{ au[ip] = au[ip] + coef; av[ip] = av[ip] + coef; aw[ip] = aw[ip] + coef; su[ip] = su[ip] + coef * uCell[ip] - force.cmp[0]; sv[ip] = sv[ip] + coef * vCell[ip] - force.cmp[1]; sw[ip] = sw[ip] + coef * wCell[ip] - force.cmp[2]; //} uBoundary[ib] = uw.cmp[0]; vBoundary[ib] = uw.cmp[1]; wBoundary[ib] = uw.cmp[2]; } } } return cupcfd::error::E_SUCCESS; } template <class M, class I, class T, class L> void FluxUVWDolfynRegionLoop1(cupcfd::geometry::mesh::UnstructuredMeshInterface<M,I,T,L>& mesh) { I ir; cupcfd::geometry::euclidean::EuclideanVector<T,3> zero((T) 0, (T) 0, (T) 0); for(ir = 0; ir < mesh.properties.lRegions; ir++) { mesh.setRegionForceTangent(ir, zero); } } template <class M, class I, class T, class L> void FluxUVWDolfynBndsLoop1(cupcfd::geometry::mesh::UnstructuredMeshInterface<M,I,T,L>& mesh) { I ib, ir; cupcfd::geometry::mesh::RType it; cupcfd::geometry::euclidean::EuclideanVector<T,3> shear; cupcfd::geometry::euclidean::EuclideanVector<T,3> forceTangent; cupcfd::geometry::euclidean::EuclideanVector<T,3> tmp; for(ib = 0; ib < mesh.properties.lBoundaries; ib++) { ir = mesh.getBoundaryRegionID(ib); it = mesh.getRegionType(ir); if(it == cupcfd::geometry::mesh::RTYPE_WALL) { tmp = mesh.getRegionForceTangent(ir) + mesh.getBoundaryShear(ib); mesh.setRegionForceTangent(ir, tmp); } } } } } #endif
29.918033
128
0.561157
thorbenlouw
a7cb9a2c143254217942cbfb71b3dbaf38a32baf
47
hpp
C++
src/boost_property_tree_string_path.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
10
2018-03-17T00:58:42.000Z
2021-07-06T02:48:49.000Z
src/boost_property_tree_string_path.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
2
2021-03-26T15:17:35.000Z
2021-05-20T23:55:08.000Z
src/boost_property_tree_string_path.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
4
2019-05-28T21:06:37.000Z
2021-07-06T03:06:52.000Z
#include <boost/property_tree/string_path.hpp>
23.5
46
0.829787
miathedev
a7d138fd1dede1938dc88228a1f8a601b9c3d419
32,104
cpp
C++
src/IL/ILInstr.cpp
fencl/Crs
902f6f293bcf33ff71ca6cfc306d8b833d1e0e63
[ "MIT" ]
null
null
null
src/IL/ILInstr.cpp
fencl/Crs
902f6f293bcf33ff71ca6cfc306d8b833d1e0e63
[ "MIT" ]
null
null
null
src/IL/ILInstr.cpp
fencl/Crs
902f6f293bcf33ff71ca6cfc306d8b833d1e0e63
[ "MIT" ]
null
null
null
#include "IL.hpp" namespace Crs { using il_l_itr = std::vector<std::uint8_t>::iterator&; using il_b = ILBlock*&; struct il_no_pass { }; #define il_exec static errvoid exec(ILInstruction instr,il_l_itr it, il_b block, il_no_pass& pass) { #define il_print static errvoid print(ILInstruction instr,il_l_itr it, il_b block, il_no_pass& pass) { #define il_ok return err::ok; } struct il_memop_instr { il_exec { auto size = ILBlock::read_data<ILSize>(it); switch (instr) { case ILInstruction::memcpy: return ILBuilder::eval_memcpy(size); case ILInstruction::memcpy2: return ILBuilder::eval_memcpy_rev(size); case ILInstruction::memcmp: return ILBuilder::eval_memcmp(size); case ILInstruction::memcmp2: return ILBuilder::eval_memcmp_rev(size); } } il_ok; il_print { auto size = ILBlock::read_data<ILSize>(it); switch (instr) { case ILInstruction::memcpy: std::cout<<"memcpy "; size.print(ILEvaluator::active->parent); std::cout<<"\n"; break; case ILInstruction::memcpy2: std::cout<<"memcpy rev "; size.print(ILEvaluator::active->parent); std::cout<<"\n"; break; case ILInstruction::memcmp: std::cout<<"memcmp "; size.print(ILEvaluator::active->parent); std::cout<<"\n"; break; case ILInstruction::memcmp2: std::cout<<"memcmp rev "; size.print(ILEvaluator::active->parent); std::cout<<"\n"; break; } } il_ok; }; struct il_clone_instr { il_exec { auto type = ILBlock::read_data<ILDataType>(it); auto times = ILBlock::read_data<std::uint16_t>(it); if (!ILBuilder::eval_clone(type, times)) return err::fail; } il_ok; il_print { auto type = ILBlock::read_data<ILDataType>(it); auto times = ILBlock::read_data<std::uint16_t>(it); std::cout<<"clone "<<times<<"\n"; } il_ok; }; struct il_swap2_instr { il_exec { auto p = ILBlock::read_data<ILDataTypePair>(it); if (!ILBuilder::eval_swap2(p.first(), p.second())) return err::fail; } il_ok; il_print { auto p = ILBlock::read_data<ILDataTypePair>(it); std::cout<<"swap pair "; ILBlock::dump_data_type(p.first()); std::cout<<" "; ILBlock::dump_data_type(p.second()); std::cout<<"\n"; } il_ok; }; struct il_insintric_instr { il_exec { auto id = ILBlock::read_data<std::uint8_t>(it); if (!ILBuilder::eval_insintric((ILInsintric)id)) return err::fail; } il_ok; il_print { auto id = ILBlock::read_data<std::uint8_t>(it); std::cout<<"insintric "<<id<<"\n"; } il_ok; }; struct il_operator_instr { il_exec { auto type = ILBlock::read_data<ILDataTypePair>(it); switch (instr) { case ILInstruction::sub: return ILBuilder::eval_sub(type.first(), type.second()); case ILInstruction::div: return ILBuilder::eval_div(type.first(), type.second()); case ILInstruction::rem: return ILBuilder::eval_rem(type.first(), type.second()); case ILInstruction::mul: return ILBuilder::eval_mul(type.first(), type.second()); case ILInstruction::add: return ILBuilder::eval_add(type.first(), type.second()); case ILInstruction::bit_and: return ILBuilder::eval_and(type.first(), type.second()); case ILInstruction::bit_or: return ILBuilder::eval_or(type.first(), type.second()); case ILInstruction::bit_xor: return ILBuilder::eval_xor(type.first(), type.second()); case ILInstruction::eq: return ILBuilder::eval_eq(type.first(), type.second()); case ILInstruction::ne: return ILBuilder::eval_ne(type.first(), type.second()); case ILInstruction::gt: return ILBuilder::eval_gt(type.first(), type.second()); case ILInstruction::lt: return ILBuilder::eval_lt(type.first(), type.second()); case ILInstruction::ge: return ILBuilder::eval_ge(type.first(), type.second()); case ILInstruction::le: return ILBuilder::eval_le(type.first(), type.second()); case ILInstruction::cast: return ILBuilder::eval_cast(type.first(), type.second()); case ILInstruction::bitcast: return ILBuilder::eval_bitcast(type.first(), type.second()); } } il_ok; il_print { auto type = ILBlock::read_data<ILDataTypePair>(it); switch (instr) { case ILInstruction::sub: std::cout<<"sub "; break; case ILInstruction::div: std::cout<<"div "; break; case ILInstruction::rem: std::cout<<"rem "; break; case ILInstruction::mul: std::cout<<"mul "; break; case ILInstruction::add: std::cout<<"add "; break; case ILInstruction::bit_and: std::cout<<"and "; break; case ILInstruction::bit_or: std::cout<<"or "; break; case ILInstruction::bit_xor: std::cout<<"xor "; break; case ILInstruction::eq: std::cout<<"eq "; break; case ILInstruction::ne: std::cout<<"ne "; break; case ILInstruction::gt: std::cout<<"gt "; break; case ILInstruction::lt: std::cout<<"lt "; break; case ILInstruction::ge: std::cout<<"ge "; break; case ILInstruction::le: std::cout<<"le "; break; case ILInstruction::cast: std::cout<<"cast "; break; case ILInstruction::bitcast: std::cout<<"bitcast "; break; } ILBlock::dump_data_type(type.first()); std::cout<<" "; ILBlock::dump_data_type(type.second()); std::cout<<"\n"; } il_ok; }; struct il_regop_instr { il_exec { auto type = ILBlock::read_data<ILDataType>(it); switch (instr) { case ILInstruction::swap: return ILBuilder::eval_swap(type); case ILInstruction::duplicate: return ILBuilder::eval_duplicate(type); case ILInstruction::isnotzero: return ILBuilder::eval_isnotzero(type); case ILInstruction::negative: return ILBuilder::eval_negative(type); case ILInstruction::forget: return ILBuilder::eval_forget(type); case ILInstruction::load: return ILBuilder::eval_load(type); case ILInstruction::store: return ILBuilder::eval_store(type); case ILInstruction::store2: return ILBuilder::eval_store_rev(type); case ILInstruction::yield: return ILBuilder::eval_yield(type); case ILInstruction::accept: return ILBuilder::eval_accept(type); case ILInstruction::discard: return ILBuilder::eval_discard(type); case ILInstruction::rmemcmp: return ILBuilder::eval_rmemcmp(type); case ILInstruction::rmemcmp2: return ILBuilder::eval_rmemcmp_rev(type); case ILInstruction::ret: it = block->data_pool.end(); return err::ok; } } il_ok; il_print { auto type = ILBlock::read_data<ILDataType>(it); switch (instr) { case ILInstruction::swap: std::cout<<"swap "; break; case ILInstruction::duplicate: std::cout<<"duplicate "; break; case ILInstruction::isnotzero: std::cout<<"not zero "; break; case ILInstruction::negative: std::cout<<"negative "; break; case ILInstruction::forget: std::cout<<"forget "; break; case ILInstruction::load: std::cout<<"load "; break; case ILInstruction::store: std::cout<<"store "; break; case ILInstruction::store2: std::cout<<"store rev "; break; case ILInstruction::yield: std::cout<<"yield "; break; case ILInstruction::accept: std::cout<<"accept "; break; case ILInstruction::discard: std::cout<<"discard "; break; case ILInstruction::rmemcmp: std::cout<<"rmemcmp "; break; case ILInstruction::rmemcmp2: std::cout<<"rmemcmp rev "; break; case ILInstruction::ret: std::cout<<"ret "; break; } ILBlock::dump_data_type(type); std::cout<<"\n"; } il_ok; }; struct il_simple_instr { il_exec { switch (instr) { case ILInstruction::negate: return ILBuilder::eval_negate(); case ILInstruction::panic: return ILBuilder::eval_panic(); case ILInstruction::combinedw: return ILBuilder::eval_combine_dword(); case ILInstruction::highdw: return ILBuilder::eval_high_word(); case ILInstruction::lowdw: return ILBuilder::eval_low_word(); case ILInstruction::splitdw: return ILBuilder::eval_split_dword(); case ILInstruction::start: return ILBuilder::eval_callstart(); case ILInstruction::null: return ILBuilder::eval_null(); case ILInstruction::rtoffset: return ILBuilder::eval_rtoffset(); case ILInstruction::rtoffset2: return ILBuilder::eval_rtoffset_rev(); } } il_ok; il_print { switch (instr) { case ILInstruction::negate: std::cout<<"negate\n"; break; case ILInstruction::panic: std::cout<<"panic\n"; break; case ILInstruction::combinedw: std::cout<<"combine dword\n"; break; case ILInstruction::highdw: std::cout<<"high dword\n"; break; case ILInstruction::lowdw: std::cout<<"low dword\n"; break; case ILInstruction::splitdw: std::cout<<"split dword\n"; break; case ILInstruction::start: std::cout<<"start\n"; break; case ILInstruction::null: std::cout<<"null\n"; break; case ILInstruction::rtoffset: std::cout<<"rtoffset\n"; break; case ILInstruction::rtoffset2: std::cout<<"rtoffset rev\n"; break; } } il_ok; }; template<typename T> struct il_size_instr { il_exec { auto t = ILBlock::read_data<ILSizeType>(it); auto v = ILBlock::read_data<T>(it); ILSize s(t,(std::uint32_t)v); switch (instr) { case ILInstruction::offset8: case ILInstruction::offset16: case ILInstruction::offset32: return ILBuilder::eval_offset(s); case ILInstruction::extract8: case ILInstruction::extract16: case ILInstruction::extract32: return ILBuilder::eval_extract(s); case ILInstruction::cut8: case ILInstruction::cut16: case ILInstruction::cut32: return ILBuilder::eval_cut(s); case ILInstruction::size8: case ILInstruction::size16: case ILInstruction::size32: return ILBuilder::eval_const_size(s); } } il_ok; il_print { auto t = ILBlock::read_data<ILSizeType>(it); auto v = ILBlock::read_data<T>(it); ILSize s(t,(std::uint32_t)v); switch (instr) { case ILInstruction::offset8: case ILInstruction::offset16: case ILInstruction::offset32: std::cout<<"offset "; break; case ILInstruction::extract8: case ILInstruction::extract16: case ILInstruction::extract32: std::cout<<"extract "; break; case ILInstruction::cut8: case ILInstruction::cut16: case ILInstruction::cut32: std::cout<<"cut "; break; case ILInstruction::size8: case ILInstruction::size16: case ILInstruction::size32: std::cout<<"size "; break; } s.print(ILEvaluator::active->parent); std::cout<<"\n"; } il_ok; }; template<typename T> struct il_aoffset_instr { il_exec { auto s = ILBlock::read_data<T>(it); return ILBuilder::eval_aoffset((std::uint32_t)s); } il_ok; il_print { auto s = ILBlock::read_data<T>(it); std::cout<<"aoffset "<<(std::uint32_t)s<<"\n"; } il_ok; }; template<typename T> struct il_woffset_instr { il_exec{ auto s = ILBlock::read_data<T>(it); return ILBuilder::eval_woffset((std::uint32_t)s); } il_ok; il_print { auto s = ILBlock::read_data<T>(it); std::cout<<"woffset "<<(std::uint32_t)s<<"\n"; } il_ok; }; struct il_const_u8_instr { il_exec { auto s = ILBlock::read_data<std::uint8_t>(it); return ILBuilder::eval_const_u8(s); } il_ok; il_print { auto s = ILBlock::read_data<std::uint8_t>(it); std::cout<<"u8 " << (std::uint64_t)s<<"\n"; } il_ok; }; struct il_const_i8_instr { il_exec { auto s = ILBlock::read_data<std::uint8_t>(it); return ILBuilder::eval_const_i8(s); } il_ok; il_print { auto s = ILBlock::read_data<std::int8_t>(it); std::cout<<"i8 " << (std::int64_t)s<<"\n"; } il_ok; }; template<typename T> struct il_const_u16_instr { il_exec { auto s = ILBlock::read_data<T>(it); return ILBuilder::eval_const_u16((std::uint16_t)s); } il_ok; il_print { auto s = ILBlock::read_data<T>(it); std::cout<<"u16 " << (std::uint64_t)s<<"\n"; } il_ok; }; template<typename T> struct il_const_i16_instr { il_exec { auto s = ILBlock::read_data<T>(it); return ILBuilder::eval_const_i16((std::int16_t)s); } il_ok; il_print { auto s = ILBlock::read_data<T>(it); std::cout<<"i16 " << (std::int64_t)s<<"\n"; } il_ok; }; template<typename T> struct il_const_u32_instr { il_exec { auto s = ILBlock::read_data<T>(it); return ILBuilder::eval_const_u32((std::uint32_t)s); } il_ok; il_print { auto s = ILBlock::read_data<T>(it); std::cout<<"u32 " << (std::uint64_t)s<<"\n"; } il_ok; }; template<typename T> struct il_const_i32_instr { il_exec { auto s = ILBlock::read_data<T>(it); return ILBuilder::eval_const_i32((std::int32_t)s); } il_ok; il_print { auto s = ILBlock::read_data<T>(it); std::cout<<"i32 " << (std::int64_t)s<<"\n"; } il_ok; }; template<typename T> struct il_const_u64_instr { il_exec { auto s = ILBlock::read_data<T>(it); return ILBuilder::eval_const_u64((std::uint64_t)s); } il_ok; il_print { auto s = ILBlock::read_data<T>(it); std::cout<<"u64 " << (std::uint64_t)s<<"\n"; } il_ok; }; template<typename T> struct il_const_i64_instr { il_exec { auto s = ILBlock::read_data<T>(it); return ILBuilder::eval_const_i64((std::int64_t)s); } il_ok; il_print { auto s = ILBlock::read_data<T>(it); std::cout<<"i64 " << (std::int64_t)s<<"\n"; } il_ok; }; struct il_const_f32_instr { il_exec { auto s = ILBlock::read_data<float>(it); return ILBuilder::eval_const_f32(s); } il_ok; il_print { auto s = ILBlock::read_data<float>(it); std::cout<<"f32 " << s <<"\n"; } il_ok; }; struct il_const_f64_instr { il_exec { auto s = ILBlock::read_data<float>(it); return ILBuilder::eval_const_f64(s); } il_ok; il_print { auto s = ILBlock::read_data<double>(it); std::cout<<"f64 " << s <<"\n"; } il_ok; }; struct il_const_word_instr { il_exec{ auto s = ILBlock::read_data<void*>(it); return ILBuilder::eval_const_word(s); } il_ok; il_print { auto s = ILBlock::read_data<std::size_t>(it); std::cout<<"word " << s <<"\n"; } il_ok; }; struct il_const_dword_instr { il_exec { auto v1 = ILBlock::read_data<void*>(it); auto v2 = ILBlock::read_data<void*>(it); dword_t dw = {v1,v2}; return ILBuilder::eval_const_dword(dw); } il_ok; il_print { auto v1 = ILBlock::read_data<std::size_t>(it); auto v2 = ILBlock::read_data<std::size_t>(it); std::cout<<"dword " << v1 << ", " << v2 <<"\n"; } il_ok; }; template<typename T> struct il_identifier_instr { il_exec { auto v = ILBlock::read_data<T>(it); switch (instr) { case ILInstruction::local8: case ILInstruction::local16: case ILInstruction::local32: { auto& offset = block->parent->calculated_local_offsets[v]; return ILBuilder::eval_const_word(ILEvaluator::active->stack_base_aligned + offset); } case ILInstruction::call8: case ILInstruction::call16: case ILInstruction::call32: return ILBuilder::eval_call(v); case ILInstruction::constref: return ILBuilder::eval_constref(v); case ILInstruction::staticref: return ILBuilder::eval_staticref(v); case ILInstruction::fnptr8: case ILInstruction::fnptr16: case ILInstruction::fnptr32: return ILBuilder::eval_fnptr(ILEvaluator::active->parent->functions[v].get()); case ILInstruction::fncall8: case ILInstruction::fncall16: case ILInstruction::fncall32: return ILBuilder::eval_fncall(ILEvaluator::active->parent->functions[v].get()); case ILInstruction::vtable: return ILBuilder::eval_vtable(v); case ILInstruction::jmp8: case ILInstruction::jmp16: case ILInstruction::jmp32: { block = block->parent->blocks_memory[v].get(); it = block->data_pool.begin(); return err::ok; } } } il_ok; il_print { auto v = ILBlock::read_data<T>(it); switch (instr) { case ILInstruction::local8: case ILInstruction::local16: case ILInstruction::local32: std::cout<<"local "; break; case ILInstruction::call8: case ILInstruction::call16: case ILInstruction::call32: std::cout<<"call "; break; case ILInstruction::constref: std::cout<<"constref "; break; case ILInstruction::staticref: std::cout<<"staticref "; break; case ILInstruction::fnptr8: case ILInstruction::fnptr16: case ILInstruction::fnptr32: std::cout<<"fnptr "; break; case ILInstruction::fncall8: case ILInstruction::fncall16: case ILInstruction::fncall32: std::cout<<"fncall "; break; case ILInstruction::vtable: std::cout<<"vtable "; break; case ILInstruction::jmp8: case ILInstruction::jmp16: case ILInstruction::jmp32: std::cout<<"jmp "; break; } std::cout << (std::uint64_t)v << "\n"; } il_ok; }; struct il_jmpz_instr { il_exec { auto v1 = ILBlock::read_data<std::uint32_t>(it); auto v2 = ILBlock::read_data<std::uint32_t>(it); std::uint8_t z; if (!ILEvaluator::active->pop_register_value<std::uint8_t>(z)) return err::fail; if (z) { block = block->parent->blocks_memory[v2].get(); it = block->data_pool.begin(); } else { block = block->parent->blocks_memory[v1].get(); it = block->data_pool.begin(); } } il_ok; il_print { auto v1 = ILBlock::read_data<std::uint32_t>(it); auto v2 = ILBlock::read_data<std::uint32_t>(it); std::cout<<"jmpz " << v1 << ", "<<v2<<"\n"; } il_ok; }; template<typename T> struct il_roffset_instr { il_exec { auto types = ILBlock::read_data<ILDataTypePair>(it); auto t = ILBlock::read_data<ILSizeType>(it); auto v = ILBlock::read_data<T>(it); return ILBuilder::eval_roffset(types.first(), types.second(), ILSize(t,(std::uint32_t)v)); } il_ok; il_print { auto types = ILBlock::read_data<ILDataTypePair>(it); auto t = ILBlock::read_data<ILSizeType>(it); auto v = ILBlock::read_data<T>(it); std::cout<<"roffset "; ILBlock::dump_data_type(types.first()); std::cout<<" "; ILBlock::dump_data_type(types.second()); std::cout<<" "; ILSize(t,(std::uint32_t)v).print(ILEvaluator::active->parent); std::cout<<"\n"; } il_ok; }; struct il_aroffset_instr { il_exec { auto types = ILBlock::read_data<ILDataTypePair>(it); auto v = ILBlock::read_data<std::uint8_t>(it); return ILBuilder::eval_aroffset(types.first(), types.second(), (std::uint32_t)v); } il_ok; il_print { auto types = ILBlock::read_data<ILDataTypePair>(it); auto v = ILBlock::read_data<std::uint8_t>(it); std::cout<<"aroffset "; ILBlock::dump_data_type(types.first()); std::cout<<" "; ILBlock::dump_data_type(types.second()); std::cout<<" "<<(std::uint64_t)v<<"\n"; } il_ok; }; struct il_wroffset_instr { il_exec { auto types = ILBlock::read_data<ILDataTypePair>(it); auto v = ILBlock::read_data<std::uint8_t>(it); return ILBuilder::eval_wroffset(types.first(), types.second(), (std::uint32_t)v); } il_ok; il_print { auto types = ILBlock::read_data<ILDataTypePair>(it); auto v = ILBlock::read_data<std::uint8_t>(it); std::cout<<"wroffset "; ILBlock::dump_data_type(types.first()); std::cout<<" "; ILBlock::dump_data_type(types.second()); std::cout<<" "<<(std::uint64_t)v<<"\n"; } il_ok; }; template<typename T1, typename T2> struct il_tableoffset_instr { il_exec { auto v1 = ILBlock::read_data<T1>(it); auto v2 = ILBlock::read_data<T2>(it); return ILBuilder::eval_tableoffset(v1, v2); } il_ok; il_print { auto v1 = ILBlock::read_data<T1>(it); auto v2 = ILBlock::read_data<T2>(it); std::cout<<"tableoffset "<<(std::uint64_t) v1<<" "<<(std::uint64_t)v2<<"\n"; } il_ok; }; struct il_debug_instr { il_exec { auto v1 = ILBlock::read_data<std::uint16_t>(it); auto v2 = ILBlock::read_data<std::uint16_t>(it); return ILBuilder::eval_debug(v1, v2); } il_ok; il_print { auto v1 = ILBlock::read_data<std::uint16_t>(it); auto v2 = ILBlock::read_data<std::uint16_t>(it); } il_ok; }; struct il_slice_instr { il_exec { std::uint32_t cid = ILBlock::read_data<std::uint32_t>(it); auto st = ILBlock::read_data<ILSizeType>(it); auto sv = ILBlock::read_data<std::uint32_t>(it); return ILBuilder::eval_const_slice(cid, ILSize(st,sv)); } il_ok; il_print { std::uint32_t cid = ILBlock::read_data<std::uint32_t>(it); auto st = ILBlock::read_data<ILSizeType>(it); auto sv = ILBlock::read_data<std::uint32_t>(it); std::cout<<"slice " << cid << " "; ILSize(st,sv).print(ILEvaluator::active->parent); std::cout<<"\n"; } il_ok; }; template<template<typename Ty1, typename Ty2> class op, typename P, typename E> errvoid loop_code(ILBytecodeFunction* fun, P& pass) { ILBlock* block = fun->blocks[0]; auto it = block->data_pool.begin(); while (true) { if (it == block->data_pool.end()) { if (E::block_end(it,block)) continue; else break; } auto inst = block->read_data<ILInstruction>(it); E::pre(inst, it, block); switch (inst) { case ILInstruction::memcpy: case ILInstruction::memcpy2: case ILInstruction::memcmp: case ILInstruction::memcmp2: if (!op<il_memop_instr, P>::call(inst, it, block, pass)) return err::fail; break; case ILInstruction::clone: if (!op<il_clone_instr, P>::call(inst, it, block, pass)) return err::fail; break; case ILInstruction::swap2: if (!op<il_swap2_instr, P>::call(inst, it, block, pass)) return err::fail; break; case ILInstruction::insintric: if (!op<il_insintric_instr, P>::call(inst, it, block, pass)) return err::fail; break; case ILInstruction::sub: case ILInstruction::div: case ILInstruction::rem: case ILInstruction::mul: case ILInstruction::add: case ILInstruction::bit_and: case ILInstruction::bit_or: case ILInstruction::bit_xor: case ILInstruction::eq: case ILInstruction::ne: case ILInstruction::gt: case ILInstruction::lt: case ILInstruction::ge: case ILInstruction::le: case ILInstruction::cast: case ILInstruction::bitcast: if (!op<il_operator_instr, P>::call(inst, it, block, pass)) return err::fail; break; case ILInstruction::duplicate: case ILInstruction::isnotzero: case ILInstruction::forget: case ILInstruction::negative: case ILInstruction::load: case ILInstruction::ret: case ILInstruction::rmemcmp: case ILInstruction::rmemcmp2: case ILInstruction::store: case ILInstruction::store2: case ILInstruction::yield: case ILInstruction::accept: case ILInstruction::discard: case ILInstruction::swap: if (!op<il_regop_instr, P>::call(inst, it, block, pass)) return err::fail; break; case ILInstruction::negate: case ILInstruction::combinedw: case ILInstruction::highdw: case ILInstruction::lowdw: case ILInstruction::splitdw: case ILInstruction::rtoffset: case ILInstruction::rtoffset2: case ILInstruction::start: case ILInstruction::panic: case ILInstruction::null: if (!op<il_simple_instr, P>::call(inst, it, block, pass)) return err::fail; break; case ILInstruction::size8: case ILInstruction::cut8: case ILInstruction::extract8: case ILInstruction::offset8: if (!op<il_size_instr<std::uint8_t>, P>::call(inst, it, block, pass)) return err::fail; break; case ILInstruction::size16: case ILInstruction::cut16: case ILInstruction::extract16: case ILInstruction::offset16: if (!op<il_size_instr<std::uint16_t>, P>::call(inst, it, block, pass)) return err::fail; break; case ILInstruction::size32: case ILInstruction::cut32: case ILInstruction::extract32: case ILInstruction::offset32: if (!op<il_size_instr<std::uint32_t>, P>::call(inst, it, block, pass)) return err::fail; break; case ILInstruction::aoffset8: if (!op<il_aoffset_instr<std::uint8_t>, P>::call(inst, it, block, pass)) return err::fail; break; case ILInstruction::woffset8: if (!op<il_woffset_instr<std::uint8_t>, P>::call(inst, it, block, pass)) return err::fail; break; case ILInstruction::aoffset16: if (!op<il_aoffset_instr<std::uint16_t>, P>::call(inst, it, block, pass)) return err::fail; break; case ILInstruction::woffset16: if (!op<il_woffset_instr<std::uint16_t>, P>::call(inst, it, block, pass)) return err::fail; break; case ILInstruction::aoffset32: if (!op<il_aoffset_instr<std::uint32_t>, P>::call(inst, it, block, pass)) return err::fail; break; case ILInstruction::woffset32: if (!op<il_woffset_instr<std::uint32_t>, P>::call(inst, it, block, pass)) return err::fail; break; case ILInstruction::i8: if (!op<il_const_i8_instr, P>::call(inst, it, block, pass)) return err::fail; break; case ILInstruction::u8: if (!op<il_const_u8_instr, P>::call(inst, it, block, pass)) return err::fail; break; case ILInstruction::i16: if (!op<il_const_i16_instr<std::int16_t>, P>::call(inst, it, block, pass)) return err::fail; break; case ILInstruction::i16_8: if (!op<il_const_i16_instr<std::int8_t>, P>::call(inst, it, block, pass)) return err::fail; break; case ILInstruction::u16: if (!op<il_const_u16_instr<std::uint16_t>, P>::call(inst, it, block, pass)) return err::fail; break; case ILInstruction::u16_8: if (!op<il_const_u16_instr<std::uint8_t>, P>::call(inst, it, block, pass)) return err::fail; break; case ILInstruction::i32: if (!op<il_const_i32_instr<std::int32_t>, P>::call(inst, it, block, pass)) return err::fail; break; case ILInstruction::i32_16: if (!op<il_const_i32_instr<std::int16_t>, P>::call(inst, it, block, pass)) return err::fail; break; case ILInstruction::i32_8: if (!op<il_const_i32_instr<std::int8_t>, P>::call(inst, it, block, pass)) return err::fail; break; case ILInstruction::u32: if (!op<il_const_u32_instr<std::uint32_t>, P>::call(inst, it, block, pass)) return err::fail; break; case ILInstruction::u32_16: if (!op<il_const_u32_instr<std::uint16_t>, P>::call(inst, it, block, pass)) return err::fail; break; case ILInstruction::u32_8: if (!op<il_const_u32_instr<std::uint8_t>, P>::call(inst, it, block, pass)) return err::fail; break; case ILInstruction::i64: if (!op<il_const_i64_instr<std::int64_t>, P>::call(inst, it, block, pass)) return err::fail; break; case ILInstruction::i64_32: if (!op<il_const_i64_instr<std::int32_t>, P>::call(inst, it, block, pass)) return err::fail; break; case ILInstruction::i64_16: if (!op<il_const_i64_instr<std::int16_t>, P>::call(inst, it, block, pass)) return err::fail; break; case ILInstruction::i64_8: if (!op<il_const_i64_instr<std::int8_t>, P>::call(inst, it, block, pass)) return err::fail; break; case ILInstruction::u64: if (!op<il_const_u64_instr<std::uint64_t>, P>::call(inst, it, block, pass)) return err::fail; break; case ILInstruction::u64_32: if (!op<il_const_u64_instr<std::uint32_t>, P>::call(inst, it, block, pass)) return err::fail; break; case ILInstruction::u64_16: if (!op<il_const_u64_instr<std::uint16_t>, P>::call(inst, it, block, pass)) return err::fail; break; case ILInstruction::u64_8: if (!op<il_const_u64_instr<std::uint8_t>, P>::call(inst, it, block, pass)) return err::fail; break; case ILInstruction::f32: if (!op<il_const_f32_instr, P>::call(inst, it, block, pass)) return err::fail; break; case ILInstruction::f64: if (!op<il_const_f64_instr, P>::call(inst, it, block, pass)) return err::fail; break; case ILInstruction::word: if (!op<il_const_word_instr, P>::call(inst, it, block, pass)) return err::fail; break; case ILInstruction::dword: if (!op<il_const_dword_instr, P>::call(inst, it, block, pass)) return err::fail; break; case ILInstruction::call8: case ILInstruction::jmp8: case ILInstruction::fnptr8: case ILInstruction::fncall8: case ILInstruction::local8: if (!op<il_identifier_instr<std::uint8_t>, P>::call(inst, it, block, pass)) return err::fail; break; case ILInstruction::call16: case ILInstruction::jmp16: case ILInstruction::fnptr16: case ILInstruction::fncall16: case ILInstruction::local16: if (!op<il_identifier_instr<std::uint16_t>, P>::call(inst, it, block, pass)) return err::fail; break; case ILInstruction::call32: case ILInstruction::jmp32: case ILInstruction::fnptr32: case ILInstruction::fncall32: case ILInstruction::vtable: case ILInstruction::constref: case ILInstruction::staticref: case ILInstruction::local32: if (!op<il_identifier_instr<std::uint32_t>, P>::call(inst, it, block, pass)) return err::fail; break; case ILInstruction::jmpz: if (!op<il_jmpz_instr, P>::call(inst, it, block, pass)) return err::fail; break; case ILInstruction::roffset8: if (!op<il_roffset_instr<std::uint8_t>, P>::call(inst, it, block, pass)) return err::fail; break; case ILInstruction::roffset16: if (!op<il_roffset_instr<std::uint16_t>, P>::call(inst, it, block, pass)) return err::fail; break; case ILInstruction::roffset32: if (!op<il_roffset_instr<std::uint32_t>, P>::call(inst, it, block, pass)) return err::fail; break; case ILInstruction::aroffset: if (!op<il_aroffset_instr, P>::call(inst, it, block, pass)) return err::fail; break; case ILInstruction::wroffset: if (!op<il_wroffset_instr, P>::call(inst, it, block, pass)) return err::fail; break; case ILInstruction::table8offset8: if (!op<il_tableoffset_instr<std::uint8_t, std::uint8_t>, P>::call(inst, it, block, pass)) return err::fail; break; case ILInstruction::table16offset8: if (!op<il_tableoffset_instr<std::uint16_t, std::uint8_t>, P>::call(inst, it, block, pass)) return err::fail; break; case ILInstruction::table32offset8: if (!op<il_tableoffset_instr<std::uint32_t, std::uint8_t>, P>::call(inst, it, block, pass)) return err::fail; break; case ILInstruction::table8offset16: if (!op<il_tableoffset_instr<std::uint8_t, std::uint16_t>, P>::call(inst, it, block, pass)) return err::fail; break; case ILInstruction::table16offset16: if (!op<il_tableoffset_instr<std::uint16_t, std::uint16_t>, P>::call(inst, it, block, pass)) return err::fail; break; case ILInstruction::table32offset16: if (!op<il_tableoffset_instr<std::uint32_t, std::uint16_t>, P>::call(inst, it, block, pass)) return err::fail; break; case ILInstruction::table8offset32: if (!op<il_tableoffset_instr<std::uint8_t, std::uint32_t>, P>::call(inst, it, block, pass)) return err::fail; break; case ILInstruction::table16offset32: if (!op<il_tableoffset_instr<std::uint16_t, std::uint32_t>, P>::call(inst, it, block, pass)) return err::fail; break; case ILInstruction::table32offset32: if (!op<il_tableoffset_instr<std::uint32_t, std::uint32_t>, P>::call(inst, it, block, pass)) return err::fail; break; case ILInstruction::debug: if (!op<il_debug_instr, P>::call(inst, it, block, pass)) return err::fail; break; case ILInstruction::slice: if (!op<il_slice_instr, P>::call(inst, it, block, pass)) return err::fail; break; default: break; } } return err::ok; } struct exec_end_op { static bool block_end(il_l_itr it, il_b block) { return false; } static void pre(ILInstruction inst, il_l_itr it, il_b block) { } }; struct print_end_op { static bool block_end(il_l_itr it, il_b block) { auto fun = block->parent; if (block->id >= fun->blocks.size()-1) return false; block = fun->blocks[block->id+1]; it = block->data_pool.begin(); std::cout<<"\nblock "<< block->id <<":\n"; return true; } static void pre(ILInstruction inst, il_l_itr it, il_b block) { if (inst!= ILInstruction::debug) std::cout << "\t"; } }; template<typename T, typename P> struct ILExec { static errvoid call(ILInstruction instr,std::vector<std::uint8_t>::iterator& it, ILBlock*& block, P& pass) { return T::exec(instr,it, block, pass); } }; template<typename T, typename P> struct ILPrint { static errvoid call(ILInstruction instr,std::vector<std::uint8_t>::iterator& it, ILBlock*& block, P& pass) { return T::print(instr, it, block, pass); } }; errvoid ILEvaluator::exec_function(ILBytecodeFunction* fun) { il_no_pass pass; return loop_code<ILExec,il_no_pass,exec_end_op>(fun, pass); } errvoid ILBytecodeFunction::print_function(ILBytecodeFunction* fun) { std::cout<<"function "<<fun->id<<" "<<fun->name<<"\n\n"; std::cout<<"block 0:\n"; il_no_pass pass; return loop_code<ILPrint,il_no_pass,print_end_op>(fun, pass); } }
36.234763
158
0.675523
fencl
a7d481f6cabea71f16c779dff2e5a52a3d6dbc2d
2,351
cpp
C++
tests/failed/main.cpp
igagis/testy
a38281336816bec1651d818fa7aad89ecade17b2
[ "MIT" ]
8
2021-04-16T13:17:20.000Z
2022-01-05T09:14:03.000Z
tests/failed/main.cpp
igagis/testy
a38281336816bec1651d818fa7aad89ecade17b2
[ "MIT" ]
16
2021-04-19T07:59:52.000Z
2022-02-07T11:14:55.000Z
tests/failed/main.cpp
igagis/testy
a38281336816bec1651d818fa7aad89ecade17b2
[ "MIT" ]
3
2021-04-17T02:33:46.000Z
2022-02-21T15:37:55.000Z
#include "../../src/tst/application.hpp" #include "../../src/tst/check.hpp" #include "../harness/testees.hpp" namespace{ class fixture{ public: fixture() = default; fixture(const std::pair<int, int>& p) : a(p.first) {} fixture(const fixture&) = delete; int a = 10; }; } namespace{ struct some_unknown_exception{}; } class application : public tst::application{ public: application() : tst::application("failing tests", "some tests are failing") {} void init()override; }; void application::init(){ this->tst::application::init(); auto& suite = this->get_suite("factorial"); suite.add( "positive_arguments_must_produce_expected_result", [](){ tst::check(factorial(1) == 1, SL); tst::check_eq(factorial(2), 2, SL); tst::check_eq(factorial(3), 6, [](auto& o){o << "hello world!";}, SL); tst::check_ne(factorial(3), 6, [](auto& o){o << "hello world!";}, SL); tst::check_lt(factorial(3), 6, [](auto& o){o << "hello world!";}, SL); tst::check(factorial(8) == 40320, SL); throw std::runtime_error("thrown by test"); } ); suite.add( "test_which_throws_unknown_exception", [](){ throw some_unknown_exception(); } ); suite.add( "test_which_fails_check_eq_with_custom_message", [](){ tst::check_eq(factorial(3), 7, [](auto& o){o << "hello world!";}, SL); } ); suite.add_disabled("disabled_test", [](){tst::check(false, SL);}); suite.add( "factorial_of_value_from_fixture", [](){ fixture f; tst::check_eq(factorial(f.a), 3628801, SL); // will fail } ); suite.add<std::pair<int, int>>( "positive_arguments_must_produce_expected_result", { {1, 1}, {2, 2}, {3, 7}, // will fail {8, 40320} }, [](const auto& i){ tst::check(factorial(i.first) == i.second, SL); } ); suite.add_disabled<std::pair<int, int>>( "disabled_param_test", { {1, 1}, {2, 3}, // will fail {3, 6}, {8, 40320} }, [](const auto& i){tst::check(false, SL);} ); suite.add<std::pair<int, int>>( "factorial_of_value_from_fixture", { {1, 2}, // will fail {2, 2}, {3, 6}, {8, 40320} }, [](const auto& i){ tst::check(factorial(i.first) == i.second, SL) << "expected " << i.second; } ); } tst::application_factory fac([](){ return std::make_unique<::application>(); });
20.094017
78
0.58741
igagis
a7dbf77fd95783f96e05334686015efffabffc10
3,006
cpp
C++
caffe/src/caffe/test/test_solver.cpp
blitzingeagle/DeepEmbeddedClustering
cbc648fc9271f74c3bb257f57f0f78e1a1a66459
[ "MIT" ]
408
2015-11-19T21:50:16.000Z
2022-03-22T08:17:26.000Z
caffe/src/caffe/test/test_solver.cpp
blitzingeagle/DeepEmbeddedClustering
cbc648fc9271f74c3bb257f57f0f78e1a1a66459
[ "MIT" ]
29
2016-05-18T10:24:00.000Z
2021-09-26T21:43:46.000Z
caffe/src/caffe/test/test_solver.cpp
blitzingeagle/DeepEmbeddedClustering
cbc648fc9271f74c3bb257f57f0f78e1a1a66459
[ "MIT" ]
152
2015-11-24T17:30:36.000Z
2021-11-11T07:17:03.000Z
#include <string> #include <utility> #include <vector> #include "google/protobuf/text_format.h" #include "gtest/gtest.h" #include "caffe/common.hpp" #include "caffe/proto/caffe.pb.h" #include "caffe/solver.hpp" #include "caffe/test/test_caffe_main.hpp" using std::ostringstream; namespace caffe { template <typename TypeParam> class SolverTest : public MultiDeviceTest<TypeParam> { typedef typename TypeParam::Dtype Dtype; protected: virtual void InitSolverFromProtoString(const string& proto) { SolverParameter param; CHECK(google::protobuf::TextFormat::ParseFromString(proto, &param)); // Set the solver_mode according to current Caffe::mode. switch (Caffe::mode()) { case Caffe::CPU: param.set_solver_mode(SolverParameter_SolverMode_CPU); break; case Caffe::GPU: param.set_solver_mode(SolverParameter_SolverMode_GPU); break; default: LOG(FATAL) << "Unknown Caffe mode: " << Caffe::mode(); } solver_.reset(new SGDSolver<Dtype>(param)); } shared_ptr<Solver<Dtype> > solver_; }; TYPED_TEST_CASE(SolverTest, TestDtypesAndDevices); TYPED_TEST(SolverTest, TestInitTrainTestNets) { const string& proto = "test_interval: 10 " "test_iter: 10 " "test_state: { stage: 'with-softmax' }" "test_iter: 10 " "test_state: {}" "net_param { " " name: 'TestNetwork' " " layers: { " " name: 'data' " " type: DUMMY_DATA " " dummy_data_param { " " num: 5 " " channels: 3 " " height: 10 " " width: 10 " " num: 5 " " channels: 1 " " height: 1 " " width: 1 " " } " " top: 'data' " " top: 'label' " " } " " layers: { " " name: 'innerprod' " " type: INNER_PRODUCT " " inner_product_param { " " num_output: 10 " " } " " bottom: 'data' " " top: 'innerprod' " " } " " layers: { " " name: 'accuracy' " " type: ACCURACY " " bottom: 'innerprod' " " bottom: 'label' " " top: 'accuracy' " " exclude: { phase: TRAIN } " " } " " layers: { " " name: 'loss' " " type: SOFTMAX_LOSS " " bottom: 'innerprod' " " bottom: 'label' " " include: { phase: TRAIN } " " include: { phase: TEST stage: 'with-softmax' } " " } " "} "; this->InitSolverFromProtoString(proto); ASSERT_TRUE(this->solver_->net() != NULL); EXPECT_TRUE(this->solver_->net()->has_layer("loss")); EXPECT_FALSE(this->solver_->net()->has_layer("accuracy")); ASSERT_EQ(2, this->solver_->test_nets().size()); EXPECT_TRUE(this->solver_->test_nets()[0]->has_layer("loss")); EXPECT_TRUE(this->solver_->test_nets()[0]->has_layer("accuracy")); EXPECT_FALSE(this->solver_->test_nets()[1]->has_layer("loss")); EXPECT_TRUE(this->solver_->test_nets()[1]->has_layer("accuracy")); } } // namespace caffe
27.833333
72
0.576181
blitzingeagle
a7dcf745a43afc34281af88fd981a2f6559de471
48
hpp
C++
src/boost_algorithm_string_iter_find.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
10
2018-03-17T00:58:42.000Z
2021-07-06T02:48:49.000Z
src/boost_algorithm_string_iter_find.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
2
2021-03-26T15:17:35.000Z
2021-05-20T23:55:08.000Z
src/boost_algorithm_string_iter_find.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
4
2019-05-28T21:06:37.000Z
2021-07-06T03:06:52.000Z
#include <boost/algorithm/string/iter_find.hpp>
24
47
0.8125
miathedev
a7dec5eba5baa52eaf6befc87719d1aec27d3ea9
5,026
hpp
C++
include/eve/concept/value.hpp
leha-bot/eve
30e7a7f6bcc5cf524a6c2cc624234148eee847be
[ "MIT" ]
null
null
null
include/eve/concept/value.hpp
leha-bot/eve
30e7a7f6bcc5cf524a6c2cc624234148eee847be
[ "MIT" ]
null
null
null
include/eve/concept/value.hpp
leha-bot/eve
30e7a7f6bcc5cf524a6c2cc624234148eee847be
[ "MIT" ]
null
null
null
//================================================================================================== /* EVE - Expressive Vector Engine Copyright : EVE Contributors & Maintainers SPDX-License-Identifier: MIT */ //================================================================================================== #pragma once #include <eve/forward.hpp> #include <eve/concept/vectorizable.hpp> #include <eve/concept/vectorized.hpp> #include <eve/traits/is_logical.hpp> #include <concepts> #include <type_traits> namespace eve { //================================================================================================ //! @addtogroup concepts //! @{ //! @var value //! The concept `value<T>` is satisfied if and only if T satisfies //! either `eve::scalar_value` or `eve::simd_value`. //! //! #### Examples //! - `eve::logical<eve::wide<char>>` //! - `float` //! - `eve::wide<std::uint64_t>` //! - `eve::wide<int, eve::fixed<1>>` //! @} //================================================================================================ template<typename T> concept value = simd_value<T> || scalar_value<T>; template<typename T> concept integral_value = value<T> && std::integral<detail::value_type_t<T>>; //================================================================================================ //! @addtogroup concepts //! @{ //! @var integral_value //! TODO describe //! //! #### Examples //! - `eve::wide<char>` //! - `int` //! - `eve::wide<int, eve::fixed<1>>` //! @} //================================================================================================ template<typename T> concept signed_value = value<T> && std::is_signed_v<detail::value_type_t<T>>; //================================================================================================ //! @addtogroup concepts //! @{ //! @var signed_value //! TODO describe //! //! #### Examples //! - `eve::wide<char>` //! - `float` //! - `eve::wide<int, eve::fixed<1>>` //! @} //================================================================================================ template<typename T> concept unsigned_value = value<T> && std::unsigned_integral<detail::value_type_t<T>>; //================================================================================================ //! @addtogroup concepts //! @{ //! @var unsigned_value //! TODO describe //! //! #### Examples //! - `unsigned int` //! - `eve::wide<std::uint8_t, eve::fixed<1>>` //! @} //================================================================================================ template<typename T> concept signed_integral_value = value<T> && std::signed_integral<detail::value_type_t<T>>; //================================================================================================ //! @addtogroup concepts //! @{ //! @var signed_integral_value //! TODO describe //! //! #### Examples //! - `short int` //! - `eve::wide<int, eve::fixed<1>>` //! @} template<typename T> concept floating_value = value<T> && std::floating_point<detail::value_type_t<T>>; //================================================================================================ //! @addtogroup concepts //! @{ //! @var floating_value //! TODO describe //! //! #### Examples //! - `double` //! - `eve::wide<float, eve::fixed<2>>` //! @} template<typename T> concept real_value = real_simd_value<T> || real_scalar_value<T>; //================================================================================================ //! @addtogroup concepts //! @{ //! @var real_value //! TODO describe //! //! #### Examples //! - `double` //! - `eve::wide<int, eve::fixed<2>>` //! @} template<typename T> concept floating_real_value = real_value<T> && std::floating_point<detail::value_type_t<T>>; //================================================================================================ //! @addtogroup concepts //! @{ //! @var floating_real_value //! TODO describe //! //! #### Examples //! - `double` //! - `eve::wide<float, eve::fixed<2>>` //! @} template<typename T> concept integral_real_value = real_value<T> && std::integral<detail::value_type_t<T>>; //================================================================================================ //! @addtogroup concepts //! @{ //! @var integral_real_value //! TODO describe //! //! #### Examples //! - `char` //! - `eve::wide<long int, eve::fixed<2>>` //! @} template<typename T> concept logical_value = value<T> && is_logical_v<T>; //================================================================================================ //! @addtogroup concepts //! @{ //! @var logical_value //! TODO describe //! //! #### Examples //! - `eve::logical<eve::wide<char>>` //! - `eve::logical<double>` //! @} }
33.959459
117
0.39037
leha-bot
a7e2c5bd51a09198b501c9aa1463f25b95a82b50
1,531
cpp
C++
Singleton.cpp
kanirudh/design_patterns
79a289299d65b672d8362920898c810e92c840f3
[ "MIT" ]
null
null
null
Singleton.cpp
kanirudh/design_patterns
79a289299d65b672d8362920898c810e92c840f3
[ "MIT" ]
null
null
null
Singleton.cpp
kanirudh/design_patterns
79a289299d65b672d8362920898c810e92c840f3
[ "MIT" ]
null
null
null
/* * So lets say in your pgroam, there is one object * that should preform the function. * * This is many times called an Anti-Pattern. * * Why to do this * 1. It is easy to implement * 2. It is to share the object in the program * * Destruction of dependent Singletons, use the atexit() * * References: * 1. https://sourcemaking.com/design_patterns/singleton * */ #include <iostream> class Singleton { int value{0}; // Constructor is private // People cannot create an object of this class Singleton() { std::cout << __PRETTY_FUNCTION__ << std::endl; } // This is just to present that idea, this destructor is really called. // Private destructor is allowed, becuase the object is created by the class itself. ~Singleton() { std::cout << __PRETTY_FUNCTION__ << std::endl; } public: // Delete Copy Constructor and Assignment // Now we have ensured nobody can create a copy of static object Singleton(Singleton const& other) = delete; Singleton& operator=(Singleton const& other) = delete; static Singleton& instance() { static Singleton inst; return inst; } void print() const { std::cout << value << std::endl; } }; int main() { // Singleton x; // This is not allowed // auto x = new Singleton(); // This is also not allowed std::cout << "Called Main" << std::endl; Singleton::instance().print(); std::cout << "Exitting Main" << std::endl; return 0; }
23.19697
88
0.629001
kanirudh
a7e5076b591151ae983e0fec51ea1bd12d490940
1,142
cpp
C++
examples/advanced/mockAdvanced.cpp
mcci-catena/arduinounit
6c54942ab58653bd0780a4041a016596dae1128e
[ "MIT" ]
null
null
null
examples/advanced/mockAdvanced.cpp
mcci-catena/arduinounit
6c54942ab58653bd0780a4041a016596dae1128e
[ "MIT" ]
null
null
null
examples/advanced/mockAdvanced.cpp
mcci-catena/arduinounit
6c54942ab58653bd0780a4041a016596dae1128e
[ "MIT" ]
1
2022-03-09T09:54:03.000Z
2022-03-09T09:54:03.000Z
#if !defined(ARDUINO) // only used for "en vitro" tests (not on actual board) #include <stdlib.h> #include <sys/time.h> #include <time.h> #include "ArduinoUnit.h" #include "ArduinoUnitMock.h" int random(int n) { static bool setup = false; if (!setup) { srand(time(0)); setup = true; } return rand() % n; } int random(int a, int b) { return a+rand() % (b-a+1); } void setup(); void loop(); CppIOStream Serial; int main(int argc, char *argv[]) { setup(); // parse --exclude/-e <pattern> and --include/-i <pattern> commands for (int i=1; i<argc; ++i) { if (strcmp(argv[i],"--exclude")==0 || strcmp(argv[i],"-e")==0) { ++i; Test::exclude(argv[i]); continue; } if (strcmp(argv[i],"--include")==0 || strcmp(argv[i],"-i")==0) { ++i; Test::include(argv[i]); continue; } if (strcmp(argv[i],"--")==0) { break; } std::cerr << "unknown argument '" << argv[i] << "'" << std::endl; exit(1); } // instead of looping forever, loop while there are active tests while (Test::remaining() > 0) { loop(); } return 0; } #include "advanced.ino" #endif
19.355932
69
0.56042
mcci-catena
a7e5e8019d48e31c4be866729b5938626c6dec35
234
cpp
C++
EscapeRoomZ/item.cpp
ermario/ScapeRoomZ
2ec78b353248347cc5ad70e47daa06bc72c033b0
[ "MIT" ]
null
null
null
EscapeRoomZ/item.cpp
ermario/ScapeRoomZ
2ec78b353248347cc5ad70e47daa06bc72c033b0
[ "MIT" ]
null
null
null
EscapeRoomZ/item.cpp
ermario/ScapeRoomZ
2ec78b353248347cc5ad70e47daa06bc72c033b0
[ "MIT" ]
null
null
null
#include <iostream> #include "item.h" Item::Item(const char* title, const char* description, Entity* prev, ItemType item_type) : Entity(title, description, prev), item_type(item_type) { type = EntityType::ITEM; } Item::~Item() {}
19.5
90
0.709402
ermario
a7e81123f763f6adaed0a1135c901f72bb076e6e
8,516
cpp
C++
source/Lys/GUIModule/GUI_Manager_Loader.cpp
Tigole/Lys-Framework
c7a51261b78c69fbfd823c1d20617ef13ca83a39
[ "MIT" ]
null
null
null
source/Lys/GUIModule/GUI_Manager_Loader.cpp
Tigole/Lys-Framework
c7a51261b78c69fbfd823c1d20617ef13ca83a39
[ "MIT" ]
null
null
null
source/Lys/GUIModule/GUI_Manager_Loader.cpp
Tigole/Lys-Framework
c7a51261b78c69fbfd823c1d20617ef13ca83a39
[ "MIT" ]
null
null
null
#include "Lys/GUIModule/GUI_Manager_Loader.hpp" /* #include "XMLFileLoader.hpp" #include "GUI_Manager.hpp" #include "GUI_Element.hpp" #include "Elements/GUI_Button.hpp" #include "Elements/GUI_Layout.hpp" #include "GUI_Interface.hpp" #include "Environment.hpp" GUI_Manager_Interface_Loader::~GUI_Manager_Interface_Loader() { for (auto& el : m_elements) delete el; } void GUI_Manager_Interface_Loader::mt_Prepare(const std::string& file_name, XMLFileLoader& loader, GUI_Manager* target) { m_target = target; loader.mt_Set_File(file_name); loader.mt_Add_On_Entry_Callback(file_name, "/Interface", &GUI_Manager_Interface_Loader::mt_Load_Interface, this); loader.mt_Add_On_Entry_Callback(file_name, "/Interface/Button", &GUI_Manager_Interface_Loader::mt_Load_Button, this); loader.mt_Add_On_Entry_Callback(file_name, "/Interface/Layout", &GUI_Manager_Interface_Loader::mt_Load_Layout, this); loader.mt_Add_On_Entry_Callback(file_name, "/Interface/Layout/Button", &GUI_Manager_Interface_Loader::mt_Load_Layout_Button, this); loader.mt_Add_On_Exit_Callback(file_name, "/Interface", &GUI_Manager_Interface_Loader::mt_Finalize_Interface, this); loader.mt_Add_On_Exit_Callback(file_name, "/Interface/Layout", &GUI_Manager_Interface_Loader::mt_Finalize_Layout, this); } bool GUI_Manager_Interface_Loader::mt_Load_Button(const XML_Element& button) { bool l_b_ret(false); GUI_Button* l_button; l_button = mt_Load_Button_From_Element(button, m_interface); if (l_button != nullptr) { m_interface->mt_Add_Element(l_button); l_b_ret = true; } return l_b_ret; } bool GUI_Manager_Interface_Loader::mt_Load_Interface(const XML_Element& element) { bool l_b_ret(false); std::string l_id; l_b_ret = element.mt_Get_Attribute("id", l_id); if (l_b_ret == true) { m_interface = new GUI_Interface(l_id, m_target); } if (l_b_ret == true) { l_b_ret = element.mt_Get_Attribute<GameStateType>("game_state", m_game_state, &fn_GameStateType_ToEnum); } return l_b_ret; } bool GUI_Manager_Interface_Loader::mt_Finalize_Interface(const XML_Element& element) { bool l_b_ret(false); if (m_interface != nullptr) { m_target->mt_Add_Interface(m_game_state, m_interface); l_b_ret = true; } return l_b_ret; } bool GUI_Manager_Interface_Loader::mt_Load_Layout(const XML_Element& layout) { bool l_b_ret; sf::FloatRect l_allocation; std::string l_text_id; std::string l_id; sf::Vector2f l_margin; l_b_ret = layout.mt_Get_Attribute("id", l_id); if (l_b_ret == true) { l_b_ret = layout.mt_Get_Attribute("text_id", l_text_id); } if (l_b_ret == true) { l_b_ret = mt_Load_Allocation(layout, l_allocation); } if (l_b_ret == true) { l_b_ret = mt_Load_Margin(layout, l_margin); } if (l_b_ret == true) { m_layout = new GUI_Layout(l_id, m_interface); l_b_ret = (m_layout != nullptr); } if (l_b_ret == true) { m_layout->mt_Set_Margin(l_margin); m_layout->mt_Set_Allocation(l_allocation); m_layout->mt_Set_Text(m_target->mt_Get_Environment()->m_string_manager.mt_Get_String(m_target->mt_Get_Environment()->m_string_manager.mt_Get_Current_Lang(), l_text_id)); } return l_b_ret; } bool GUI_Manager_Interface_Loader::mt_Finalize_Layout(const XML_Element& layout) { bool l_b_ret(true); m_interface->mt_Add_Element(m_layout); return l_b_ret; } bool GUI_Manager_Interface_Loader::mt_Load_Layout_Button(const XML_Element& button) { bool l_b_ret; sf::FloatRect l_allocation; GUI_Button* l_button(nullptr); l_button = mt_Load_Button_From_Element(button, m_layout); if (l_button != nullptr) { m_layout->mt_Add_Element(l_button->mt_Get_Id(), l_button->mt_Get_Screen_Space()); m_interface->mt_Add_Element(l_button); l_b_ret = true; } else { l_b_ret = false; } return l_b_ret; } GUI_Button* GUI_Manager_Interface_Loader::mt_Load_Button_From_Element(const XML_Element& button, GUI_Element* owner) { bool l_b_ret(false); std::string l_id; std::string text_id; std::string l_style_id; GUI_Button* l_button(nullptr); const Style* l_style(nullptr); sf::FloatRect l_allocation; l_b_ret = button.mt_Get_Attribute("id", l_id); if (l_b_ret == true) { l_b_ret = button.mt_Get_Attribute("text_id", text_id); } if (l_b_ret == true) { l_b_ret = button.mt_Get_Attribute("style_id", l_style_id); } if (l_b_ret == true) { l_b_ret = mt_Load_Allocation(button, l_allocation); } if (l_b_ret == true) { l_style = m_target->mt_Get_Style(l_style_id); l_b_ret = (l_style != nullptr); } if (l_b_ret == true) { l_button = new GUI_Button(l_id, owner); l_button->mt_Set_Text(m_target->mt_Get_Environment()->m_string_manager.mt_Get_String(m_target->mt_Get_Environment()->m_string_manager.mt_Get_Current_Lang(), text_id)); l_button->mt_Set_Allocation(l_allocation); for (auto& s : *l_style) { l_button->mt_Set_Style(s.first, s.second); } } return l_button; } bool GUI_Manager_Interface_Loader::mt_Load_Allocation(const XML_Element& element, sf::FloatRect& rect) { bool l_b_ret; l_b_ret = element.mt_Get_Attribute("x_pos", rect.left); if (l_b_ret == true) { l_b_ret = element.mt_Get_Attribute("y_pos", rect.top); } if (l_b_ret == true) { l_b_ret = element.mt_Get_Attribute("x_size", rect.width); } if (l_b_ret == true) { l_b_ret = element.mt_Get_Attribute("y_size", rect.height); } return l_b_ret; } bool GUI_Manager_Interface_Loader::mt_Load_Margin(const XML_Element& element, sf::Vector2f& margin) { bool l_b_ret; l_b_ret = element.mt_Get_Attribute("x_margin", margin.x) && element.mt_Get_Attribute("y_margin", margin.y); return l_b_ret; } GUI_Manager_Style_Loader::~GUI_Manager_Style_Loader() {} void GUI_Manager_Style_Loader::mt_Prepare(const std::string& file_name, XMLFileLoader& loader, GUI_Manager* target) { m_target = target; loader.mt_Set_File(file_name); loader.mt_Add_On_Entry_Callback(file_name, "/Styles/Style", &GUI_Manager_Style_Loader::mt_Load_Style, this); loader.mt_Add_On_Entry_Callback(file_name, "/Styles/Style/State", &GUI_Manager_Style_Loader::mt_Load_State, this); loader.mt_Add_On_Entry_Callback(file_name, "/Styles/Style/State/Text", &GUI_Manager_Style_Loader::mt_Load_Text, this); loader.mt_Add_On_Entry_Callback(file_name, "/Styles/Style/State/Background", &GUI_Manager_Style_Loader::mt_Load_Background, this); loader.mt_Add_On_Exit_Callback(file_name, "/Styles/Style/State", &GUI_Manager_Style_Loader::mt_Finalize_State, this); } bool GUI_Manager_Style_Loader::mt_Load_Style(const XML_Element& style) { bool l_b_ret(false); mt_Reset_Style(); l_b_ret = style.mt_Get_Attribute("id", m_style_id); return l_b_ret; } bool GUI_Manager_Style_Loader::mt_Load_State(const XML_Element& state) { bool l_b_ret(true); state.mt_Get_Attribute<GUI_Element_State>("id", m_state_id, &fn_GUIElementState_ToEnum); return l_b_ret; } bool GUI_Manager_Style_Loader::mt_Load_Text(const XML_Element& text) { bool l_b_ret(true); text.mt_Get_Attribute("font_id", m_style.m_text.m_font_id); text.mt_Get_Attribute("char_size", m_style.m_text.m_size); text.mt_Get_Attribute<GUI_Style_TextHAlign>("h_align", m_style.m_text.m_h_align, &fn_GUIStyleTextHAlign_ToEnum); text.mt_Get_Attribute<GUI_Style_TextVAlign>("v_align", m_style.m_text.m_v_align, &fn_GUIStyleTextVAlign_ToEnum); mt_Load_Color(text, m_style.m_text.m_color); return l_b_ret; } bool GUI_Manager_Style_Loader::mt_Load_Background(const XML_Element& background) { bool l_b_ret(true); mt_Load_Color(background, m_style.m_background.m_background_color); return l_b_ret; } bool GUI_Manager_Style_Loader::mt_Finalize_State(const XML_Element& state) { bool l_b_ret(true); m_target->mt_Add_Style(m_style_id, m_state_id, m_style); return l_b_ret; } void GUI_Manager_Style_Loader::mt_Load_Color(const XML_Element& element, sf::Color& color) { int r, g, b, a; r = color.r; g = color.g; b = color.b; a = color.a; element.mt_Get_Attribute("r", r); element.mt_Get_Attribute("g", g); element.mt_Get_Attribute("b", b); element.mt_Get_Attribute("a", a); color.r = r; color.g = g; color.b = b; color.a = a; } void GUI_Manager_Style_Loader::mt_Reset_Style(void) { m_style.m_text.m_color = sf::Color(255, 250, 205); m_style.m_text.m_h_align = GUI_Style_TextHAlign::Left; m_style.m_text.m_v_align = GUI_Style_TextVAlign::Top; m_style.m_text.m_font_id = ""; m_style.m_text.m_size = 0; m_style.m_background.m_background_color = sf::Color(0, 51, 102); m_style.m_background.m_outline_color = m_style.m_text.m_color; m_style.m_background.m_outline_thickness = 1.0f; } */
24.684058
171
0.764443
Tigole
a7eafcd0ddd64f4cfe98c427867d583888e69abb
18,157
hpp
C++
rocsolver/clients/include/testing_larfb.hpp
LuckyBoyDE/rocSOLVER
6431459ce3f68b5a4c14b28b4ec35c25d664f0bc
[ "BSD-2-Clause" ]
null
null
null
rocsolver/clients/include/testing_larfb.hpp
LuckyBoyDE/rocSOLVER
6431459ce3f68b5a4c14b28b4ec35c25d664f0bc
[ "BSD-2-Clause" ]
null
null
null
rocsolver/clients/include/testing_larfb.hpp
LuckyBoyDE/rocSOLVER
6431459ce3f68b5a4c14b28b4ec35c25d664f0bc
[ "BSD-2-Clause" ]
null
null
null
/* ************************************************************************ * Copyright (c) 2020 Advanced Micro Devices, Inc. * ************************************************************************ */ #include "cblas_interface.h" #include "clientcommon.hpp" #include "norm.hpp" #include "rocsolver.hpp" #include "rocsolver_arguments.hpp" #include "rocsolver_test.hpp" template <typename T> void larfb_checkBadArgs(const rocblas_handle handle, const rocblas_side side, const rocblas_operation trans, const rocblas_direct direct, const rocblas_storev storev, const rocblas_int m, const rocblas_int n, const rocblas_int k, T dV, const rocblas_int ldv, T dT, const rocblas_int ldt, T dA, const rocblas_int lda) { // handle EXPECT_ROCBLAS_STATUS( rocsolver_larfb(nullptr, side, trans, direct, storev, m, n, k, dV, ldv, dT, ldt, dA, lda), rocblas_status_invalid_handle); // values EXPECT_ROCBLAS_STATUS(rocsolver_larfb(handle, rocblas_side(-1), trans, direct, storev, m, n, k, dV, ldv, dT, ldt, dA, lda), rocblas_status_invalid_value); EXPECT_ROCBLAS_STATUS(rocsolver_larfb(handle, side, rocblas_operation(-1), direct, storev, m, n, k, dV, ldv, dT, ldt, dA, lda), rocblas_status_invalid_value); EXPECT_ROCBLAS_STATUS(rocsolver_larfb(handle, side, trans, rocblas_direct(-1), storev, m, n, k, dV, ldv, dT, ldt, dA, lda), rocblas_status_invalid_value); EXPECT_ROCBLAS_STATUS(rocsolver_larfb(handle, side, trans, direct, rocblas_storev(-1), m, n, k, dV, ldv, dT, ldt, dA, lda), rocblas_status_invalid_value); // pointers EXPECT_ROCBLAS_STATUS(rocsolver_larfb(handle, side, trans, direct, storev, m, n, k, (T) nullptr, ldv, dT, ldt, dA, lda), rocblas_status_invalid_pointer); EXPECT_ROCBLAS_STATUS(rocsolver_larfb(handle, side, trans, direct, storev, m, n, k, dV, ldv, (T) nullptr, ldt, dA, lda), rocblas_status_invalid_pointer); EXPECT_ROCBLAS_STATUS(rocsolver_larfb(handle, side, trans, direct, storev, m, n, k, dV, ldv, dT, ldt, (T) nullptr, lda), rocblas_status_invalid_pointer); // quick return with invalid pointers EXPECT_ROCBLAS_STATUS(rocsolver_larfb(handle, rocblas_side_left, trans, direct, storev, 0, n, k, (T) nullptr, ldv, dT, ldt, (T) nullptr, lda), rocblas_status_success); EXPECT_ROCBLAS_STATUS(rocsolver_larfb(handle, rocblas_side_right, trans, direct, storev, m, 0, k, (T) nullptr, ldv, dT, ldt, (T) nullptr, lda), rocblas_status_success); } template <typename T> void testing_larfb_bad_arg() { // safe arguments rocblas_local_handle handle; rocblas_side side = rocblas_side_left; rocblas_operation trans = rocblas_operation_none; rocblas_direct direct = rocblas_forward_direction; rocblas_storev storev = rocblas_column_wise; rocblas_int k = 1; rocblas_int m = 1; rocblas_int n = 1; rocblas_int ldv = 1; rocblas_int ldt = 1; rocblas_int lda = 1; // memory allocation device_strided_batch_vector<T> dV(1, 1, 1, 1); device_strided_batch_vector<T> dA(1, 1, 1, 1); device_strided_batch_vector<T> dT(1, 1, 1, 1); CHECK_HIP_ERROR(dV.memcheck()); CHECK_HIP_ERROR(dT.memcheck()); CHECK_HIP_ERROR(dA.memcheck()); // check bad arguments larfb_checkBadArgs(handle, side, trans, direct, storev, m, n, k, dV.data(), ldv, dT.data(), ldt, dA.data(), lda); } template <bool CPU, bool GPU, typename T, typename Td, typename Th> void larfb_initData(const rocblas_handle handle, const rocblas_side side, const rocblas_operation trans, const rocblas_direct direct, const rocblas_storev storev, const rocblas_int m, const rocblas_int n, const rocblas_int k, Td& dV, const rocblas_int ldv, Td& dT, const rocblas_int ldt, Td& dA, const rocblas_int lda, Th& hV, Th& hT, Th& hA, std::vector<T>& hW, size_t sizeW) { if(CPU) { bool left = (side == rocblas_side_left); bool forward = (direct == rocblas_forward_direction); bool column = (storev == rocblas_column_wise); std::vector<T> htau(k); rocblas_init<T>(hV, true); rocblas_init<T>(hA, true); rocblas_init<T>(hT, true); // scale to avoid singularities // create householder reflectors and triangular factor if(left) { if(column) { for(int i = 0; i < m; ++i) { for(int j = 0; j < k; ++j) { if(i == j) hV[0][i + j * ldv] += 400; else hV[0][i + j * ldv] -= 4; } } if(forward) cblas_geqrf<T>(m, k, hV[0], ldv, htau.data(), hW.data(), sizeW); else cblas_geqlf<T>(m, k, hV[0], ldv, htau.data(), hW.data(), sizeW); } else { for(int i = 0; i < k; ++i) { for(int j = 0; j < m; ++j) { if(i == j) hV[0][i + j * ldv] += 400; else hV[0][i + j * ldv] -= 4; } } if(forward) cblas_gelqf<T>(k, m, hV[0], ldv, htau.data(), hW.data(), sizeW); else cblas_gerqf<T>(k, m, hV[0], ldv, htau.data(), hW.data(), sizeW); } cblas_larft<T>(direct, storev, m, k, hV[0], ldv, htau.data(), hT[0], ldt); } else { if(column) { for(int i = 0; i < n; ++i) { for(int j = 0; j < k; ++j) { if(i == j) hV[0][i + j * ldv] += 400; else hV[0][i + j * ldv] -= 4; } } if(forward) cblas_geqrf<T>(n, k, hV[0], ldv, htau.data(), hW.data(), sizeW); else cblas_geqlf<T>(n, k, hV[0], ldv, htau.data(), hW.data(), sizeW); } else { for(int i = 0; i < k; ++i) { for(int j = 0; j < n; ++j) { if(i == j) hV[0][i + j * ldv] += 400; else hV[0][i + j * ldv] -= 4; } } if(forward) cblas_gelqf<T>(k, n, hV[0], ldv, htau.data(), hW.data(), sizeW); else cblas_gerqf<T>(k, n, hV[0], ldv, htau.data(), hW.data(), sizeW); } cblas_larft<T>(direct, storev, n, k, hV[0], ldv, htau.data(), hT[0], ldt); } } if(GPU) { // copy data from CPU to device CHECK_HIP_ERROR(dV.transfer_from(hV)); CHECK_HIP_ERROR(dT.transfer_from(hT)); CHECK_HIP_ERROR(dA.transfer_from(hA)); } } template <typename T, typename Td, typename Th> void larfb_getError(const rocblas_handle handle, const rocblas_side side, const rocblas_operation trans, const rocblas_direct direct, const rocblas_storev storev, const rocblas_int m, const rocblas_int n, const rocblas_int k, Td& dV, const rocblas_int ldv, Td& dT, const rocblas_int ldt, Td& dA, const rocblas_int lda, Th& hV, Th& hT, Th& hA, Th& hAr, double* max_err) { bool left = (side == rocblas_side_left); rocblas_int ldw = left ? n : m; size_t sizeW = size_t(ldw) * k; std::vector<T> hW(sizeW); // initialize data larfb_initData<true, true, T>(handle, side, trans, direct, storev, m, n, k, dV, ldv, dT, ldt, dA, lda, hV, hT, hA, hW, sizeW); // execute computations // GPU lapack CHECK_ROCBLAS_ERROR(rocsolver_larfb(handle, side, trans, direct, storev, m, n, k, dV.data(), ldv, dT.data(), ldt, dA.data(), lda)); CHECK_HIP_ERROR(hAr.transfer_from(dA)); // CPU lapack cblas_larfb<T>(side, trans, direct, storev, m, n, k, hV[0], ldv, hT[0], ldt, hA[0], lda, hW.data(), ldw); // error is ||hA - hAr|| / ||hA|| // (THIS DOES NOT ACCOUNT FOR NUMERICAL REPRODUCIBILITY ISSUES. // IT MIGHT BE REVISITED IN THE FUTURE) // using frobenius *max_err = norm_error('F', m, n, lda, hA[0], hAr[0]); } template <typename T, typename Td, typename Th> void larfb_getPerfData(const rocblas_handle handle, const rocblas_side side, const rocblas_operation trans, const rocblas_direct direct, const rocblas_storev storev, const rocblas_int m, const rocblas_int n, const rocblas_int k, Td& dV, const rocblas_int ldv, Td& dT, const rocblas_int ldt, Td& dA, const rocblas_int lda, Th& hV, Th& hT, Th& hA, double* gpu_time_used, double* cpu_time_used, const rocblas_int hot_calls, const bool perf) { bool left = (side == rocblas_side_left); rocblas_int ldw = left ? n : m; size_t sizeW = size_t(ldw) * k; std::vector<T> hW(sizeW); if(!perf) { larfb_initData<true, false, T>(handle, side, trans, direct, storev, m, n, k, dV, ldv, dT, ldt, dA, lda, hV, hT, hA, hW, sizeW); // cpu-lapack performance (only if not in perf mode) *cpu_time_used = get_time_us(); cblas_larfb<T>(side, trans, direct, storev, m, n, k, hV[0], ldv, hT[0], ldt, hA[0], lda, hW.data(), ldw); *cpu_time_used = get_time_us() - *cpu_time_used; } larfb_initData<true, false, T>(handle, side, trans, direct, storev, m, n, k, dV, ldv, dT, ldt, dA, lda, hV, hT, hA, hW, sizeW); // cold calls for(int iter = 0; iter < 2; iter++) { larfb_initData<false, true, T>(handle, side, trans, direct, storev, m, n, k, dV, ldv, dT, ldt, dA, lda, hV, hT, hA, hW, sizeW); CHECK_ROCBLAS_ERROR(rocsolver_larfb(handle, side, trans, direct, storev, m, n, k, dV.data(), ldv, dT.data(), ldt, dA.data(), lda)); } // gpu-lapack performance double start; for(int iter = 0; iter < hot_calls; iter++) { larfb_initData<false, true, T>(handle, side, trans, direct, storev, m, n, k, dV, ldv, dT, ldt, dA, lda, hV, hT, hA, hW, sizeW); start = get_time_us(); rocsolver_larfb(handle, side, trans, direct, storev, m, n, k, dV.data(), ldv, dT.data(), ldt, dA.data(), lda); *gpu_time_used += get_time_us() - start; } *gpu_time_used /= hot_calls; } template <typename T> void testing_larfb(Arguments argus) { // get arguments rocblas_local_handle handle; rocblas_int k = argus.K; rocblas_int m = argus.M; rocblas_int n = argus.N; rocblas_int ldv = argus.ldv; rocblas_int lda = argus.lda; rocblas_int ldt = argus.ldt; rocblas_int hot_calls = argus.iters; char sideC = argus.side_option; char transC = argus.transH_option; char directC = argus.direct_option; char storevC = argus.storev; rocblas_side side = char2rocblas_side(sideC); rocblas_operation trans = char2rocblas_operation(transC); rocblas_direct direct = char2rocblas_direct(directC); rocblas_storev storev = char2rocblas_storev(storevC); // check non-supported values if(side != rocblas_side_left && side != rocblas_side_right) { EXPECT_ROCBLAS_STATUS(rocsolver_larfb(handle, side, trans, direct, storev, m, n, k, (T*)nullptr, ldv, (T*)nullptr, ldt, (T*)nullptr, lda), rocblas_status_invalid_value); if(argus.timing) ROCSOLVER_BENCH_INFORM(2); return; } // determine sizes bool row = (storev == rocblas_row_wise); bool left = (side == rocblas_side_left); size_t size_V = size_t(ldv) * k; if(row) size_V = left ? size_t(ldv) * m : size_t(ldv) * n; size_t size_T = size_t(ldt) * k; size_t size_A = size_t(lda) * n; double max_error = 0, gpu_time_used = 0, cpu_time_used = 0; size_t size_Ar = (argus.unit_check || argus.norm_check) ? size_A : 0; // check invalid sizes bool invalid_size = (m < 0 || n < 0 || k < 1 || ldt < k || lda < m || (row && ldv < k) || (!row && !left && ldv < n) || (!row && left && ldv < m)); if(invalid_size) { EXPECT_ROCBLAS_STATUS(rocsolver_larfb(handle, side, trans, direct, storev, m, n, k, (T*)nullptr, ldv, (T*)nullptr, ldt, (T*)nullptr, lda), rocblas_status_invalid_size); if(argus.timing) ROCSOLVER_BENCH_INFORM(1); return; } // memory allocations host_strided_batch_vector<T> hT(size_T, 1, size_T, 1); host_strided_batch_vector<T> hA(size_A, 1, size_A, 1); host_strided_batch_vector<T> hAr(size_Ar, 1, size_Ar, 1); host_strided_batch_vector<T> hV(size_V, 1, size_V, 1); device_strided_batch_vector<T> dT(size_T, 1, size_T, 1); device_strided_batch_vector<T> dA(size_A, 1, size_A, 1); device_strided_batch_vector<T> dV(size_V, 1, size_V, 1); if(size_V) CHECK_HIP_ERROR(dV.memcheck()); if(size_T) CHECK_HIP_ERROR(dT.memcheck()); if(size_A) CHECK_HIP_ERROR(dA.memcheck()); // check quick return if(n == 0 || m == 0) { EXPECT_ROCBLAS_STATUS(rocsolver_larfb(handle, side, trans, direct, storev, m, n, k, dV.data(), ldv, dT.data(), ldt, dA.data(), lda), rocblas_status_success); if(argus.timing) ROCSOLVER_BENCH_INFORM(0); return; } // check computations if(argus.unit_check || argus.norm_check) larfb_getError<T>(handle, side, trans, direct, storev, m, n, k, dV, ldv, dT, ldt, dA, lda, hV, hT, hA, hAr, &max_error); // collect performance data if(argus.timing) larfb_getPerfData<T>(handle, side, trans, direct, storev, m, n, k, dV, ldv, dT, ldt, dA, lda, hV, hT, hA, &gpu_time_used, &cpu_time_used, hot_calls, argus.perf); // validate results for rocsolver-test // using s * machine_precision as tolerance rocblas_int s = left ? m : n; if(argus.unit_check) rocsolver_test_check<T>(max_error, s); // output results for rocsolver-bench if(argus.timing) { if(!argus.perf) { rocblas_cout << "\n============================================\n"; rocblas_cout << "Arguments:\n"; rocblas_cout << "============================================\n"; rocsolver_bench_output("side", "trans", "direct", "storev", "m", "n", "k", "ldv", "ldt", "lda"); rocsolver_bench_output(sideC, transC, directC, storevC, m, n, k, ldv, ldt, lda); rocblas_cout << "\n============================================\n"; rocblas_cout << "Results:\n"; rocblas_cout << "============================================\n"; if(argus.norm_check) { rocsolver_bench_output("cpu_time", "gpu_time", "error"); rocsolver_bench_output(cpu_time_used, gpu_time_used, max_error); } else { rocsolver_bench_output("cpu_time", "gpu_time"); rocsolver_bench_output(cpu_time_used, gpu_time_used); } rocblas_cout << std::endl; } else { if(argus.norm_check) rocsolver_bench_output(gpu_time_used, max_error); else rocsolver_bench_output(gpu_time_used); } } }
37.748441
101
0.482514
LuckyBoyDE
a7f1f9671cf16c0899d22de32fe6b728ec5d6c51
4,302
cxx
C++
PipelineCLIBridge/qSlicerPipelineCLIBridgeModule.cxx
Connor-Bowley/SlicerPipelines
2fe92230fc6333951b7d99c272f3f2c34739624d
[ "Apache-2.0" ]
null
null
null
PipelineCLIBridge/qSlicerPipelineCLIBridgeModule.cxx
Connor-Bowley/SlicerPipelines
2fe92230fc6333951b7d99c272f3f2c34739624d
[ "Apache-2.0" ]
9
2021-11-08T20:42:49.000Z
2022-03-11T19:05:00.000Z
PipelineCLIBridge/qSlicerPipelineCLIBridgeModule.cxx
Connor-Bowley/SlicerPipelines
2fe92230fc6333951b7d99c272f3f2c34739624d
[ "Apache-2.0" ]
2
2022-01-21T09:13:40.000Z
2022-02-09T21:16:31.000Z
/*============================================================================== Program: 3D Slicer Portions (c) Copyright Brigham and Women's Hospital (BWH) All Rights Reserved. See COPYRIGHT.txt or http://www.slicer.org/copyright/copyright.txt for details. 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. ==============================================================================*/ // PipelineCLIBridge includes #include "qSlicerPipelineCLIBridgeModule.h" //----------------------------------------------------------------------------- /// \ingroup Slicer_QtModules_ExtensionTemplate class qSlicerPipelineCLIBridgeModulePrivate { public: qSlicerPipelineCLIBridgeModulePrivate(); }; //----------------------------------------------------------------------------- // qSlicerPipelineCLIBridgeModulePrivate methods //----------------------------------------------------------------------------- qSlicerPipelineCLIBridgeModulePrivate::qSlicerPipelineCLIBridgeModulePrivate() { } //----------------------------------------------------------------------------- // qSlicerPipelineCLIBridgeModule methods //----------------------------------------------------------------------------- qSlicerPipelineCLIBridgeModule::qSlicerPipelineCLIBridgeModule(QObject* _parent) : Superclass(_parent) , d_ptr(new qSlicerPipelineCLIBridgeModulePrivate) { } //----------------------------------------------------------------------------- qSlicerPipelineCLIBridgeModule::~qSlicerPipelineCLIBridgeModule() { } //----------------------------------------------------------------------------- QString qSlicerPipelineCLIBridgeModule::helpText() const { return "The files in this directory exist to bridge the gap between the `qSlicerCLIModuleUIHelper`," " written in C++ and the Python code of the pipeline creator." " The bridge parameters are classes derived from QObject that meet the interface expected by" " the pipeline creator for pipeline parameters (two functions: `GetValue() -> SomeValueType`" " and `GetUI() -> QWidget or QLayout`). They are C++ classes wrapped by the Qt Python wrapping" " mechanism in CMake. The bridge factory creates the appropriate bridge parameter type for a CLI parameter."; } //----------------------------------------------------------------------------- QString qSlicerPipelineCLIBridgeModule::acknowledgementText() const { return "This module was originally developed by Connor Bowley (Kitware, Inc.) for SlicerSALT."; } //----------------------------------------------------------------------------- QStringList qSlicerPipelineCLIBridgeModule::contributors() const { QStringList moduleContributors; moduleContributors << QString("Connor Bowley (Kitware, Inc.)"); return moduleContributors; } //----------------------------------------------------------------------------- QIcon qSlicerPipelineCLIBridgeModule::icon() const { return QIcon(":/Icons/PipelineCLIBridge.png"); } //----------------------------------------------------------------------------- QStringList qSlicerPipelineCLIBridgeModule::categories() const { return QStringList() << "Pipelines.Advanced"; } //----------------------------------------------------------------------------- QStringList qSlicerPipelineCLIBridgeModule::dependencies() const { return QStringList(); } //----------------------------------------------------------------------------- void qSlicerPipelineCLIBridgeModule::setup() { this->Superclass::setup(); } //----------------------------------------------------------------------------- qSlicerAbstractModuleRepresentation* qSlicerPipelineCLIBridgeModule ::createWidgetRepresentation() { return nullptr; } //----------------------------------------------------------------------------- vtkMRMLAbstractLogic* qSlicerPipelineCLIBridgeModule::createLogic() { return nullptr; } //----------------------------------------------------------------------------- bool qSlicerPipelineCLIBridgeModule::isHidden() const { return true; }
36.151261
118
0.522315
Connor-Bowley
a7fc3545226d6ccd62720062406be187cfdd28ff
31,824
cpp
C++
iceoryx_posh/test/moduletests/test_roudi_portmanager_client_server.cpp
andre-nguyen/iceoryx
1efa29a0fa5816bf3529b873b6618cade013c623
[ "Apache-2.0" ]
null
null
null
iceoryx_posh/test/moduletests/test_roudi_portmanager_client_server.cpp
andre-nguyen/iceoryx
1efa29a0fa5816bf3529b873b6618cade013c623
[ "Apache-2.0" ]
null
null
null
iceoryx_posh/test/moduletests/test_roudi_portmanager_client_server.cpp
andre-nguyen/iceoryx
1efa29a0fa5816bf3529b873b6618cade013c623
[ "Apache-2.0" ]
null
null
null
// Copyright (c) 2022 by Apex.AI Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // SPDX-License-Identifier: Apache-2.0 #include "test_roudi_portmanager_fixture.hpp" namespace iox_test_roudi_portmanager { using namespace iox::popo; constexpr uint64_t RESPONSE_QUEUE_CAPACITY{2U}; constexpr uint64_t REQUEST_QUEUE_CAPACITY{2U}; ClientOptions createTestClientOptions() { return ClientOptions{RESPONSE_QUEUE_CAPACITY, iox::NodeName_t("node")}; } ServerOptions createTestServerOptions() { return ServerOptions{REQUEST_QUEUE_CAPACITY, iox::NodeName_t("node")}; } // BEGIN aquireClientPortData tests TEST_F(PortManager_test, AcquireClientPortDataReturnsPort) { ::testing::Test::RecordProperty("TEST_ID", "92225f2c-619a-425b-bba0-6a014822c4c3"); const ServiceDescription sd{"hyp", "no", "toad"}; const RuntimeName_t runtimeName{"hypnotoad"}; auto clientOptions = createTestClientOptions(); clientOptions.connectOnCreate = false; clientOptions.responseQueueFullPolicy = QueueFullPolicy::BLOCK_PRODUCER; clientOptions.serverTooSlowPolicy = ConsumerTooSlowPolicy::WAIT_FOR_CONSUMER; m_portManager->acquireClientPortData(sd, clientOptions, runtimeName, m_payloadDataSegmentMemoryManager, {}) .and_then([&](const auto& clientPortData) { EXPECT_THAT(clientPortData->m_serviceDescription, Eq(sd)); EXPECT_THAT(clientPortData->m_runtimeName, Eq(runtimeName)); EXPECT_THAT(clientPortData->m_nodeName, Eq(clientOptions.nodeName)); EXPECT_THAT(clientPortData->m_toBeDestroyed, Eq(false)); EXPECT_THAT(clientPortData->m_chunkReceiverData.m_queue.capacity(), Eq(clientOptions.responseQueueCapacity)); EXPECT_THAT(clientPortData->m_connectRequested, Eq(clientOptions.connectOnCreate)); EXPECT_THAT(clientPortData->m_chunkReceiverData.m_queueFullPolicy, Eq(clientOptions.responseQueueFullPolicy)); EXPECT_THAT(clientPortData->m_chunkSenderData.m_consumerTooSlowPolicy, Eq(clientOptions.serverTooSlowPolicy)); }) .or_else([&](const auto& error) { GTEST_FAIL() << "Expected ClientPortData but got PortPoolError: " << static_cast<uint8_t>(error); }); } // END aquireClientPortData tests // BEGIN aquireServerPortData tests TEST_F(PortManager_test, AcquireServerPortDataReturnsPort) { ::testing::Test::RecordProperty("TEST_ID", "776c51c4-074a-4404-b6a7-ed08f59f05a0"); const ServiceDescription sd{"hyp", "no", "toad"}; const RuntimeName_t runtimeName{"hypnotoad"}; auto serverOptions = createTestServerOptions(); serverOptions.offerOnCreate = false; serverOptions.requestQueueFullPolicy = QueueFullPolicy::BLOCK_PRODUCER; serverOptions.clientTooSlowPolicy = ConsumerTooSlowPolicy::WAIT_FOR_CONSUMER; m_portManager->acquireServerPortData(sd, serverOptions, runtimeName, m_payloadDataSegmentMemoryManager, {}) .and_then([&](const auto& serverPortData) { EXPECT_THAT(serverPortData->m_serviceDescription, Eq(sd)); EXPECT_THAT(serverPortData->m_runtimeName, Eq(runtimeName)); EXPECT_THAT(serverPortData->m_nodeName, Eq(serverOptions.nodeName)); EXPECT_THAT(serverPortData->m_toBeDestroyed, Eq(false)); EXPECT_THAT(serverPortData->m_chunkReceiverData.m_queue.capacity(), Eq(serverOptions.requestQueueCapacity)); EXPECT_THAT(serverPortData->m_offeringRequested, Eq(serverOptions.offerOnCreate)); EXPECT_THAT(serverPortData->m_chunkReceiverData.m_queueFullPolicy, Eq(serverOptions.requestQueueFullPolicy)); EXPECT_THAT(serverPortData->m_chunkSenderData.m_consumerTooSlowPolicy, Eq(serverOptions.clientTooSlowPolicy)); }) .or_else([&](const auto& error) { GTEST_FAIL() << "Expected ClientPortData but got PortPoolError: " << static_cast<uint8_t>(error); }); } TEST_F(PortManager_test, AcquireServerPortDataWithSameServiceDescriptionTwiceCallsErrorHandlerAndReturnsError) { ::testing::Test::RecordProperty("TEST_ID", "9f2c24ba-192d-4ce8-a61a-fe40b42c655b"); const ServiceDescription sd{"hyp", "no", "toad"}; const RuntimeName_t runtimeName{"hypnotoad"}; auto serverOptions = createTestServerOptions(); // first call must be successful m_portManager->acquireServerPortData(sd, serverOptions, runtimeName, m_payloadDataSegmentMemoryManager, {}) .or_else([&](const auto& error) { GTEST_FAIL() << "Expected ClientPortData but got PortPoolError: " << static_cast<uint8_t>(error); }); iox::cxx::optional<iox::Error> detectedError; auto errorHandlerGuard = iox::ErrorHandlerMock::setTemporaryErrorHandler<iox::Error>([&](const auto error, const auto errorLevel) { EXPECT_THAT(error, Eq(iox::Error::kPOSH__PORT_MANAGER_SERVERPORT_NOT_UNIQUE)); EXPECT_THAT(errorLevel, Eq(iox::ErrorLevel::MODERATE)); detectedError.emplace(error); }); // second call must fail m_portManager->acquireServerPortData(sd, serverOptions, runtimeName, m_payloadDataSegmentMemoryManager, {}) .and_then([&](const auto&) { GTEST_FAIL() << "Expected PortPoolError::UNIQUE_SERVER_PORT_ALREADY_EXISTS but got ServerPortData"; }) .or_else([&](const auto& error) { EXPECT_THAT(error, Eq(PortPoolError::UNIQUE_SERVER_PORT_ALREADY_EXISTS)); }); EXPECT_TRUE(detectedError.has_value()); } TEST_F(PortManager_test, AcquireServerPortDataWithSameServiceDescriptionTwiceAndFirstPortMarkedToBeDestroyedReturnsPort) { ::testing::Test::RecordProperty("TEST_ID", "d7f2815d-f1ea-403d-9355-69470d92a10f"); const ServiceDescription sd{"hyp", "no", "toad"}; const RuntimeName_t runtimeName{"hypnotoad"}; auto serverOptions = createTestServerOptions(); // first call must be successful auto serverPortDataResult = m_portManager->acquireServerPortData(sd, serverOptions, runtimeName, m_payloadDataSegmentMemoryManager, {}); ASSERT_FALSE(serverPortDataResult.has_error()); serverPortDataResult.value()->m_toBeDestroyed = true; iox::cxx::optional<iox::Error> detectedError; auto errorHandlerGuard = iox::ErrorHandlerMock::setTemporaryErrorHandler<iox::Error>( [&](const auto error, const auto) { detectedError.emplace(error); }); // second call must now also succeed m_portManager->acquireServerPortData(sd, serverOptions, runtimeName, m_payloadDataSegmentMemoryManager, {}) .or_else([&](const auto& error) { GTEST_FAIL() << "Expected ClientPortData but got PortPoolError: " << static_cast<uint8_t>(error); }); detectedError.and_then([&](const auto& error) { GTEST_FAIL() << "Expected error handler to not be called but got: " << static_cast<std::underlying_type<iox::Error>::type>(error); }); } // END aquireServerPortData tests // BEGIN discovery tests TEST_F(PortManager_test, CreateClientWithConnectOnCreateAndNoServerResultsInWaitForOffer) { ::testing::Test::RecordProperty("TEST_ID", "14070d7b-d8e1-4df5-84fc-119e5e126cde"); auto clientOptions = createTestClientOptions(); clientOptions.connectOnCreate = true; auto clientPortUser = createClient(clientOptions); EXPECT_THAT(clientPortUser.getConnectionState(), Eq(ConnectionState::WAIT_FOR_OFFER)); } TEST_F(PortManager_test, DoDiscoveryWithClientConnectOnCreateAndNoServerResultsInClientNotConnected) { ::testing::Test::RecordProperty("TEST_ID", "6829e506-9f58-4253-bc42-469f2970a2c7"); auto clientOptions = createTestClientOptions(); clientOptions.connectOnCreate = true; auto clientPortUser = createClient(clientOptions); m_portManager->doDiscovery(); EXPECT_THAT(clientPortUser.getConnectionState(), Eq(ConnectionState::WAIT_FOR_OFFER)); } TEST_F(PortManager_test, CreateClientWithConnectOnCreateAndNotOfferingServerResultsInWaitForOffer) { ::testing::Test::RecordProperty("TEST_ID", "0f7098d0-2646-4c10-b347-9b57b0f593ce"); auto clientOptions = createTestClientOptions(); clientOptions.connectOnCreate = true; auto serverOptions = createTestServerOptions(); serverOptions.offerOnCreate = false; auto serverPortUser = createServer(serverOptions); auto clientPortUser = createClient(clientOptions); EXPECT_THAT(clientPortUser.getConnectionState(), Eq(ConnectionState::WAIT_FOR_OFFER)); } TEST_F(PortManager_test, CreateClientWithConnectOnCreateAndOfferingServerResultsInClientConnected) { ::testing::Test::RecordProperty("TEST_ID", "108170d4-786b-4266-ad2a-ef922188f70b"); auto clientOptions = createTestClientOptions(); clientOptions.connectOnCreate = true; auto serverOptions = createTestServerOptions(); serverOptions.offerOnCreate = true; auto serverPortUser = createServer(serverOptions); auto clientPortUser = createClient(clientOptions); EXPECT_THAT(clientPortUser.getConnectionState(), Eq(ConnectionState::CONNECTED)); } TEST_F(PortManager_test, CreateServerWithOfferOnCreateAndClientWaitingToConnectResultsInClientConnected) { ::testing::Test::RecordProperty("TEST_ID", "b5bb10b2-bf9b-400e-ab5c-aa3a1e0e826f"); auto clientOptions = createTestClientOptions(); clientOptions.connectOnCreate = true; auto serverOptions = createTestServerOptions(); serverOptions.offerOnCreate = true; auto clientPortUser = createClient(clientOptions); auto serverPortUser = createServer(serverOptions); EXPECT_THAT(clientPortUser.getConnectionState(), Eq(ConnectionState::CONNECTED)); } TEST_F(PortManager_test, CreateClientWithNotConnectOnCreateAndNoServerResultsInClientNotConnected) { ::testing::Test::RecordProperty("TEST_ID", "fde662f1-f9e1-4302-be41-59a7a0bfa4e7"); auto clientOptions = createTestClientOptions(); clientOptions.connectOnCreate = false; auto clientPortUser = createClient(clientOptions); EXPECT_THAT(clientPortUser.getConnectionState(), Eq(ConnectionState::NOT_CONNECTED)); } TEST_F(PortManager_test, DoDiscoveryWithClientNotConnectOnCreateAndNoServerResultsInClientNotConnected) { ::testing::Test::RecordProperty("TEST_ID", "c59b7343-6277-4a4b-8204-506048726be4"); auto clientOptions = createTestClientOptions(); clientOptions.connectOnCreate = false; auto clientPortUser = createClient(clientOptions); m_portManager->doDiscovery(); EXPECT_THAT(clientPortUser.getConnectionState(), Eq(ConnectionState::NOT_CONNECTED)); } TEST_F(PortManager_test, CreateClientWithNotConnectOnCreateAndOfferingServerResultsInClientNotConnected) { ::testing::Test::RecordProperty("TEST_ID", "17cf22ba-066a-418a-8366-1c6b75177b9a"); auto clientOptions = createTestClientOptions(); clientOptions.connectOnCreate = false; auto serverOptions = createTestServerOptions(); serverOptions.offerOnCreate = true; auto serverPortUser = createServer(serverOptions); auto clientPortUser = createClient(clientOptions); EXPECT_THAT(clientPortUser.getConnectionState(), Eq(ConnectionState::NOT_CONNECTED)); } TEST_F(PortManager_test, DoDiscoveryWithClientNotConnectOnCreateAndServerResultsInConnectedWhenCallingConnect) { ::testing::Test::RecordProperty("TEST_ID", "87bbb991-4aaf-49c1-b238-d9b0bb18d699"); auto clientOptions = createTestClientOptions(); clientOptions.connectOnCreate = false; auto serverOptions = createTestServerOptions(); serverOptions.offerOnCreate = true; auto serverPortUser = createServer(serverOptions); auto clientPortUser = createClient(clientOptions); clientPortUser.connect(); m_portManager->doDiscovery(); EXPECT_THAT(clientPortUser.getConnectionState(), Eq(ConnectionState::CONNECTED)); } TEST_F(PortManager_test, DoDiscoveryWithClientConnectResultsInClientNotConnectedWhenCallingDisconnect) { ::testing::Test::RecordProperty("TEST_ID", "b6826f93-096d-473d-b846-ab824efff1ee"); auto clientOptions = createTestClientOptions(); clientOptions.connectOnCreate = true; auto serverOptions = createTestServerOptions(); serverOptions.offerOnCreate = true; auto serverPortUser = createServer(serverOptions); auto clientPortUser = createClient(clientOptions); clientPortUser.disconnect(); m_portManager->doDiscovery(); EXPECT_THAT(clientPortUser.getConnectionState(), Eq(ConnectionState::NOT_CONNECTED)); } TEST_F(PortManager_test, DoDiscoveryWithClientConnectResultsInWaitForOfferWhenCallingStopOffer) { ::testing::Test::RecordProperty("TEST_ID", "45c9cc27-4198-4539-943f-2111ae2d1368"); auto clientOptions = createTestClientOptions(); clientOptions.connectOnCreate = true; auto serverOptions = createTestServerOptions(); serverOptions.offerOnCreate = true; auto serverPortUser = createServer(serverOptions); auto clientPortUser = createClient(clientOptions); serverPortUser.stopOffer(); m_portManager->doDiscovery(); EXPECT_THAT(clientPortUser.getConnectionState(), Eq(ConnectionState::WAIT_FOR_OFFER)); } TEST_F(PortManager_test, DoDiscoveryWithClientConnectResultsInWaitForOfferWhenServerIsDestroyed) { ::testing::Test::RecordProperty("TEST_ID", "585ad47d-1a03-4599-a4dc-57ea1fb6eac7"); auto clientOptions = createTestClientOptions(); clientOptions.connectOnCreate = true; auto serverOptions = createTestServerOptions(); serverOptions.offerOnCreate = true; auto serverPortUser = createServer(serverOptions); auto clientPortUser = createClient(clientOptions); serverPortUser.destroy(); m_portManager->doDiscovery(); EXPECT_THAT(clientPortUser.getConnectionState(), Eq(ConnectionState::WAIT_FOR_OFFER)); } TEST_F(PortManager_test, DoDiscoveryWithClientConnectResultsInNoClientsWhenClientIsDestroyed) { ::testing::Test::RecordProperty("TEST_ID", "3be2f7b5-7e22-4676-a25b-c8a93a4aaa7d"); auto clientOptions = createTestClientOptions(); clientOptions.connectOnCreate = true; auto serverOptions = createTestServerOptions(); serverOptions.offerOnCreate = true; auto serverPortUser = createServer(serverOptions); auto clientPortUser = createClient(clientOptions); EXPECT_TRUE(serverPortUser.hasClients()); clientPortUser.destroy(); m_portManager->doDiscovery(); EXPECT_FALSE(serverPortUser.hasClients()); } TEST_F(PortManager_test, CreateMultipleClientsWithConnectOnCreateAndOfferingServerResultsInAllClientsConnected) { ::testing::Test::RecordProperty("TEST_ID", "08f9981f-2585-4574-b0fc-c16cf0eef7d4"); auto clientOptions = createTestClientOptions(); clientOptions.connectOnCreate = true; auto serverOptions = createTestServerOptions(); serverOptions.offerOnCreate = true; auto serverPortUser = createServer(serverOptions); auto clientPortUser1 = createClient(clientOptions); auto clientPortUser2 = createClient(clientOptions); EXPECT_THAT(clientPortUser1.getConnectionState(), Eq(ConnectionState::CONNECTED)); EXPECT_THAT(clientPortUser2.getConnectionState(), Eq(ConnectionState::CONNECTED)); } TEST_F(PortManager_test, DoDiscoveryWithMultipleClientsNotConnectedAndOfferingServerResultsSomeClientsConnectedWhenSomeClientsCallConnect) { ::testing::Test::RecordProperty("TEST_ID", "7d210259-7c50-479e-b108-bf9747ceb0ef"); auto clientOptions = createTestClientOptions(); clientOptions.connectOnCreate = false; auto serverOptions = createTestServerOptions(); serverOptions.offerOnCreate = true; auto serverPortUser = createServer(serverOptions); auto clientPortUser1 = createClient(clientOptions); auto clientPortUser2 = createClient(clientOptions); clientPortUser2.connect(); m_portManager->doDiscovery(); EXPECT_THAT(clientPortUser1.getConnectionState(), Eq(ConnectionState::NOT_CONNECTED)); EXPECT_THAT(clientPortUser2.getConnectionState(), Eq(ConnectionState::CONNECTED)); } // END discovery tests // BEGIN forwarding to InterfacePort tests TEST_F(PortManager_test, ServerStateIsForwardedToInterfacePortWhenOffer) { ::testing::Test::RecordProperty("TEST_ID", "e51d6f8b-55dd-43b6-977a-da08cfed7be1"); auto interfacePort = m_portManager->acquireInterfacePortData(iox::capro::Interfaces::DDS, "penguin"); auto serverOptions = createTestServerOptions(); m_portManager->doDiscovery(); serverOptions.offerOnCreate = true; auto serverPortUser = createServer(serverOptions); m_portManager->doDiscovery(); interfacePort->m_caproMessageFiFo.pop() .and_then([&](const auto& caproMessage) { EXPECT_THAT(caproMessage.m_type, Eq(CaproMessageType::OFFER)); EXPECT_THAT(caproMessage.m_serviceType, Eq(CaproServiceType::SERVER)); }) .or_else([&]() { GTEST_FAIL() << "Expected OFFER message but got none"; }); EXPECT_FALSE(interfacePort->m_caproMessageFiFo.pop().has_value()); } TEST_F(PortManager_test, ServerStateIsForwardedToInterfacePortWhenStopOffer) { ::testing::Test::RecordProperty("TEST_ID", "70692935-82da-4694-a2b0-8307ab2c167c"); auto interfacePort = m_portManager->acquireInterfacePortData(iox::capro::Interfaces::DDS, "penguin"); auto serverOptions = createTestServerOptions(); serverOptions.offerOnCreate = true; auto serverPortUser = createServer(serverOptions); m_portManager->doDiscovery(); // empty fifo while (interfacePort->m_caproMessageFiFo.pop().has_value()) { } serverPortUser.stopOffer(); m_portManager->doDiscovery(); interfacePort->m_caproMessageFiFo.pop() .and_then([&](const auto& caproMessage) { EXPECT_THAT(caproMessage.m_type, Eq(CaproMessageType::STOP_OFFER)); EXPECT_THAT(caproMessage.m_serviceType, Eq(CaproServiceType::SERVER)); }) .or_else([&]() { GTEST_FAIL() << "Expected STOP_OFFER message but got none"; }); EXPECT_FALSE(interfacePort->m_caproMessageFiFo.pop().has_value()); } TEST_F(PortManager_test, ServerStateIsForwardedToInterfacePortWhenDestroyed) { ::testing::Test::RecordProperty("TEST_ID", "3e9660f8-046c-4e3a-acfd-bad33a6f999c"); auto interfacePort = m_portManager->acquireInterfacePortData(iox::capro::Interfaces::DDS, "penguin"); auto serverOptions = createTestServerOptions(); serverOptions.offerOnCreate = true; auto serverPortUser = createServer(serverOptions); m_portManager->doDiscovery(); // empty fifo while (interfacePort->m_caproMessageFiFo.pop().has_value()) { } serverPortUser.destroy(); m_portManager->doDiscovery(); interfacePort->m_caproMessageFiFo.pop() .and_then([&](const auto& caproMessage) { EXPECT_THAT(caproMessage.m_type, Eq(CaproMessageType::STOP_OFFER)); EXPECT_THAT(caproMessage.m_serviceType, Eq(CaproServiceType::SERVER)); }) .or_else([&]() { GTEST_FAIL() << "Expected STOP_OFFER message but got none"; }); EXPECT_FALSE(interfacePort->m_caproMessageFiFo.pop().has_value()); } TEST_F(PortManager_test, ServerStateIsForwardedToInterfacePortWhenAlreadyOfferAndInterfacePortIsNewlyCreated) { ::testing::Test::RecordProperty("TEST_ID", "31563bb9-561c-43ee-8e3e-b6676cfc9547"); auto serverOptions = createTestServerOptions(); serverOptions.offerOnCreate = true; auto serverPortUser = createServer(serverOptions); m_portManager->doDiscovery(); auto interfacePort = m_portManager->acquireInterfacePortData(iox::capro::Interfaces::DDS, "penguin"); m_portManager->doDiscovery(); interfacePort->m_caproMessageFiFo.pop() .and_then([&](const auto& caproMessage) { EXPECT_THAT(caproMessage.m_type, Eq(CaproMessageType::OFFER)); EXPECT_THAT(caproMessage.m_serviceType, Eq(CaproServiceType::SERVER)); }) .or_else([&]() { GTEST_FAIL() << "Expected OFFER message but got none"; }); EXPECT_FALSE(interfacePort->m_caproMessageFiFo.pop().has_value()); } // END forwarding to InterfacePort tests // BEGIN service registry tests TEST_F(PortManager_test, CreateServerWithNotOfferOnCreateDoesNotAddServerToServiceRegistry) { ::testing::Test::RecordProperty("TEST_ID", "df05ce4d-a1f2-46f2-8224-34b0dbc237ad"); auto serverOptions = createTestServerOptions(); serverOptions.offerOnCreate = false; auto serverPortUser = createServer(serverOptions); m_portManager->doDiscovery(); uint64_t serverCount{0U}; m_portManager->serviceRegistry().find(nullopt, nullopt, nullopt, [&](const auto& entry) { EXPECT_THAT(entry.serverCount, Eq(1U)); serverCount += entry.serverCount; }); EXPECT_THAT(serverCount, Eq(0U)); } TEST_F(PortManager_test, CreateServerWithOfferOnCreateAddsServerToServiceRegistry) { ::testing::Test::RecordProperty("TEST_ID", "8ac876e9-f460-4d1c-97c9-995f3a603317"); auto serverOptions = createTestServerOptions(); serverOptions.offerOnCreate = true; auto serverPortUser = createServer(serverOptions); m_portManager->doDiscovery(); uint64_t serverCount{0U}; m_portManager->serviceRegistry().find(nullopt, nullopt, nullopt, [&](const auto& entry) { EXPECT_THAT(entry.serverCount, Eq(1U)); serverCount += entry.serverCount; }); EXPECT_THAT(serverCount, Eq(1U)); } TEST_F(PortManager_test, StopOfferRemovesServerFromServiceRegistry) { ::testing::Test::RecordProperty("TEST_ID", "5cb255ec-446c-4c68-99b4-c99d0f8abdc5"); auto serverOptions = createTestServerOptions(); serverOptions.offerOnCreate = true; auto serverPortUser = createServer(serverOptions); m_portManager->doDiscovery(); serverPortUser.stopOffer(); m_portManager->doDiscovery(); uint64_t serverCount{0U}; m_portManager->serviceRegistry().find(nullopt, nullopt, nullopt, [&](const auto& entry) { EXPECT_THAT(entry.serverCount, Eq(1U)); serverCount += entry.serverCount; }); EXPECT_THAT(serverCount, Eq(0U)); } TEST_F(PortManager_test, OfferAddsServerToServiceRegistry) { ::testing::Test::RecordProperty("TEST_ID", "60beb1df-a806-4b3a-9e2f-6f6bf352ea1b"); auto serverOptions = createTestServerOptions(); serverOptions.offerOnCreate = false; auto serverPortUser = createServer(serverOptions); m_portManager->doDiscovery(); serverPortUser.offer(); m_portManager->doDiscovery(); uint64_t serverCount{0U}; m_portManager->serviceRegistry().find(nullopt, nullopt, nullopt, [&](const auto& entry) { EXPECT_THAT(entry.serverCount, Eq(1U)); serverCount += entry.serverCount; }); EXPECT_THAT(serverCount, Eq(1U)); } // END service registry tests // BEGIN policy based connection tests // NOTE: there is a client/server sandwich to test both code paths where the client and // the server initiates the state machine ping pong TEST_F(PortManager_test, ClientWithDiscardOldestDataAndServerWithDiscardOldestDataAreConnected) { ::testing::Test::RecordProperty("TEST_ID", "56871f9d-d7c1-4c3c-b86c-9a1e1dc9fd74"); auto clientOptions = createTestClientOptions(); clientOptions.responseQueueFullPolicy = QueueFullPolicy::DISCARD_OLDEST_DATA; auto serverOptions = createTestServerOptions(); serverOptions.clientTooSlowPolicy = ConsumerTooSlowPolicy::DISCARD_OLDEST_DATA; auto clientBeforeServerOffer = createClient(clientOptions); auto serverPortUser = createServer(serverOptions); auto clientAfterServerOffer = createClient(clientOptions); EXPECT_THAT(clientBeforeServerOffer.getConnectionState(), Eq(ConnectionState::CONNECTED)); EXPECT_THAT(clientAfterServerOffer.getConnectionState(), Eq(ConnectionState::CONNECTED)); } TEST_F(PortManager_test, ClientWithDiscardOldestDataAndServerWithWaitForConsumerAreConnected) { ::testing::Test::RecordProperty("TEST_ID", "4767b263-1ca4-4e54-b489-5e486f40f4db"); auto clientOptions = createTestClientOptions(); clientOptions.responseQueueFullPolicy = QueueFullPolicy::DISCARD_OLDEST_DATA; auto serverOptions = createTestServerOptions(); serverOptions.clientTooSlowPolicy = ConsumerTooSlowPolicy::WAIT_FOR_CONSUMER; auto clientBeforeServerOffer = createClient(clientOptions); auto serverPortUser = createServer(serverOptions); auto clientAfterServerOffer = createClient(clientOptions); EXPECT_THAT(clientBeforeServerOffer.getConnectionState(), Eq(ConnectionState::CONNECTED)); EXPECT_THAT(clientAfterServerOffer.getConnectionState(), Eq(ConnectionState::CONNECTED)); } TEST_F(PortManager_test, ClientWithBlockProducerAndServerWithWaitForConsumerAreConnected) { ::testing::Test::RecordProperty("TEST_ID", "c118ce87-25bf-4f53-b157-7414b9f10193"); auto clientOptions = createTestClientOptions(); clientOptions.responseQueueFullPolicy = QueueFullPolicy::BLOCK_PRODUCER; auto serverOptions = createTestServerOptions(); serverOptions.clientTooSlowPolicy = ConsumerTooSlowPolicy::WAIT_FOR_CONSUMER; auto clientBeforeServerOffer = createClient(clientOptions); auto serverPortUser = createServer(serverOptions); auto clientAfterServerOffer = createClient(clientOptions); EXPECT_THAT(clientBeforeServerOffer.getConnectionState(), Eq(ConnectionState::CONNECTED)); EXPECT_THAT(clientAfterServerOffer.getConnectionState(), Eq(ConnectionState::CONNECTED)); } TEST_F(PortManager_test, ClientWithBlockProducerAndServerWithDiscardOldestDataAreNotConnected) { ::testing::Test::RecordProperty("TEST_ID", "f5c6213a-b875-42bd-b55b-17bc04179e6d"); auto clientOptions = createTestClientOptions(); clientOptions.responseQueueFullPolicy = QueueFullPolicy::BLOCK_PRODUCER; auto serverOptions = createTestServerOptions(); serverOptions.clientTooSlowPolicy = ConsumerTooSlowPolicy::DISCARD_OLDEST_DATA; auto clientBeforeServerOffer = createClient(clientOptions); auto serverPortUser = createServer(serverOptions); auto clientAfterServerOffer = createClient(clientOptions); EXPECT_THAT(clientBeforeServerOffer.getConnectionState(), Ne(ConnectionState::CONNECTED)); EXPECT_THAT(clientAfterServerOffer.getConnectionState(), Ne(ConnectionState::CONNECTED)); } TEST_F(PortManager_test, ServerWithDiscardOldestDataAndClientWithDiscardOldestDataAreConnected) { ::testing::Test::RecordProperty("TEST_ID", "53d4ee50-5799-4405-8505-4b7ac3037310"); auto clientOptions = createTestClientOptions(); clientOptions.serverTooSlowPolicy = ConsumerTooSlowPolicy::DISCARD_OLDEST_DATA; auto serverOptions = createTestServerOptions(); serverOptions.requestQueueFullPolicy = QueueFullPolicy::DISCARD_OLDEST_DATA; auto clientBeforeServerOffer = createClient(clientOptions); auto serverPortUser = createServer(serverOptions); auto clientAfterServerOffer = createClient(clientOptions); EXPECT_THAT(clientBeforeServerOffer.getConnectionState(), Eq(ConnectionState::CONNECTED)); EXPECT_THAT(clientAfterServerOffer.getConnectionState(), Eq(ConnectionState::CONNECTED)); } TEST_F(PortManager_test, ServerWithDiscardOldestDataAndClientWithWaitForConsumerAreConnected) { ::testing::Test::RecordProperty("TEST_ID", "0d7a8819-3e33-478e-a13b-844b83fe92ae"); auto clientOptions = createTestClientOptions(); clientOptions.serverTooSlowPolicy = ConsumerTooSlowPolicy::WAIT_FOR_CONSUMER; auto serverOptions = createTestServerOptions(); serverOptions.requestQueueFullPolicy = QueueFullPolicy::DISCARD_OLDEST_DATA; auto clientBeforeServerOffer = createClient(clientOptions); auto serverPortUser = createServer(serverOptions); auto clientAfterServerOffer = createClient(clientOptions); EXPECT_THAT(clientBeforeServerOffer.getConnectionState(), Eq(ConnectionState::CONNECTED)); EXPECT_THAT(clientAfterServerOffer.getConnectionState(), Eq(ConnectionState::CONNECTED)); } TEST_F(PortManager_test, ServerWithBlockProducerAndClientWithWaitForConsumerAreConnected) { ::testing::Test::RecordProperty("TEST_ID", "8c3b7770-13e6-4003-aa9f-b04a34df67c9"); auto clientOptions = createTestClientOptions(); clientOptions.serverTooSlowPolicy = ConsumerTooSlowPolicy::WAIT_FOR_CONSUMER; auto serverOptions = createTestServerOptions(); serverOptions.requestQueueFullPolicy = QueueFullPolicy::BLOCK_PRODUCER; auto clientBeforeServerOffer = createClient(clientOptions); auto serverPortUser = createServer(serverOptions); auto clientAfterServerOffer = createClient(clientOptions); EXPECT_THAT(clientBeforeServerOffer.getConnectionState(), Eq(ConnectionState::CONNECTED)); EXPECT_THAT(clientAfterServerOffer.getConnectionState(), Eq(ConnectionState::CONNECTED)); } TEST_F(PortManager_test, ServerWithBlockProducerAndClientWithDiscardOldestDataAreNotConnected) { ::testing::Test::RecordProperty("TEST_ID", "1d89fa87-3628-4645-9147-82f4223e878a"); auto clientOptions = createTestClientOptions(); clientOptions.serverTooSlowPolicy = ConsumerTooSlowPolicy::DISCARD_OLDEST_DATA; auto serverOptions = createTestServerOptions(); serverOptions.requestQueueFullPolicy = QueueFullPolicy::BLOCK_PRODUCER; auto clientBeforeServerOffer = createClient(clientOptions); auto serverPortUser = createServer(serverOptions); auto clientAfterServerOffer = createClient(clientOptions); EXPECT_THAT(clientBeforeServerOffer.getConnectionState(), Ne(ConnectionState::CONNECTED)); EXPECT_THAT(clientAfterServerOffer.getConnectionState(), Ne(ConnectionState::CONNECTED)); } // END policy based connection tests // BEGIN communication tests TEST_F(PortManager_test, ConnectedClientCanCommunicateWithServer) { ::testing::Test::RecordProperty("TEST_ID", "6376b58d-a796-4cc4-9c40-0c5a117b53f5"); auto clientOptions = createTestClientOptions(); clientOptions.connectOnCreate = true; auto serverOptions = createTestServerOptions(); serverOptions.offerOnCreate = true; auto serverPortUser = createServer(serverOptions); auto clientPortUser = createClient(clientOptions); using DataType = uint64_t; constexpr int64_t SEQUENCE_ID{42}; auto allocateRequestResult = clientPortUser.allocateRequest(sizeof(DataType), alignof(DataType)); ASSERT_FALSE(allocateRequestResult.has_error()); auto requestHeader = allocateRequestResult.value(); requestHeader->setSequenceId(SEQUENCE_ID); EXPECT_FALSE(clientPortUser.sendRequest(requestHeader).has_error()); auto getRequestResult = serverPortUser.getRequest(); ASSERT_FALSE(getRequestResult.has_error()); auto receivedRequestHeader = getRequestResult.value(); EXPECT_THAT(receivedRequestHeader->getSequenceId(), Eq(SEQUENCE_ID)); auto allocateResponseResult = serverPortUser.allocateResponse(receivedRequestHeader, sizeof(DataType), alignof(DataType)); ASSERT_FALSE(allocateResponseResult.has_error()); auto responseHeader = allocateResponseResult.value(); EXPECT_FALSE(serverPortUser.sendResponse(responseHeader).has_error()); auto getResponseResult = clientPortUser.getResponse(); ASSERT_FALSE(getResponseResult.has_error()); auto receivedResponseHeader = getResponseResult.value(); EXPECT_THAT(receivedResponseHeader->getSequenceId(), Eq(SEQUENCE_ID)); } // END communication tests } // namespace iox_test_roudi_portmanager
42.375499
120
0.763009
andre-nguyen
c501e558740a8553e011fff44a46c859952b9830
165
hpp
C++
GameAutomatic.hpp
CLA-TC1030/s4t3.sye
4718be3e4387be95c28bb908f575f6e78e160d4f
[ "MIT" ]
null
null
null
GameAutomatic.hpp
CLA-TC1030/s4t3.sye
4718be3e4387be95c28bb908f575f6e78e160d4f
[ "MIT" ]
null
null
null
GameAutomatic.hpp
CLA-TC1030/s4t3.sye
4718be3e4387be95c28bb908f575f6e78e160d4f
[ "MIT" ]
null
null
null
#pragma once #include "Game.hpp" class GameAutomatic:public Game { protected: std::string getInput(); public: GameAutomatic(std::string, bool, bool); };
16.5
43
0.690909
CLA-TC1030
c503dd4e8a0c722fd1729d6c136b6a7d958becd8
40,067
cpp
C++
integrate/property_system/property_system/source/property_system/serialization/sr_property_json_de_serializer.cpp
BoneCrasher/ShirabeEngine
39b3aa2c5173084d59b96b7f60c15207bff0ad04
[ "MIT" ]
5
2019-12-02T12:28:57.000Z
2021-04-07T21:21:13.000Z
integrate/property_system/property_system/source/property_system/serialization/sr_property_json_de_serializer.cpp
BoneCrasher/ShirabeEngine
39b3aa2c5173084d59b96b7f60c15207bff0ad04
[ "MIT" ]
null
null
null
integrate/property_system/property_system/source/property_system/serialization/sr_property_json_de_serializer.cpp
BoneCrasher/ShirabeEngine
39b3aa2c5173084d59b96b7f60c15207bff0ad04
[ "MIT" ]
1
2020-01-09T14:25:42.000Z
2020-01-09T14:25:42.000Z
#include "sr_pch.h" #include <inttypes.h> // PRIu64 etc... #include <cstdlib> #include <nlohmann/json.hpp> #include <core/base/types/sr_enum.h> #include "property_system/sr_meta_object.h" #include "property_system/sr_meta_property.h" #include "property_system/sr_meta_prototype.h" #include "property_system/serialization/sr_property_json_de_serializer.h" /*! * Convenience wrapper to check for identity of a type T and a CMetaObject shared pointer. */ template <typename TType> constexpr bool TIsObjectPointer = std::is_same_v<TType, CStdSharedPtr_t<CMetaObject>>; /*! * Convenience wrapper to check for identity of a type T and std::wstring. */ template <typename TType> constexpr bool TIsWideString = std::is_same_v<TType, std::wstring>; //<----------------------------------------------------------------------------- //< //<----------------------------------------------------------------------------- CPropertySerializer::CSerializationResult::CSerializationResult(const nlohmann::json& aData) : mData(std::move(aData)) { } //<----------------------------------------------------------------------------- //<----------------------------------------------------------------------------- //< //<----------------------------------------------------------------------------- bool CPropertySerializer::CSerializationResult::asString(std::string& aOutString) const { static constexpr const int32_t sIndent = 4; static constexpr const char sIndentChar = ' '; static constexpr const bool sEnsureAscii = true; const std::string result = mData.dump(sIndent, sIndentChar, sEnsureAscii); aOutString = result; return true; } //<----------------------------------------------------------------------------- //<----------------------------------------------------------------------------- //< //<----------------------------------------------------------------------------- bool CPropertySerializer::CSerializationResult::asBinaryBuffer(std::vector<uint8_t>& aOutBinaryBuffer) const { // @Review.Note: Went through source code of nlohmann. // Shouldn't throw anything during msgpack serialization. // Only the UBJSON variants throw, which we don't use. const std::vector<uint8_t> binary = nlohmann::json::to_msgpack(mData); aOutBinaryBuffer = binary; return true; } //<----------------------------------------------------------------------------- //<----------------------------------------------------------------------------- //< //<----------------------------------------------------------------------------- bool CPropertySerializer::initialize() { return true; } //<----------------------------------------------------------------------------- //<----------------------------------------------------------------------------- //< //<----------------------------------------------------------------------------- bool CPropertySerializer::deinitialize() { return true; } //<----------------------------------------------------------------------------- //<----------------------------------------------------------------------------- //< //<----------------------------------------------------------------------------- bool CPropertySerializer::serialize( const CMetaObject& aSource, CStdSharedPtr_t<ISerializer<CMetaObject>::IResult>& aOutResult) { nlohmann::json root{}; pushObject(root); const bool serialized = writeObject(aSource); if(serialized) { CStdSharedPtr_t<ISerializer<CMetaObject>::IResult> result = makeStdSharedPtr<CPropertySerializer::CSerializationResult>(root); aOutResult = result; } else { aOutResult = nullptr; } popObject(); return serialized; } //<----------------------------------------------------------------------------- //<----------------------------------------------------------------------------- //< //<----------------------------------------------------------------------------- bool CPropertySerializer::writeObject(const CMetaObject& aObject) { // Double dispatch. The object knows, what to serialize... const bool serialized = aObject.acceptSerializer(*this); return serialized; } //<----------------------------------------------------------------------------- //<----------------------------------------------------------------------------- //< //<----------------------------------------------------------------------------- bool CPropertySerializer::beginProperties() { nlohmann::json& current = mObjectStack.top(); current["properties"] = nlohmann::json{}; nlohmann::json& properties = current["properties"]; pushObject(properties); return true; } //<----------------------------------------------------------------------------- //<----------------------------------------------------------------------------- //< //<----------------------------------------------------------------------------- bool CPropertySerializer::commitProperties() { popObject(); return true; } //<----------------------------------------------------------------------------- //<----------------------------------------------------------------------------- //< //<----------------------------------------------------------------------------- template <typename TDataType> bool CPropertySerializer::writePropertyImpl( const std::string& aIdentifier, const CMetaProperty<TDataType>& aProperty) { nlohmann::json object{}; pushObject(object); const bool serialized = aProperty.acceptSerializer(*this); popObject(); nlohmann::json& parent = mObjectStack.top(); parent[aIdentifier] = object; return serialized; } //<----------------------------------------------------------------------------- //<----------------------------------------------------------------------------- //< //<----------------------------------------------------------------------------- template <typename TDataType> bool CPropertySerializer::writeAttributeImpl(const std::string& aIdentifier, const TDataType& aValue) { bool serialized = true; nlohmann::json& current = mObjectStack.top(); if constexpr (TIsObjectPointer<TDataType>) { nlohmann::json object{}; pushObject(object); if(aValue) { serialized = writeObject(*aValue); } popObject(); current[aIdentifier] = object; } else if constexpr (TIsWideString<TDataType>) { const std::string narrowed = CString::narrow(aValue); current[aIdentifier] = narrowed; } else { current[aIdentifier] = aValue; } return serialized; } //<----------------------------------------------------------------------------- //<----------------------------------------------------------------------------- //< //<----------------------------------------------------------------------------- template <typename TDataType> bool CPropertySerializer::writeValueListImpl(const std::string& aIdentifier, const std::vector<TDataType>& aValues) { bool serialized = true; if constexpr (TIsObjectPointer<TDataType>) { std::vector<nlohmann::json> serializedObjects{}; for(const CStdSharedPtr_t<CMetaObject>& object : aValues) { const bool containsValue = (nullptr != object); if(containsValue) { nlohmann::json jsonObject{}; pushObject(jsonObject); serialized = writeObject(*object); popObject(); serializedObjects.push_back(jsonObject); } else { serializedObjects.push_back(nullptr); // Will write "null" } } nlohmann::json& current = mObjectStack.top(); current[aIdentifier] = serializedObjects; } else { nlohmann::json list{}; for(uint32_t k=0; k<aValues.size(); ++k) { if constexpr (std::is_same_v<TDataType, std::wstring>) { const std::wstring& widened = aValues.at(k); const std::string narrowed = CString::narrow(widened); list[k] = narrowed; } else { list[k] = aValues.at(k); } } nlohmann::json& current = mObjectStack.top(); current[aIdentifier] = list; } return serialized; } //<----------------------------------------------------------------------------- //<----------------------------------------------------------------------------- //< //<----------------------------------------------------------------------------- void CPropertySerializer::pushObject(Object_t& aJSONObjectInstance) { mObjectStack.push(aJSONObjectInstance); } //<----------------------------------------------------------------------------- //<----------------------------------------------------------------------------- //< //<----------------------------------------------------------------------------- void CPropertySerializer::popObject() { mObjectStack.pop(); } //<----------------------------------------------------------------------------- //<----------------------------------------------------------------------------- //< //<----------------------------------------------------------------------------- CPropertyDeserializer::CDeserializationResult::CDeserializationResult( CStdSharedPtr_t<CMetaObject> aObject, const PathMap_t& aPropertyPathMap) : mObject(aObject) , mPropertyPathMap(aPropertyPathMap) {} //<----------------------------------------------------------------------------- //<----------------------------------------------------------------------------- //< //<----------------------------------------------------------------------------- bool CPropertyDeserializer::CDeserializationResult::asT(CStdSharedPtr_t<CMetaObject>& aOutResult) const { if(!mObject) { aOutResult = nullptr; return false; } aOutResult = mObject; return true; } //<----------------------------------------------------------------------------- //<----------------------------------------------------------------------------- //< //<----------------------------------------------------------------------------- bool CPropertyDeserializer::CDeserializationResult::getPropertyPathMap(PathMap_t& aOutPathMap) const { aOutPathMap = mPropertyPathMap; return true; } //<----------------------------------------------------------------------------- //<----------------------------------------------------------------------------- //< //<----------------------------------------------------------------------------- CPropertyDeserializer::CPropertyDeserializer(const bool aUseDynamicDeserialization) : mUseDynamicDeserialization(aUseDynamicDeserialization) {} //<----------------------------------------------------------------------------- //<----------------------------------------------------------------------------- //< //<----------------------------------------------------------------------------- bool CPropertyDeserializer::initialize() { return true; } //<----------------------------------------------------------------------------- //<----------------------------------------------------------------------------- //< //<----------------------------------------------------------------------------- bool CPropertyDeserializer::deinitialize() { mAdjacencyLists.clear(); mPropertyReferences.clear(); return true; } //<----------------------------------------------------------------------------- //<----------------------------------------------------------------------------- //< //<----------------------------------------------------------------------------- bool CPropertyDeserializer::deserialize( const std::string& aSource, CStdSharedPtr_t<IDeserializer<CMetaObject>::IResult>& aOutResult) { // Important @ Developer: For some reason I had to store the result returned // from deserializeFwd into a temporary object. // Could be a compiler bug. Will review this (MBT). CStdSharedPtr_t<IDeserializer<CMetaObject>::IResult> result = nullptr; nlohmann::json deserializedJSON = nlohmann::json::parse(aSource); const bool objectSuccessfullyRead = deserializeFwd(deserializedJSON, result); if(objectSuccessfullyRead) { aOutResult = result; } else { aOutResult = nullptr; } return objectSuccessfullyRead; } //<----------------------------------------------------------------------------- //<----------------------------------------------------------------------------- //< //<----------------------------------------------------------------------------- bool CPropertyDeserializer::deserialize( const std::vector<uint8_t>& aSource, CStdSharedPtr_t<IDeserializer<CMetaObject>::IResult>& aOutResult) { // Important @ Developer: For some reason I had to store the result returned // from deserializeFwd into a temporary object. // Could be a compiler bug. Will review this (MBT). CStdSharedPtr_t<IDeserializer<CMetaObject>::IResult> result = nullptr; nlohmann::json deserializedJSON = nlohmann::json::from_msgpack(aSource); const bool objectSuccessfullyRead = deserializeFwd(deserializedJSON, result); if(objectSuccessfullyRead) { aOutResult = result; } else { aOutResult = nullptr; } return objectSuccessfullyRead; } //<----------------------------------------------------------------------------- //<----------------------------------------------------------------------------- //< //<----------------------------------------------------------------------------- // Forward declaration. Documentation in definition. bool compilePathMap( const CPropertyDeserializer::AdjacencyListMap_t& aAdjacencyLists, const CPropertyDeserializer::PropertyRefMap_t& aPropertyReferences, const CPropertyDeserializer::NodeId_t& aRootNodeId, CPropertyDeserializer::PathMap_t& aOutPathMap); //<----------------------------------------------------------------------------- //<----------------------------------------------------------------------------- //< //<----------------------------------------------------------------------------- bool CPropertyDeserializer::deserializeFwd( const nlohmann::json& deserializedJSON, CStdSharedPtr_t<IDeserializer<CMetaObject>::IResult>& aOutResult) { pushObject(deserializedJSON); CStdSharedPtr_t<CMetaObject> instance = nullptr; const bool objectSuccessfullyRead = readObjectFwd(instance); if(objectSuccessfullyRead) { PathMap_t pathMap{}; const bool pathMapCompiled = compilePathMap(mAdjacencyLists, mPropertyReferences, instance->getInstanceUID(), pathMap); SR_RETURN_IF(!pathMapCompiled, false) CStdSharedPtr_t<IDeserializer<CMetaObject>::IResult> result = makeStdSharedPtr<CDeserializationResult>(instance, pathMap); aOutResult = result; } else { aOutResult = nullptr; } popObject(); return objectSuccessfullyRead; } //<----------------------------------------------------------------------------- //<----------------------------------------------------------------------------- //< //<----------------------------------------------------------------------------- /*! * Create an empty typed CMetaProperty and push it to a variant holder. * * @param aOutVariant A variant out reference holding the result of creation. * @return True, if successful. False, otherwise. */ template <typename T> bool createEmptyProperty( const PropertyUID_t& aUID, MetaPropertyVariant_t& aOutVariant) { // Any error case? const CMetaProperty<T> property = { aUID, "", T() }; MetaPropertyVariant_t variant = property; aOutVariant = variant; return true; } //<----------------------------------------------------------------------------- //<----------------------------------------------------------------------------- //< //<----------------------------------------------------------------------------- /*! * Reads a properties valueType and invokes creation of a typed CMetaProperty instance. * * @param aProperty The JSONified property from nlohmann::json. * @param aOutPropertyVariant A variant out reference holding the result of creation. * @return True, if successful. False otherwise. */ bool determinePropertyForDynamicDeserialization( const nlohmann::json& aProperty, MetaPropertyVariant_t& aOutPropertyVariant) { using ValueType_t = CMetaPropertyCore::EPropertyValueType; const CEnum::UnderlyingType_t<ValueType_t> valueTypeValue = aProperty["valuetype"]; const ValueType_t valueType = static_cast<ValueType_t>(valueTypeValue); const PropertyUID_t& uid = aProperty["uid"]; MetaPropertyVariant_t variant{}; bool deserialized = true; switch(valueType) { default: case ValueType_t::Undefined: break; case ValueType_t::Int8: deserialized = deserialized && createEmptyProperty<int8_t>(uid, variant); break; case ValueType_t::Int16: deserialized = deserialized && createEmptyProperty<int16_t>(uid, variant); break; case ValueType_t::Int32: deserialized = deserialized && createEmptyProperty<int32_t>(uid, variant); break; case ValueType_t::Int64: deserialized = deserialized && createEmptyProperty<int64_t>(uid, variant); break; case ValueType_t::UInt8: deserialized = deserialized && createEmptyProperty<uint8_t>(uid, variant); break; case ValueType_t::UInt16: deserialized = deserialized && createEmptyProperty<uint16_t>(uid, variant); break; case ValueType_t::UInt32: deserialized = deserialized && createEmptyProperty<uint32_t>(uid, variant); break; case ValueType_t::UInt64: deserialized = deserialized && createEmptyProperty<uint64_t>(uid, variant); break; case ValueType_t::Float: deserialized = deserialized && createEmptyProperty<float>(uid, variant); break; case ValueType_t::Double: deserialized = deserialized && createEmptyProperty<double>(uid, variant); break; case ValueType_t::String: deserialized = deserialized && createEmptyProperty<std::string>(uid, variant); break; case ValueType_t::WString: deserialized = deserialized && createEmptyProperty<std::wstring>(uid, variant); break; case ValueType_t::Object: deserialized = deserialized && createEmptyProperty<CStdSharedPtr_t<CMetaObject>>(uid, variant); break; } aOutPropertyVariant = variant; return deserialized; } //<----------------------------------------------------------------------------- //<----------------------------------------------------------------------------- //< //<----------------------------------------------------------------------------- /*! * Attempts to enter the "properties block" of an object and determine all properties available. * Foreach property detected, a typed empty property instance will be created and stored in 'aOutMap'. * * @param aObject The nlohmann::json object optionally containing properties. * @param aOutMap The map holding an assignment of propertyId to empty property instance. * @return True, if successful, false otherwise. */ bool determinePropertiesForDynamicDeserialization( const nlohmann::json& aObject, MetaPropertyMap_t& aOutMap) { using ConstIterator_t = nlohmann::json::const_iterator; const bool propertiesContained = aObject.find("properties") != aObject.end(); SR_RETURN_IF(false == propertiesContained, true); // It is valid to not have properties! const nlohmann::json& properties = aObject.at("properties"); for (ConstIterator_t it = properties.begin(); it != properties.end(); ++it) { const nlohmann::json& property = it.value(); MetaPropertyVariant_t variant{}; const bool determined = determinePropertyForDynamicDeserialization(property, variant); SR_RETURN_IF(false == determined, false); aOutMap[it.key()] = variant; } return true; } //<----------------------------------------------------------------------------- //<----------------------------------------------------------------------------- //< //<----------------------------------------------------------------------------- /*! * Creates a resolver usable within std::visit to fetch an iterator to an element * inside an object's property map and store it in a property reference map. * * @tparam T The underlying type of the property. */ template <typename T> struct SGetPropertyReferenceResolver { static auto getResolver( CPropertyDeserializer::PropertyRefMap_t& aPropertyReferences, CPropertyDeserializer::PropertyMap_t& aPropertyMap, const std::string& aUID) { const auto fn = [&] (CMetaProperty<T> &aResolvedInstance) -> void { aPropertyReferences[aResolvedInstance.getPropertyUID()] = aPropertyMap.find(aUID); }; return fn; } }; //<----------------------------------------------------------------------------- //<----------------------------------------------------------------------------- //< //<----------------------------------------------------------------------------- bool CPropertyDeserializer::readObjectFwd(CStdSharedPtr_t<CMetaObject> &aOutObject) { const nlohmann::json& current = mObjectStack.top(); std::string prototypeId = ""; std::string instanceName = ""; InstanceUID_t instanceUID = 0; readAttribute("uid", instanceUID); readAttribute("name", instanceName); if(0 == instanceUID) { CStdSharedPtr_t<CMetaSystem> system = CMetaSystem::get(); instanceUID = system->generateObjectUID(); } CStdSharedPtr_t<CMetaObject> instance = nullptr; if(mUseDynamicDeserialization) // Read all properties, which can be found! { MetaPropertyMap_t map{}; const bool hasProperties = determinePropertiesForDynamicDeserialization(current, map); SR_UNUSED(hasProperties); CMetaObject* object = CMetaObject::create(nullptr, instanceUID, instanceName, map); instance = CStdSharedPtr_t<CMetaObject>(object); } else { readAttribute("prototypeId", prototypeId); CStdSharedPtr_t<CMetaSystem> system = CMetaSystem::get(); CStdSharedPtr_t<CMetaPrototypeBase> prototype = system->getPrototype<CMetaPrototypeBase>(prototypeId); instance = prototype->createAbstractInstance(instanceUID, instanceName); } pushAdjacencyLevel(instanceUID); const bool objectSuccessfullyRead = readObject(*instance); if(objectSuccessfullyRead) { // PathMap-generation: Fetching property references here. // Important: // We store iterators into the maps, as they won't be invalidated as long as // the desired map is always the same instance. CMetaObject::PropertyMap_t &properties = instance->getMutableProperties(); for(auto& [id, property] : properties) { const std::string& uid = id; MetaPropertyVariant_t& propertyVariant = properties.at(uid); SR_RESOLVE(SGetPropertyReferenceResolver, propertyVariant, mPropertyReferences, properties, uid); } aOutObject = instance; } else { aOutObject = nullptr; } popAdjacencyLevel(); return objectSuccessfullyRead; } //<----------------------------------------------------------------------------- //<----------------------------------------------------------------------------- //< //<----------------------------------------------------------------------------- bool CPropertyDeserializer::readObject(CMetaObject& aObject) { // @Code.Review: Temporary // std::cerr << "Reading object\n"; const bool deserialized = aObject.acceptDeserializer(*this); return deserialized; } //<----------------------------------------------------------------------------- //<----------------------------------------------------------------------------- //< //<----------------------------------------------------------------------------- bool CPropertyDeserializer::beginProperties() { const nlohmann::json& current = mObjectStack.top(); const bool propertyContained = current.find("properties") != current.end(); SR_RETURN_IF(false == propertyContained, false); const nlohmann::json& properties = current.at("properties"); pushObject(properties); return true; } //<----------------------------------------------------------------------------- //<----------------------------------------------------------------------------- //< //<----------------------------------------------------------------------------- bool CPropertyDeserializer::commitProperties() { popObject(); return true; } //<----------------------------------------------------------------------------- //<----------------------------------------------------------------------------- //< //<----------------------------------------------------------------------------- template <typename TDataType> bool CPropertyDeserializer::readPropertyImpl( const std::string& aIdentifier, CMetaProperty<TDataType>& aProperty) { // @Code.Review: Temporary // std::cerr << "Reading property " << aIdentifier << "\n"; const nlohmann::json& current = mObjectStack.top(); const bool propertyContained = current.find(aIdentifier) != current.end(); SR_RETURN_IF(false == propertyContained, false); const nlohmann::json& propertyJSON = current.at(aIdentifier); const bool propertyIsNull = propertyJSON.is_null(); if(propertyIsNull) { aProperty = CMetaProperty<TDataType>(); return true; } PropertyUID_t propertyUID = propertyJSON["uid"]; if(0 == propertyUID) { CStdSharedPtr_t<CMetaSystem> system = CMetaSystem::get(); propertyUID = system->generatePropertyUID(); } pushAdjacencyLevel(propertyUID); pushObject(propertyJSON); const bool deserialized = aProperty.acceptDeserializer(*this); popObject(); popAdjacencyLevel(); return deserialized; } //<----------------------------------------------------------------------------- //<----------------------------------------------------------------------------- //< //<----------------------------------------------------------------------------- template <typename TDataType> bool CPropertyDeserializer::readAttributeImpl(const std::string& aIdentifier, TDataType& aValue) { // @Code.Review: Temporary //std::cerr << "Reading attribute " << aIdentifier << "\n"; const nlohmann::json& current = mObjectStack.top(); const bool attributeContained = current.find(aIdentifier) != current.end(); SR_RETURN_IF(false == attributeContained, false); const nlohmann::json& attributeJSON = current.at(aIdentifier); const bool attributeIsNull = attributeJSON.is_null(); if(attributeIsNull) { aValue = TDataType(); return true; } if constexpr (TIsObjectPointer<TDataType>) { SR_RETURN_IF(false == attributeJSON.is_object(), false); CStdSharedPtr_t<CMetaObject> instance = nullptr; pushObject(attributeJSON); const bool deserialized = readObjectFwd(instance); if(deserialized) { aValue = instance; } popObject(); return deserialized; } else if constexpr (TIsWideString<TDataType>) { SR_RETURN_IF(false == attributeJSON.is_string(), false); const std::string& narrowed = attributeJSON; const std::wstring widened = CString::widen(narrowed); aValue = widened; return true; } else { const TDataType attributeValue = attributeJSON; aValue = attributeValue; return true; } } //<----------------------------------------------------------------------------- //<----------------------------------------------------------------------------- //< //<----------------------------------------------------------------------------- template <typename TDataType> bool CPropertyDeserializer::readValueListImpl(const std::string& aIdentifier, std::vector<TDataType>& aValues) { // @Code.Review: Temporary //std::cerr << "Reading value list " << aIdentifier << "\n"; const nlohmann::json& current = mObjectStack.top(); const bool valueContained = current.find(aIdentifier) != current.end(); SR_RETURN_IF(false == valueContained, false); const nlohmann::json& listJSON = current.at(aIdentifier); const bool valueListIsNull = listJSON.is_null(); if(valueListIsNull) { aValues = std::vector<TDataType>(); return true; } const bool valueIsArray = listJSON.is_array(); SR_RETURN_IF(false == valueIsArray, false); std::vector<TDataType> list{}; if(!listJSON.empty()) { for(const nlohmann::json& valueJSON : listJSON) { if constexpr (std::is_same_v<TDataType, CStdSharedPtr_t<CMetaObject>>) { CStdSharedPtr_t<CMetaObject> instance = nullptr; const bool isNull = valueJSON.is_null(); if(!isNull) { pushObject(valueJSON); const bool deserialized = readObjectFwd(instance); SR_RETURN_IF(false == deserialized, false); popObject(); } list.push_back(std::move(instance)); } else if constexpr (std::is_same_v<TDataType, std::wstring>) { const std::string str = valueJSON; const std::wstring wstr = CString::widen(str); list.push_back(wstr); } else { const TDataType& value = valueJSON; list.push_back(value); } } } aValues = list; return true; } //<----------------------------------------------------------------------------- //<----------------------------------------------------------------------------- //< //<----------------------------------------------------------------------------- void CPropertyDeserializer::pushObject(const Object_t& aObjectRef) { mObjectStack.push(aObjectRef); } //<----------------------------------------------------------------------------- //<----------------------------------------------------------------------------- //< //<----------------------------------------------------------------------------- void CPropertyDeserializer::popObject() { mObjectStack.pop(); } //<----------------------------------------------------------------------------- //<----------------------------------------------------------------------------- //< //<----------------------------------------------------------------------------- void CPropertyDeserializer::pushAdjacencyLevel(const NodeId_t& aNodeId) { if(!mAdjacencyStack.empty()) { mCurrentAdjacencyList->get().push_back(aNodeId); } mCurrentAdjacencyList = mAdjacencyLists[aNodeId]; // Implicit creation mAdjacencyStack.push(aNodeId); } //<----------------------------------------------------------------------------- //<----------------------------------------------------------------------------- //< //<----------------------------------------------------------------------------- void CPropertyDeserializer::popAdjacencyLevel() { // If the stack is empty, assume clean state and perform no-op. if(mAdjacencyStack.empty()) { return; } mAdjacencyStack.pop(); // If the last element was popped from the stack, subsequent access to a "top" element // would fail... if(mAdjacencyStack.empty()) { mCurrentAdjacencyList.reset(); return; } const NodeId_t& parentItemId = mAdjacencyStack.top(); mCurrentAdjacencyList = mAdjacencyLists[parentItemId]; } //<----------------------------------------------------------------------------- //<----------------------------------------------------------------------------- //< //<----------------------------------------------------------------------------- /*! * Algorithm to generate a path-map from a map of adjacency lists. * * The algorithm is based on the adjacency-list, depth-first-sorting, with * small modifications. * * @param aAdjacencyLists Map of adjacency lists, mapping a NodeId to an array of other NodeIds, * resembling graph-edges. * @param aPropertyRefMap Map of nodeId -> iterator into the internal property-maps of the object instances. * @param aRootNodeId The root-object's nodeId to begin the algorithm with. * @param aOutPathMap A map of string -> iterator into the internal property-maps of the object instances. * @return True, if the map generation was successful. False otherwise. */ bool compilePathMap( const CPropertyDeserializer::AdjacencyListMap_t& aAdjacencyLists, const CPropertyDeserializer::PropertyRefMap_t& aPropertyRefMap, const CPropertyDeserializer::NodeId_t& aRootNodeId, CPropertyDeserializer::PathMap_t& aOutPathMap) { // Convenience alias to keep code readable. using AdjacencyListMap_t = CPropertyDeserializer::AdjacencyListMap_t; using AdjacencyList_t = CPropertyDeserializer::AdjacencyList_t; using NodeId_t = CPropertyDeserializer::NodeId_t; using VisitedEdgeMap_t = std::map<CPropertyDeserializer::NodeId_t, bool>; using PathMap_t = CPropertyDeserializer::PathMap_t; // Recursive function declaration, called for edge in the graph. std::function< void( const AdjacencyListMap_t&,/* Map of adjacency lists for next edge access */ const NodeId_t& ,/* Current edge-root node id to be processed. */ VisitedEdgeMap_t& ,/* Map of edge-roots to "already visited flag" to avoid circularity */ const std::string& ,/* Path of the parent property, appended by the currently processed properties' index in the parent property. */ PathMap_t& /* Output reference to the path map */)> CompileFn_i; // Effective function definition, which had to be separated for recursive calls to work. CompileFn_i = [&]( const AdjacencyListMap_t& aEdges, const NodeId_t& aNode, VisitedEdgeMap_t& aVisitedEdges, const std::string& aCurrentPath, PathMap_t& aOutPathMap) -> void { const bool edgeVisited = aVisitedEdges[aNode]; SR_RETURN_VOID_IF(edgeVisited); aVisitedEdges[aNode] = true; // Only proceed if a specific node effectively has outgoing edges, since the path map // only stores leaf-nodes, i.e. any property, which is not of type Object. const bool edgeContained = aEdges.contains(aNode); if(edgeContained) { std::string path = aCurrentPath; // Check, whether the node is a property and generate the property path! // For object-nodes, the path is equal to the parent properties' path. const bool isProperty = aPropertyRefMap.contains(aNode); if(isProperty) { CPropertyDeserializer::PropertyMap_t::iterator property = aPropertyRefMap.at(aNode); std::string propertyName = ""; MetaPropertyVariant_t& variant = property->second; SR_RESOLVE(SGetPropertyNameResolver, variant, propertyName); path = CString::formatString("%s/%s", path.c_str(), propertyName.c_str()); } AdjacencyList_t adjacencyList = aEdges.at(aNode); // If no adjacent nodes are available, we found a leaf-property, i.e. not of type Object! const bool noAdjacentNodes = adjacencyList.empty(); if(noAdjacentNodes) { CPropertyDeserializer::PropertyMap_t::iterator refWrapper = aPropertyRefMap.at(aNode); MetaPropertyVariant_t& variant = refWrapper->second; SR_RESOLVE(SSetPropertyPathResolver, variant, path); aOutPathMap.add(path, refWrapper); } else { uint16_t k = 0; std::string localPath = path; for(const NodeId_t& adjacent : aEdges.at(aNode)) { // Append the descendent property's index in the current parent to the path, // to avoid name-clashes in subpaths and permit path-templates to work // with indexed access for Chain-type properties. localPath = path; if(isProperty) { localPath = CString::formatString("%s/%" PRIu16, path.c_str(), k); ++k; } CompileFn_i(aEdges, adjacent, aVisitedEdges, localPath, aOutPathMap); } } } }; // Make sure that "no edges were visited". VisitedEdgeMap_t visitedEdges {}; for(const auto& [k, v] : aAdjacencyLists) { visitedEdges[k] = false; } // Process root object! // Imporant: // Since the object is no leaf, the path is empty (see fourth param). CompileFn_i(aAdjacencyLists, aRootNodeId, visitedEdges, "", aOutPathMap); return true; } //<----------------------------------------------------------------------------- //<----------------------------------------------------------------------------- //< //<----------------------------------------------------------------------------- // Explicit instantiations for the template functions. #define SR_INSTANTIATE_WRITE_PROPERTY(_aType) \ template bool CPropertySerializer::writePropertyImpl<_aType>(const std::string&, const CMetaProperty<_aType>&); #define SR_INSTANTIATE_WRITE_ATTRIBUTE(_aType) \ template bool CPropertySerializer::writeAttributeImpl<_aType>(const std::string&, const _aType&); #define SR_INSTANTIATE_WRITE_VALUE_LIST(_aType) \ template bool CPropertySerializer::writeValueListImpl<_aType>(const std::string&, const std::vector<_aType>&); #define SR_INSTANTIATE_READ_PROPERTY(_aType) \ template bool CPropertyDeserializer::readPropertyImpl<_aType>(const std::string&, CMetaProperty<_aType>&); #define SR_INSTANTIATE_READ_ATTRIBUTE(_aType) \ template bool CPropertyDeserializer::readAttributeImpl<_aType>(const std::string&, _aType&); #define SR_INSTANTIATE_READ_VALUE_LIST(_aType) \ template bool CPropertyDeserializer::readValueListImpl<_aType>(const std::string&, std::vector<_aType>&); SR_APPLY_FOREACH_PROPERTY_TYPE(SR_INSTANTIATE_WRITE_PROPERTY) SR_APPLY_FOREACH_PROPERTY_TYPE(SR_INSTANTIATE_WRITE_ATTRIBUTE) SR_APPLY_FOREACH_PROPERTY_TYPE(SR_INSTANTIATE_WRITE_VALUE_LIST) SR_APPLY_FOREACH_PROPERTY_TYPE(SR_INSTANTIATE_READ_PROPERTY) SR_APPLY_FOREACH_PROPERTY_TYPE(SR_INSTANTIATE_READ_ATTRIBUTE) SR_APPLY_FOREACH_PROPERTY_TYPE(SR_INSTANTIATE_READ_VALUE_LIST)
35.67854
146
0.493498
BoneCrasher
c50492357198a9359be285c244895f3f3d5d7c3c
6,954
cpp
C++
src/morda/util/key.cpp
igagis/morda
dd7b58f7cb2689d56b7796cc9b6b9302aad1a529
[ "MIT" ]
69
2016-12-07T05:56:53.000Z
2020-11-27T20:59:05.000Z
src/morda/util/key.cpp
igagis/morda
dd7b58f7cb2689d56b7796cc9b6b9302aad1a529
[ "MIT" ]
103
2015-07-10T14:42:21.000Z
2020-09-09T16:16:21.000Z
src/morda/util/key.cpp
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 ================ */ #include "key.hpp" #include <array> #include <algorithm> #include <utki/sort.hpp> using namespace morda; using namespace std::string_view_literals; key_modifier morda::to_key_modifier(morda::key key){ switch(key){ case key::left_shift: return key_modifier::left_shift; case key::right_shift: return key_modifier::right_shift; case key::left_alt: return key_modifier::left_alt; case key::right_alt: return key_modifier::right_alt; case key::left_control: return key_modifier::left_control; case key::right_control: return key_modifier::right_control; case key::left_command: return key_modifier::left_command; case key::right_command: return key_modifier::right_command; default: return key_modifier::unknown; } } namespace{ // the order of strings must correspond to the order of morda::key enum items constexpr std::array<std::string_view, size_t(morda::key::enum_size)> key_names = { "space"sv, "enter"sv, "0"sv, "1"sv, "2"sv, "3"sv, "4"sv, "5"sv, "6"sv, "7"sv, "8"sv, "9"sv, "a"sv, "b"sv, "c"sv, "d"sv, "e"sv, "f"sv, "g"sv, "h"sv, "i"sv, "j"sv, "k"sv, "l"sv, "m"sv, "n"sv, "o"sv, "p"sv, "q"sv, "r"sv, "s"sv, "t"sv, "u"sv, "v"sv, "w"sv, "x"sv, "y"sv, "z"sv, "arrow_left"sv, "arrow_right"sv, "arrow_up"sv, "arrow_down"sv, "comma"sv, "semicolon"sv, "apostrophe"sv, "period"sv, "slash"sv, "backslash"sv, "tabulator"sv, "left_shift"sv, "right_shift"sv, "end"sv, "left_square_bracket"sv, "right_square_bracket"sv, "grave"sv, "minus"sv, "equals"sv, "backspace"sv, "capslock"sv, "escape"sv, "left_control"sv, "left_alt"sv, "f1"sv, "f2"sv, "f3"sv, "f4"sv, "f5"sv, "f6"sv, "f7"sv, "f8"sv, "f9"sv, "f10"sv, "f11"sv, "f12"sv, "right_control"sv, "print_screen"sv, "right_alt"sv, "home"sv, "page_up"sv, "page_down"sv, "insert"sv, "deletion"sv, "pause"sv, "left_command"sv, "right_command"sv, "menu"sv, "function"sv, "f17"sv, "f18"sv, "f19"sv, "f20"sv, "f13"sv, "f16"sv, "f14"sv, "f15"sv }; } std::string_view morda::to_string(morda::key key){ if(key >= morda::key::enum_size){ return "unknown"sv; } return key_names[size_t(key)]; } namespace{ struct key_name_key_pair{ std::string_view first; morda::key second; }; constexpr auto key_name_to_key_ordered_mapping = []()constexpr{ std::array<key_name_key_pair, size_t(morda::key::enum_size)> arr = {{ {"space"sv, morda::key::space}, {"enter"sv, morda::key::enter}, {"0"sv, morda::key::zero}, {"1"sv, morda::key::one}, {"2"sv, morda::key::two}, {"3"sv, morda::key::three}, {"4"sv, morda::key::four}, {"5"sv, morda::key::five}, {"6"sv, morda::key::six}, {"7"sv, morda::key::seven}, {"8"sv, morda::key::eight}, {"9"sv, morda::key::nine}, {"a"sv, morda::key::a}, {"b"sv, morda::key::b}, {"c"sv, morda::key::c}, {"d"sv, morda::key::d}, {"e"sv, morda::key::e}, {"f"sv, morda::key::f}, {"g"sv, morda::key::g}, {"h"sv, morda::key::h}, {"i"sv, morda::key::i}, {"j"sv, morda::key::j}, {"k"sv, morda::key::k}, {"l"sv, morda::key::l}, {"m"sv, morda::key::m}, {"n"sv, morda::key::n}, {"o"sv, morda::key::o}, {"p"sv, morda::key::p}, {"q"sv, morda::key::q}, {"r"sv, morda::key::r}, {"s"sv, morda::key::s}, {"t"sv, morda::key::t}, {"u"sv, morda::key::u}, {"v"sv, morda::key::v}, {"w"sv, morda::key::w}, {"x"sv, morda::key::x}, {"y"sv, morda::key::y}, {"z"sv, morda::key::z}, {"arrow_left"sv, morda::key::arrow_left}, {"arrow_right"sv, morda::key::arrow_right}, {"arrow_up"sv, morda::key::arrow_up}, {"arrow_down"sv, morda::key::arrow_down}, {"comma"sv, morda::key::comma}, {"semicolon"sv, morda::key::semicolon}, {"apostrophe"sv, morda::key::apostrophe}, {"period"sv, morda::key::period}, {"slash"sv, morda::key::slash}, {"backslash"sv, morda::key::backslash}, {"tabulator"sv, morda::key::tabulator}, {"left_shift"sv, morda::key::left_shift}, {"right_shift"sv, morda::key::right_shift}, {"end"sv, morda::key::end}, {"left_square_bracket"sv, morda::key::left_square_bracket}, {"right_square_bracket"sv, morda::key::right_square_bracket}, {"grave"sv, morda::key::grave}, {"minus"sv, morda::key::minus}, {"equals"sv, morda::key::equals}, {"backspace"sv, morda::key::backspace}, {"capslock"sv, morda::key::capslock}, {"escape"sv, morda::key::escape}, {"left_control"sv, morda::key::left_control}, {"left_alt"sv, morda::key::left_alt}, {"f1"sv, morda::key::f1}, {"f2"sv, morda::key::f2}, {"f3"sv, morda::key::f3}, {"f4"sv, morda::key::f4}, {"f5"sv, morda::key::f5}, {"f6"sv, morda::key::f6}, {"f7"sv, morda::key::f7}, {"f8"sv, morda::key::f8}, {"f9"sv, morda::key::f9}, {"f10"sv, morda::key::f10}, {"f11"sv, morda::key::f11}, {"f12"sv, morda::key::f12}, {"right_control"sv, morda::key::right_control}, {"print_screen"sv, morda::key::print_screen}, {"right_alt"sv, morda::key::right_alt}, {"home"sv, morda::key::home}, {"page_up"sv, morda::key::page_up}, {"page_down"sv, morda::key::page_down}, {"insert"sv, morda::key::insert}, {"deletion"sv, morda::key::deletion}, {"pause"sv, morda::key::pause}, {"left_command"sv, morda::key::left_command}, {"right_command"sv, morda::key::right_command}, {"menu"sv, morda::key::menu}, {"function"sv, morda::key::function}, {"f17"sv, morda::key::f17}, {"f18"sv, morda::key::f18}, {"f19"sv, morda::key::f19}, {"f20"sv, morda::key::f20}, {"f13"sv, morda::key::f13}, {"f16"sv, morda::key::f16}, {"f14"sv, morda::key::f14}, {"f15"sv, morda::key::f15}, }}; utki::sort( arr.begin(), arr.end(), [](const auto& a, const auto& b){return a.first < b.first;} ); return arr; }(); } morda::key morda::to_key(std::string_view name){ auto i = std::lower_bound( key_name_to_key_ordered_mapping.begin(), key_name_to_key_ordered_mapping.end(), name, [](const auto& a, const std::string_view& b){ return a.first < b; } ); if(i != key_name_to_key_ordered_mapping.end() && i->first == name){ return i->second; } return morda::key::unknown; }
23.896907
83
0.616336
igagis
c5057e33c2052dc4c28ea90172d9bc071ee3aab1
3,638
hpp
C++
include/Oculus/Spatializer/Propagation/MaterialProperty.hpp
RedBrumbler/virtuoso-codegen
e83f6f0f9b47bec4b6dd976b21edc1d46bf3cfe3
[ "Unlicense" ]
null
null
null
include/Oculus/Spatializer/Propagation/MaterialProperty.hpp
RedBrumbler/virtuoso-codegen
e83f6f0f9b47bec4b6dd976b21edc1d46bf3cfe3
[ "Unlicense" ]
null
null
null
include/Oculus/Spatializer/Propagation/MaterialProperty.hpp
RedBrumbler/virtuoso-codegen
e83f6f0f9b47bec4b6dd976b21edc1d46bf3cfe3
[ "Unlicense" ]
null
null
null
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "beatsaber-hook/shared/utils/typedefs.h" #include "beatsaber-hook/shared/utils/byref.hpp" // Including type: System.Enum #include "System/Enum.hpp" // Completed includes // Type namespace: Oculus.Spatializer.Propagation namespace Oculus::Spatializer::Propagation { // Forward declaring type: MaterialProperty struct MaterialProperty; } #include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp" DEFINE_IL2CPP_ARG_TYPE(::Oculus::Spatializer::Propagation::MaterialProperty, "Oculus.Spatializer.Propagation", "MaterialProperty"); // Type namespace: Oculus.Spatializer.Propagation namespace Oculus::Spatializer::Propagation { // Size: 0x4 #pragma pack(push, 1) // Autogenerated type: Oculus.Spatializer.Propagation.MaterialProperty // [TokenAttribute] Offset: FFFFFFFF struct MaterialProperty/*, public ::System::Enum*/ { public: public: // public System.UInt32 value__ // Size: 0x4 // Offset: 0x0 uint value; // Field size check static_assert(sizeof(uint) == 0x4); public: // Creating value type constructor for type: MaterialProperty constexpr MaterialProperty(uint value_ = {}) noexcept : value{value_} {} // Creating interface conversion operator: operator ::System::Enum operator ::System::Enum() noexcept { return *reinterpret_cast<::System::Enum*>(this); } // Creating conversion operator: operator uint constexpr operator uint() const noexcept { return value; } // static field const value: static public Oculus.Spatializer.Propagation.MaterialProperty ABSORPTION static constexpr const uint ABSORPTION = 0u; // Get static field: static public Oculus.Spatializer.Propagation.MaterialProperty ABSORPTION static ::Oculus::Spatializer::Propagation::MaterialProperty _get_ABSORPTION(); // Set static field: static public Oculus.Spatializer.Propagation.MaterialProperty ABSORPTION static void _set_ABSORPTION(::Oculus::Spatializer::Propagation::MaterialProperty value); // static field const value: static public Oculus.Spatializer.Propagation.MaterialProperty TRANSMISSION static constexpr const uint TRANSMISSION = 1u; // Get static field: static public Oculus.Spatializer.Propagation.MaterialProperty TRANSMISSION static ::Oculus::Spatializer::Propagation::MaterialProperty _get_TRANSMISSION(); // Set static field: static public Oculus.Spatializer.Propagation.MaterialProperty TRANSMISSION static void _set_TRANSMISSION(::Oculus::Spatializer::Propagation::MaterialProperty value); // static field const value: static public Oculus.Spatializer.Propagation.MaterialProperty SCATTERING static constexpr const uint SCATTERING = 2u; // Get static field: static public Oculus.Spatializer.Propagation.MaterialProperty SCATTERING static ::Oculus::Spatializer::Propagation::MaterialProperty _get_SCATTERING(); // Set static field: static public Oculus.Spatializer.Propagation.MaterialProperty SCATTERING static void _set_SCATTERING(::Oculus::Spatializer::Propagation::MaterialProperty value); // Get instance field reference: public System.UInt32 value__ uint& dyn_value__(); }; // Oculus.Spatializer.Propagation.MaterialProperty #pragma pack(pop) static check_size<sizeof(MaterialProperty), 0 + sizeof(uint)> __Oculus_Spatializer_Propagation_MaterialPropertySizeCheck; static_assert(sizeof(MaterialProperty) == 0x4); } #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
51.971429
131
0.752886
RedBrumbler
c506f34afec97b348679d5ca3e4c5ec6ddaac37e
19,959
hpp
C++
segmatch_ros/include/segmatch_ros/common.hpp
Oofs/segmap
98f1fddc15b863c781b78f59c65487be5e0dc497
[ "BSD-3-Clause" ]
771
2018-04-21T06:47:18.000Z
2022-03-30T11:49:32.000Z
segmatch_ros/include/segmatch_ros/common.hpp
Oofs/segmap
98f1fddc15b863c781b78f59c65487be5e0dc497
[ "BSD-3-Clause" ]
111
2018-04-22T10:11:50.000Z
2022-03-21T02:16:12.000Z
segmatch_ros/include/segmatch_ros/common.hpp
Oofs/segmap
98f1fddc15b863c781b78f59c65487be5e0dc497
[ "BSD-3-Clause" ]
287
2018-04-21T06:43:23.000Z
2022-03-24T17:45:05.000Z
#ifndef SEGMATCH_ROS_COMMON_HPP_ #define SEGMATCH_ROS_COMMON_HPP_ #include <math.h> #include <interactive_markers/interactive_marker_server.h> #include <laser_slam/common.hpp> #include <nav_msgs/Path.h> #include <pcl_conversions/pcl_conversions.h> #include <pcl/point_cloud.h> #include <pcl/point_types.h> #include <ros/ros.h> #include <segmatch/common.hpp> #include <segmatch/utilities.hpp> #include <segmatch/parameters.hpp> #include <segmatch/segmatch.hpp> #include <segmatch/segmented_cloud.hpp> #include <sensor_msgs/LaserScan.h> #include <sensor_msgs/PointCloud2.h> #include <tf/transform_listener.h> #include <visualization_msgs/Marker.h> #include <visualization_msgs/MarkerArray.h> namespace segmatch_ros { struct SegMatchWorkerParams { bool localize; bool close_loops; std::string target_cloud_filename; std::string world_frame; double distance_between_segmentations_m; double distance_to_lower_target_cloud_for_viz_m; bool align_target_map_on_first_loop_closure = false; segmatch::SegMatchParams segmatch_params; double ratio_of_points_to_keep_when_publishing; bool export_segments_and_matches = false; bool publish_predicted_segment_matches = false; double line_scale_loop_closures; double line_scale_matches; }; // struct SegMatchWorkerParams struct Color { Color(float red, float green, float blue) : r(red), g(green), b(blue) {} float r; float g; float b; }; static void publishLineSet(const segmatch::PointPairs& point_pairs, const std::string& frame, const float line_scale, const Color& color, const ros::Publisher& publisher) { visualization_msgs::Marker line_list; line_list.header.frame_id = frame; line_list.header.stamp = ros::Time(); line_list.ns = "matcher_trainer"; line_list.type = visualization_msgs::Marker::LINE_LIST; line_list.action = visualization_msgs::Marker::ADD; line_list.color.r = color.r; line_list.color.g = color.g; line_list.color.b = color.b; line_list.color.a = 1.0; line_list.scale.x = line_scale; for (size_t i = 0u; i < point_pairs.size(); ++i) { geometry_msgs::Point p; p.x = point_pairs[i].first.x; p.y = point_pairs[i].first.y; p.z = point_pairs[i].first.z; line_list.points.push_back(p); p.x = point_pairs[i].second.x; p.y = point_pairs[i].second.y; p.z = point_pairs[i].second.z; line_list.points.push_back(p); } publisher.publish(line_list); } static void convert_to_pcl_point_cloud(const sensor_msgs::PointCloud2& cloud_message, segmatch::PointICloud* converted) { pcl::PCLPointCloud2 pcl_point_cloud_2; pcl_conversions::toPCL(cloud_message, pcl_point_cloud_2); pcl::fromPCLPointCloud2(pcl_point_cloud_2, *converted); } static void convert_to_point_cloud_2_msg(const segmatch::PointICloud& cloud, const std::string& frame, sensor_msgs::PointCloud2* converted) { CHECK_NOTNULL(converted); // Convert to PCLPointCloud2. pcl::PCLPointCloud2 pcl_point_cloud_2; pcl::toPCLPointCloud2(cloud, pcl_point_cloud_2); // Convert to sensor_msgs::PointCloud2. pcl_conversions::fromPCL(pcl_point_cloud_2, *converted); // Apply frame to msg. converted->header.frame_id = frame; } static void convert_to_point_cloud_2_msg(const segmatch::PointCloud& cloud, const std::string& frame, sensor_msgs::PointCloud2* converted) { segmatch::PointICloud cloud_i; pcl::copyPointCloud(cloud, cloud_i); convert_to_point_cloud_2_msg(cloud_i, frame, converted); } static void publishCloud(const segmatch::PointICloud& cloud, const std::string& frame, const ros::Publisher& publisher) { sensor_msgs::PointCloud2 cloud_as_message; convert_to_point_cloud_2_msg(cloud, frame, &cloud_as_message); publisher.publish(cloud_as_message); } static segmatch::SegMatchParams getSegMatchParams(const ros::NodeHandle& nh, const std::string& prefix) { segmatch::SegMatchParams params; std::string ns = prefix + "/SegMatch"; nh.getParam(ns + "/segmentation_radius_m", params.segmentation_radius_m); nh.getParam(ns + "/segmentation_height_above_m", params.segmentation_height_above_m); nh.getParam(ns + "/segmentation_height_below_m", params.segmentation_height_below_m); nh.getParam(ns + "/filter_boundary_segments", params.filter_boundary_segments); nh.getParam(ns + "/boundary_radius_m", params.boundary_radius_m); nh.getParam(ns + "/filter_duplicate_segments", params.filter_duplicate_segments); nh.getParam(ns + "/centroid_distance_threshold_m", params.centroid_distance_threshold_m); int min_time_between_segment_for_matches_s; nh.getParam(ns + "/min_time_between_segment_for_matches_s", min_time_between_segment_for_matches_s); params.min_time_between_segment_for_matches_ns = laser_slam::Time(min_time_between_segment_for_matches_s) * 1000000000u; nh.getParam(ns + "/check_pose_lies_below_segments", params.check_pose_lies_below_segments); nh.getParam(ns + "/radius_for_normal_estimation_m", params.radius_for_normal_estimation_m); nh.getParam(ns + "/normal_estimator_type", params.normal_estimator_type); // Local map parameters. nh.getParam(ns + "/LocalMap/voxel_size_m", params.local_map_params.voxel_size_m); nh.getParam(ns + "/LocalMap/min_points_per_voxel", params.local_map_params.min_points_per_voxel); nh.getParam(ns + "/LocalMap/radius_m", params.local_map_params.radius_m); nh.getParam(ns + "/LocalMap/min_vertical_distance_m", params.local_map_params.min_vertical_distance_m); nh.getParam(ns + "/LocalMap/max_vertical_distance_m", params.local_map_params.max_vertical_distance_m); nh.getParam(ns + "/LocalMap/neighbors_provider_type", params.local_map_params.neighbors_provider_type); // Descriptors parameters. nh.getParam(ns + "/Descriptors/descriptor_types", params.descriptors_params.descriptor_types); nh.getParam(ns + "/Descriptors/fast_point_feature_histograms_search_radius", params.descriptors_params.fast_point_feature_histograms_search_radius); nh.getParam(ns + "/Descriptors/fast_point_feature_histograms_normals_search_radius", params.descriptors_params. fast_point_feature_histograms_normals_search_radius); nh.getParam(ns + "/Descriptors/point_feature_histograms_search_radius", params.descriptors_params.point_feature_histograms_search_radius); nh.getParam(ns + "/Descriptors/point_feature_histograms_normals_search_radius", params.descriptors_params.point_feature_histograms_normals_search_radius); nh.getParam(ns + "/Descriptors/cnn_model_path", params.descriptors_params.cnn_model_path); nh.getParam(ns + "/Descriptors/semantics_nn_path", params.descriptors_params.semantics_nn_path); // Segmenter parameters. nh.getParam(ns + "/Segmenters/segmenter_type", params.segmenter_params.segmenter_type); nh.getParam(ns + "/Segmenters/min_cluster_size", params.segmenter_params.min_cluster_size); nh.getParam(ns + "/Segmenters/max_cluster_size", params.segmenter_params.max_cluster_size); nh.getParam(ns + "/Segmenters/radius_for_growing", params.segmenter_params.radius_for_growing); nh.getParam(ns + "/Segmenters/sc_smoothness_threshold_deg", params.segmenter_params.sc_smoothness_threshold_deg); nh.getParam(ns + "/Segmenters/sc_curvature_threshold", params.segmenter_params.sc_curvature_threshold); // Classifier parameters. nh.getParam(ns + "/Classifier/classifier_filename", params.classifier_params.classifier_filename); nh.getParam(ns + "/Classifier/threshold_to_accept_match", params.classifier_params.threshold_to_accept_match); nh.getParam(ns + "/Classifier/rf_max_depth", params.classifier_params.rf_max_depth); nh.getParam(ns + "/Classifier/rf_min_sample_ratio", params.classifier_params.rf_min_sample_ratio); nh.getParam(ns + "/Classifier/rf_regression_accuracy", params.classifier_params.rf_regression_accuracy); nh.getParam(ns + "/Classifier/rf_use_surrogates", params.classifier_params.rf_use_surrogates); nh.getParam(ns + "/Classifier/rf_max_categories", params.classifier_params.rf_max_categories); nh.getParam(ns + "/Classifier/rf_priors", params.classifier_params.rf_priors); nh.getParam(ns + "/Classifier/rf_calc_var_importance", params.classifier_params.rf_calc_var_importance); nh.getParam(ns + "/Classifier/rf_n_active_vars", params.classifier_params.rf_n_active_vars); nh.getParam(ns + "/Classifier/rf_max_num_of_trees", params.classifier_params.rf_max_num_of_trees); nh.getParam(ns + "/Classifier/rf_accuracy", params.classifier_params.rf_accuracy); nh.getParam(ns + "/Classifier/do_not_use_cars", params.classifier_params.do_not_use_cars); // Convenience copy to find the correct feature distance according to // descriptors types. nh.getParam(ns + "/Descriptors/descriptor_types", params.classifier_params.descriptor_types); nh.getParam(ns + "/Classifier/n_nearest_neighbours", params.classifier_params.n_nearest_neighbours); nh.getParam(ns + "/Classifier/enable_two_stage_retrieval", params.classifier_params.enable_two_stage_retrieval); nh.getParam(ns + "/Classifier/knn_feature_dim", params.classifier_params.knn_feature_dim); nh.getParam(ns + "/Classifier/apply_hard_threshold_on_feature_distance", params.classifier_params.apply_hard_threshold_on_feature_distance); nh.getParam(ns + "/Classifier/feature_distance_threshold", params.classifier_params.feature_distance_threshold); nh.getParam(ns + "/Classifier/normalize_eigen_for_knn", params.classifier_params.normalize_eigen_for_knn); nh.getParam(ns + "/Classifier/normalize_eigen_for_hard_threshold", params.classifier_params.normalize_eigen_for_hard_threshold); nh.getParam(ns + "/Classifier/max_eigen_features_values", params.classifier_params.max_eigen_features_values); // Geometric Consistency Parameters. nh.getParam(ns + "/GeometricConsistency/recognizer_type", params.geometric_consistency_params.recognizer_type); nh.getParam(ns + "/GeometricConsistency/resolution", params.geometric_consistency_params.resolution); nh.getParam(ns + "/GeometricConsistency/min_cluster_size", params.geometric_consistency_params.min_cluster_size); nh.getParam(ns + "/GeometricConsistency/max_consistency_distance_for_caching", params.geometric_consistency_params.max_consistency_distance_for_caching); return params; } static SegMatchWorkerParams getSegMatchWorkerParams(const ros::NodeHandle& nh, const std::string& prefix) { SegMatchWorkerParams params; const std::string ns = prefix + "/SegMatchWorker"; nh.getParam(ns + "/localize", params.localize); nh.getParam(ns + "/close_loops", params.close_loops); if (params.localize && params.close_loops) { LOG(INFO) << "Parameters localize and close_loops both set."; LOG(INFO) << "Setting close_loops to false."; params.close_loops = false; } if (params.localize) { using namespace boost::filesystem; nh.getParam(ns + "/target_cloud_filename", params.target_cloud_filename); path target_cloud_path(params.target_cloud_filename); CHECK(exists(target_cloud_path)) << "Target cloud does not exist."; } nh.getParam(ns +"/distance_between_segmentations_m", params.distance_between_segmentations_m); nh.getParam(ns +"/distance_to_lower_target_cloud_for_viz_m", params.distance_to_lower_target_cloud_for_viz_m); nh.getParam(ns +"/align_target_map_on_first_loop_closure", params.align_target_map_on_first_loop_closure); nh.getParam(ns +"/export_segments_and_matches", params.export_segments_and_matches); nh.getParam(ns +"/ratio_of_points_to_keep_when_publishing", params.ratio_of_points_to_keep_when_publishing); nh.getParam(ns +"/publish_predicted_segment_matches", params.publish_predicted_segment_matches); nh.getParam(ns +"/line_scale_loop_closures", params.line_scale_loop_closures); nh.getParam(ns +"/line_scale_matches", params.line_scale_matches); params.segmatch_params = getSegMatchParams(nh, ns); return params; } // TODO needed? static segmatch::GroundTruthParameters getGroundTruthParams( const ros::NodeHandle& nh, const std::string& prefix) { segmatch::GroundTruthParameters params; nh.getParam(prefix + "/GroundTruth/overlap_radius", params.overlap_radius); nh.getParam(prefix + "/GroundTruth/significance_percentage", params.significance_percentage); nh.getParam(prefix + "/GroundTruth/number_nearest_segments", params.number_nearest_segments); nh.getParam(prefix + "/GroundTruth/maximum_centroid_distance_m", params.maximum_centroid_distance_m); return params; } static segmatch::PclPoint tfTransformToPoint(const tf::StampedTransform& tf_transform) { segmatch::PclPoint point; point.x = tf_transform.getOrigin().getX(); point.y = tf_transform.getOrigin().getY(); point.z = tf_transform.getOrigin().getZ(); return point; } segmatch::SE3 geometryMsgTransformToSE3(const geometry_msgs::Transform& transform) { segmatch::SE3::Position pos(transform.translation.x, transform.translation.y, transform.translation.z); segmatch::SE3::Rotation::Implementation rot(transform.rotation.w, transform.rotation.x, transform.rotation.y, transform.rotation.z); return segmatch::SE3(pos, rot); } geometry_msgs::Transform SE3ToGeometryMsgTransform(const segmatch::SE3& transform) { geometry_msgs::Transform result; Eigen::Affine3d eigen_transform(transform.getTransformationMatrix()); result.translation.x = eigen_transform(0,3); result.translation.y = eigen_transform(1,3); result.translation.z = eigen_transform(2,3); Eigen::Quaterniond rotation(eigen_transform.rotation()); result.rotation.w = rotation.w(); result.rotation.x = rotation.x(); result.rotation.y = rotation.y(); result.rotation.z = rotation.z(); // TODO: safe casting double to float? return result; } /// \brief Covariance type including pose and uncertainty information. struct CovarianceMsg { /// \brief Pose vector. geometry_msgs::Pose pose; /// \brief Uncertainty vector. geometry_msgs::Vector3 magnitude; }; typedef std::vector<CovarianceMsg> CovarianceMsgs; // Convert SE3 object to ROS geometry message pose. static void convert_to_geometry_msg_pose(const segmatch::SE3& pose, geometry_msgs::Pose* pose_msg) { CHECK_NOTNULL(pose_msg); pose_msg->position.x = pose.getPosition().x(); pose_msg->position.y = pose.getPosition().y(); pose_msg->position.z = pose.getPosition().z(); pose_msg->orientation.w = pose.getRotation().w(); pose_msg->orientation.x = pose.getRotation().x(); pose_msg->orientation.y = pose.getRotation().y(); pose_msg->orientation.z = pose.getRotation().z(); } // Publish ellipsoids given covariance matrices and fixed frame. static void drawCovarianceEllipsoids(const std::string& frame, const CovarianceMsgs& covariances, const ros::Publisher& publisher) { visualization_msgs::MarkerArray marker_array; visualization_msgs::Marker marker; for (size_t i = 0u; i < covariances.size(); ++i) { marker.header.frame_id = frame; marker.header.stamp = ros::Time(); marker.ns = "laser_mapper"; marker.id = i; marker.type = visualization_msgs::Marker::SPHERE; marker.action = visualization_msgs::Marker::ADD; marker.pose = covariances.at(i).pose; marker.scale = covariances.at(i).magnitude; marker.color.a = 1.0; // Distinguish start pose covariance. if (i == 0u) { marker.color.r = 1.0; marker.color.g = 1.0; marker.color.b = 0.0; } else { marker.color.r = 1.0; marker.color.g = 0.0; marker.color.b = 0.2; } // Keep marker until updated. marker.lifetime = ros::Duration(); marker_array.markers.push_back(marker); } publisher.publish(marker_array); } struct BoundingBox { segmatch::PclPoint centroid; double alignment, scale_x_m, scale_y_m, scale_z_m; }; static segmatch::PclPoint rotateAroundZAxis(const segmatch::PclPoint& p, const segmatch::PclPoint& o, double angle_rad) { segmatch::PclPoint q; q.x = o.x + cos(angle_rad) * (p.x - o.x) - sin(angle_rad) * (p.y - o.y); q.y = o.y + sin(angle_rad) * (p.x - o.x) + cos(angle_rad) * (p.y - o.y); q.z = p.z; return q; } static geometry_msgs::Point toPointMsg(const segmatch::PclPoint& p) { geometry_msgs::Point p_msg; p_msg.x = p.x; p_msg.y = p.y; p_msg.z = p.z; return p_msg; } static void publishBoundingBoxes(const std::vector<BoundingBox>& bounding_boxes, const std::string& frame, const ros::Publisher& publisher, const Color& color, double distance_to_lower_boxes_m = 0.0) { visualization_msgs::Marker marker; marker.header.frame_id = frame; marker.header.stamp = ros::Time(); marker.ns = "bounding_boxes"; marker.type = visualization_msgs::Marker::LINE_LIST; marker.action = visualization_msgs::Marker::ADD; marker.lifetime = ros::Duration(); marker.color.a = 1.0; marker.color.r = color.r; marker.color.g = color.g; marker.color.b = color.b; marker.scale.x = 0.2; marker.id = 0u; for (const auto& box: bounding_boxes) { segmatch::PclPoint centroid = box.centroid; centroid.z -= distance_to_lower_boxes_m; const double scale_x_m = box.scale_x_m / 2.0; const double scale_y_m = box.scale_y_m / 2.0; const double scale_z_m = box.scale_z_m / 2.0; const double angle_rad = box.alignment; // Centroid and direction. marker.points.push_back(toPointMsg(centroid)); segmatch::PclPoint p_dir(centroid); p_dir.x += scale_x_m; marker.points.push_back(toPointMsg(rotateAroundZAxis(p_dir, centroid, angle_rad))); segmatch::PclPoint p1(centroid); p1.x -= scale_x_m; p1.y += scale_y_m; p1.z -= scale_z_m; segmatch::PclPoint p2(centroid); p2.x -= scale_x_m; p2.y -= scale_y_m; p2.z -= scale_z_m; segmatch::PclPoint p3(centroid); p3.x += scale_x_m; p3.y -= scale_y_m; p3.z -= scale_z_m; segmatch::PclPoint p4(centroid); p4.x += scale_x_m; p4.y += scale_y_m; p4.z -= scale_z_m; segmatch::PclPoint p5(p1); p5.z += scale_z_m * 2.0; segmatch::PclPoint p6(p2); p6.z += scale_z_m * 2.0; segmatch::PclPoint p7(p3); p7.z += scale_z_m * 2.0; segmatch::PclPoint p8(p4); p8.z += scale_z_m * 2.0; for (auto pp: {&p1, &p2, &p2, &p3, &p3, &p4, &p4, &p1, &p5, &p6, &p6, &p7, &p7, &p8, &p8, &p5, &p1, &p5, &p2, &p6, &p3, &p7, &p4, &p8}) { marker.points.push_back(toPointMsg(rotateAroundZAxis(*pp, centroid, angle_rad))); } } publisher.publish(marker); } } // namespace segmatch_ros #endif // SEGMATCH_ROS_COMMON_HPP_
38.680233
95
0.699785
Oofs
c50a9a9a532a1e45cee1fef10d231e8ed4d48297
14,049
cpp
C++
groups/bsl/bslalg/bslalg_autoscalardestructor.t.cpp
hughesr/bde
d593e3213918b9292c25e08cfc5b6651bacdea0d
[ "Apache-2.0" ]
1
2019-01-22T19:44:05.000Z
2019-01-22T19:44:05.000Z
groups/bsl/bslalg/bslalg_autoscalardestructor.t.cpp
anuranrc/bde
d593e3213918b9292c25e08cfc5b6651bacdea0d
[ "Apache-2.0" ]
null
null
null
groups/bsl/bslalg/bslalg_autoscalardestructor.t.cpp
anuranrc/bde
d593e3213918b9292c25e08cfc5b6651bacdea0d
[ "Apache-2.0" ]
null
null
null
// bslalg_autoscalardestructor.t.cpp -*-C++-*- #include <bslalg_autoscalardestructor.h> #include <bslma_allocator.h> // for testing only #include <bslma_default.h> // for testing only #include <bslma_testallocator.h> // for testing only #include <bslma_testallocatorexception.h> // for testing only #include <bslma_usesbslmaallocator.h> #include <bsls_alignmentutil.h> // for testing only #include <bsls_bsltestutil.h> #include <bsls_stopwatch.h> // for testing only #include <ctype.h> // 'isalpha' #include <stdio.h> // 'printf' #include <stdlib.h> // 'atoi' #include <string.h> // 'strlen' #include <new> using namespace BloombergLP; //============================================================================= // TEST PLAN //----------------------------------------------------------------------------- // Overview // -------- // The component to be tested provides a proctor to help with exception-safety // guarantees. The test sequence is very simple: we only have to ascertain // that the proctor does destroy its guarded object unless 'release' has been // called. We use a test type that monitors the number of constructions and // destructions, and that allocates in order to take advantage of the standard // 'bslma' exception test. //----------------------------------------------------------------------------- // [ 2] bslalg::AutoScalarDestructor(T *object); // [ 2] ~AutoScalarDestructor(); // [ 3] void release(); // [ 2] void reset(T *object); //----------------------------------------------------------------------------- // [ 1] BREATHING TEST // [ 4] USAGE EXAMPLE // ============================================================================ // STANDARD BSL ASSERT TEST FUNCTION // ---------------------------------------------------------------------------- namespace { int testStatus = 0; void aSsErT(bool condition, const char *message, int line) { if (condition) { printf("Error " __FILE__ "(%d): %s (failed)\n", line, message); if (0 <= testStatus && testStatus <= 100) { ++testStatus; } } } } // close unnamed namespace // ============================================================================ // STANDARD BSL TEST DRIVER MACRO ABBREVIATIONS // ---------------------------------------------------------------------------- #define ASSERT BSLS_BSLTESTUTIL_ASSERT #define ASSERTV BSLS_BSLTESTUTIL_ASSERTV #define LOOP_ASSERT BSLS_BSLTESTUTIL_LOOP_ASSERT #define LOOP0_ASSERT BSLS_BSLTESTUTIL_LOOP0_ASSERT #define LOOP1_ASSERT BSLS_BSLTESTUTIL_LOOP1_ASSERT #define LOOP2_ASSERT BSLS_BSLTESTUTIL_LOOP2_ASSERT #define LOOP3_ASSERT BSLS_BSLTESTUTIL_LOOP3_ASSERT #define LOOP4_ASSERT BSLS_BSLTESTUTIL_LOOP4_ASSERT #define LOOP5_ASSERT BSLS_BSLTESTUTIL_LOOP5_ASSERT #define LOOP6_ASSERT BSLS_BSLTESTUTIL_LOOP6_ASSERT #define Q BSLS_BSLTESTUTIL_Q // Quote identifier literally. #define P BSLS_BSLTESTUTIL_P // Print identifier and value. #define P_ BSLS_BSLTESTUTIL_P_ // P(X) without '\n'. #define T_ BSLS_BSLTESTUTIL_T_ // Print a tab (w/o newline). #define L_ BSLS_BSLTESTUTIL_L_ // current Line number //============================================================================= // SEMI-STANDARD NEGATIVE-TESTING MACROS //----------------------------------------------------------------------------- // This component supports only wide contracts, so there is no negative testing // to perform. //============================================================================= // GLOBAL TYPEDEFS/CONSTANTS/TYPES FOR TESTING //----------------------------------------------------------------------------- // TYPES class TestType; typedef TestType T; // uses 'bslma' allocators // STATIC DATA const int MAX_ALIGN = bsls::AlignmentUtil::BSLS_MAX_ALIGNMENT; static int numDefaultCtorCalls = 0; static int numCharCtorCalls = 0; static int numCopyCtorCalls = 0; static int numAssignmentCalls = 0; static int numDestructorCalls = 0; bslma::TestAllocator *Z; // initialized at the start of main() // ============== // class TestType // ============== class TestType { // This test type contains a 'char' in some allocated storage. It counts // the number of default and copy constructions, assignments, and // destructions. It has no traits other than using a 'bslma' allocator. // It could have the bit-wise moveable traits but we defer that trait to // the 'MoveableTestType'. char *d_data_p; bslma::Allocator *d_allocator_p; public: // CREATORS TestType(bslma::Allocator *ba = 0) : d_data_p(0) , d_allocator_p(bslma::Default::allocator(ba)) { ++numDefaultCtorCalls; d_data_p = (char *)d_allocator_p->allocate(sizeof(char)); *d_data_p = '?'; } TestType(char c, bslma::Allocator *ba = 0) : d_data_p(0) , d_allocator_p(bslma::Default::allocator(ba)) { ++numCharCtorCalls; d_data_p = (char *)d_allocator_p->allocate(sizeof(char)); *d_data_p = c; } TestType(const TestType& original, bslma::Allocator *ba = 0) : d_data_p(0) , d_allocator_p(bslma::Default::allocator(ba)) { ++numCopyCtorCalls; if (&original != this) { d_data_p = (char *)d_allocator_p->allocate(sizeof(char)); *d_data_p = *original.d_data_p; } } ~TestType() { ++numDestructorCalls; *d_data_p = '_'; d_allocator_p->deallocate(d_data_p); d_data_p = 0; } // MANIPULATORS TestType& operator=(const TestType& rhs) { ++numAssignmentCalls; if (&rhs != this) { char *newData = (char *)d_allocator_p->allocate(sizeof(char)); *d_data_p = '_'; d_allocator_p->deallocate(d_data_p); d_data_p = newData; *d_data_p = *rhs.d_data_p; } return *this; } void setDatum(char c) { *d_data_p = c; } // ACCESSORS char datum() const { return *d_data_p; } void print() const { if (d_data_p) { ASSERT(isalpha(*d_data_p)); printf("%c (int: %d)\n", *d_data_p, (int)*d_data_p); } else { printf("VOID\n"); } } }; namespace BloombergLP { namespace bslma { template <> struct UsesBslmaAllocator<TestType> : bsl::true_type {}; } // close namespace bslma } // close enterprise namespace bool operator==(const TestType& lhs, const TestType& rhs) { ASSERT(isalpha(lhs.datum())); ASSERT(isalpha(rhs.datum())); return lhs.datum() == rhs.datum(); } //============================================================================= // USAGE EXAMPLE //----------------------------------------------------------------------------- // TBD //============================================================================= // MAIN PROGRAM //----------------------------------------------------------------------------- int main(int argc, char *argv[]) { int test = argc > 1 ? atoi(argv[1]) : 0; bool verbose = argc > 2; bool veryVerbose = argc > 3; bool veryVeryVerbose = argc > 4; bool veryVeryVeryVerbose = argc > 5; (void)veryVeryVerbose; // suppress warning setbuf(stdout, NULL); // Use unbuffered output printf("TEST " __FILE__ " CASE %d\n", test); bslma::TestAllocator testAllocator(veryVeryVeryVerbose); Z = &testAllocator; switch (test) { case 0: // Zero is always the leading case. case 4: { // -------------------------------------------------------------------- // TESTING USAGE EXAMPLE // // Concerns: That the usage example compiles and runs as expected. // // Testing: // USAGE EXAMPLE // -------------------------------------------------------------------- if (verbose) printf("Testing usage example.\n"); } break; case 3: { // -------------------------------------------------------------------- // TESTING 'release' // // Concerns: That the guard does not free guarded memory if 'release' // has been called. // // Plan: // // Testing: // void release(); // -------------------------------------------------------------------- if (verbose) printf("\nTESTING 'release'." "\n==================\n"); const int MAX_SIZE = 1; static union { char d_raw[MAX_SIZE * sizeof(T)]; bsls::AlignmentUtil::MaxAlignedType d_align; } u; T *buf = (T*)&u.d_raw[0]; if (verbose) printf("\tWith release.\n"); { char c = 'a'; for (int i = 0; i < MAX_SIZE; ++i, ++c) { new (&buf[i]) T(c, Z); if (veryVerbose) { buf[i].print(); } } bslalg::AutoScalarDestructor<T> mG(&buf[0]); mG.release(); } ASSERT(0 < testAllocator.numBytesInUse()); ASSERT(0 == testAllocator.numMismatches()); if (verbose) printf("\tWithout release.\n"); { bslalg::AutoScalarDestructor<T> mG(&buf[0]); } ASSERT(0 == testAllocator.numBytesInUse()); ASSERT(0 == testAllocator.numMismatches()); } break; case 2: { // -------------------------------------------------------------------- // TESTING 'class bslalg::AutoScalarDestructor' // // Concerns: That the guard frees guarded memory properly upon // exceptions. // // Plan: After asserting that the interface behaves as intended and // that the guard destruction indeed frees the memory, we set up an // exception test that ensures that the guard indeed correctly guards // a varying portion of an scalar. // // Testing: // bslalg::AutoScalarDestructor(T *object); // ~AutoScalarDestructor(); // void reset(T *object); // -------------------------------------------------------------------- if (verbose) printf("\nTESTING 'bslalg::AutoScalarDestructor'." "\n======================================\n"); static union { char d_raw[sizeof(T)]; bsls::AlignmentUtil::MaxAlignedType d_align; } u; T *buf = (T*)&u.d_raw[0]; if (verbose) printf("\tSimple interface tests (from breathing test).\n"); { new (buf) T('a', Z); if (veryVerbose) { buf->print(); } bslalg::AutoScalarDestructor<T> mG(buf); mG.reset(buf); } ASSERT(0 == testAllocator.numBytesInUse()); ASSERT(0 == testAllocator.numMismatches()); if (verbose) printf("\tException test.\n"); { BSLMA_TESTALLOCATOR_EXCEPTION_TEST_BEGIN(testAllocator) { bslalg::AutoScalarDestructor<T> mG(0); const bslalg::AutoScalarDestructor<T>& G = mG; (void) G; new (buf) T('a', Z); if (veryVerbose) { buf->print(); } mG.reset(buf); } BSLMA_TESTALLOCATOR_EXCEPTION_TEST_END } ASSERT(0 == testAllocator.numBytesInUse()); ASSERT(0 == testAllocator.numMismatches()); } break; case 1: { // -------------------------------------------------------------------- // BREATHING TEST // // Concerns: // // Plan: // // Testing: // This test exercises the component but tests nothing. // -------------------------------------------------------------------- if (verbose) printf("\nBREATHING TEST" "\n==============\n"); if (verbose) printf("\nclass bslalg::AutoScalarDestructor" "\n---------------------------------\n"); { static union { char d_raw[sizeof(T)]; bsls::AlignmentUtil::MaxAlignedType d_align; } u; T *buf = (T*)&u.d_raw[0]; new (buf) T('a', Z); if (veryVerbose) { buf->print(); } bslalg::AutoScalarDestructor<T> mG(buf); } // deallocates buf } break; default: { fprintf(stderr, "WARNING: CASE `%d' NOT FOUND.\n", test); testStatus = -1; } } if (testStatus > 0) { fprintf(stderr, "Error, non-zero test status = %d.\n", testStatus); } return testStatus; } // ---------------------------------------------------------------------------- // Copyright 2013 Bloomberg Finance L.P. // // 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. // ----------------------------- END-OF-FILE ----------------------------------
33.771635
79
0.476475
hughesr
c50e80cc1c33bf401b2d13279b27854e7c368d5a
23,679
cpp
C++
src/stage/batched/host/KokkosKernels_Test_Gemm.cpp
crtrott/kokkos-kernels
0dba50f62188eb82da35bb4fe0211c7783300903
[ "BSD-3-Clause" ]
null
null
null
src/stage/batched/host/KokkosKernels_Test_Gemm.cpp
crtrott/kokkos-kernels
0dba50f62188eb82da35bb4fe0211c7783300903
[ "BSD-3-Clause" ]
null
null
null
src/stage/batched/host/KokkosKernels_Test_Gemm.cpp
crtrott/kokkos-kernels
0dba50f62188eb82da35bb4fe0211c7783300903
[ "BSD-3-Clause" ]
null
null
null
/// \author Kyungjoo Kim (kyukim@sandia.gov) #include <iomanip> #if defined(__KOKKOSKERNELS_LIBXSMM__) #include "libxsmm.h" #endif #if defined(__KOKKOSKERNELS_INTEL_MKL__) #include "mkl.h" #endif #include "Kokkos_Core.hpp" #include "impl/Kokkos_Timer.hpp" #include "KokkosKernels_Vector.hpp" #include "KokkosKernels_Gemm_Decl.hpp" #include "KokkosKernels_Gemm_Serial_Impl.hpp" #include "KokkosKernels_Gemm_Team_Impl.hpp" bool hot = false; namespace KokkosKernels { namespace Test { #define FLOP_MUL 1.0 #define FLOP_ADD 1.0 double FlopCount(int mm, int nn, int kk) { double m = (double)mm; double n = (double)nn; double k = (double)kk; return (FLOP_MUL*(m*n*k) + FLOP_ADD*(m*n*k)); } template<int BlkSize, typename DeviceSpaceType, typename VectorTagType, typename AlgoTagType> void Gemm(const int N) { typedef Kokkos::Schedule<Kokkos::Static> ScheduleType; //typedef Kokkos::Schedule<Kokkos::Dynamic> ScheduleType; typedef typename VectorTagType::value_type ValueType; constexpr int VectorLength = VectorTagType::length; const double flop = (N*VectorLength)*FlopCount(BlkSize,BlkSize,BlkSize); const double tmax = 1.0e15; typedef typename Kokkos::Impl::is_space<DeviceSpaceType>::host_mirror_space::execution_space HostSpaceType ; const int iter_begin = -10, iter_end = 100; Kokkos::Impl::Timer timer; Kokkos::View<ValueType***,Kokkos::LayoutRight,HostSpaceType> cref; Kokkos::View<ValueType***,Kokkos::LayoutRight,HostSpaceType> amat("amat", N*VectorLength, BlkSize, BlkSize), bmat("bmat", N*VectorLength, BlkSize, BlkSize); { Random random; for (int k=0;k<N*VectorLength;++k) for (int i=0;i<BlkSize;++i) for (int j=0;j<BlkSize;++j) { amat(k, i, j) = random.value(); bmat(k, i, j) = random.value(); } } typedef Vector<VectorTagType> VectorType; Kokkos::View<VectorType***,Kokkos::LayoutRight,HostSpaceType> amat_simd("amat_simd", N, BlkSize, BlkSize), bmat_simd("bmat_simd", N, BlkSize, BlkSize); for (int k0=0;k0<N;++k0) for (int k1=0;k1<VectorLength;++k1) for (int i=0;i<BlkSize;++i) for (int j=0;j<BlkSize;++j) { amat_simd(k0, i, j)[k1] = amat(k0*VectorLength+k1, i, j); bmat_simd(k0, i, j)[k1] = bmat(k0*VectorLength+k1, i, j); } // for KNL constexpr size_t LLC_CAPACITY = 34*1024*1024; Flush<LLC_CAPACITY> flush; /// /// Reference version using MKL DGEMM /// #if defined(__KOKKOSKERNELS_INTEL_MKL__) { Kokkos::View<ValueType***,Kokkos::LayoutRight,HostSpaceType> a("a", N*VectorLength, BlkSize, BlkSize), b("b", N*VectorLength, BlkSize, BlkSize), c("c", N*VectorLength, BlkSize, BlkSize); { const Kokkos::RangePolicy<DeviceSpaceType,ScheduleType> policy(0, N*VectorLength); double tavg = 0, tmin = tmax; for (int iter=iter_begin;iter<iter_end;++iter) { // flush if (!hot) flush.run(); // initialize matrices if (!hot && iter == iter_begin) { Kokkos::deep_copy(a, amat); Kokkos::deep_copy(b, bmat); } Kokkos::deep_copy(c, 0); DeviceSpaceType::fence(); timer.reset(); Kokkos::parallel_for (policy, KOKKOS_LAMBDA(const int k) { auto aa = Kokkos::subview(a, k, Kokkos::ALL(), Kokkos::ALL()); auto bb = Kokkos::subview(b, k, Kokkos::ALL(), Kokkos::ALL()); auto cc = Kokkos::subview(c, k, Kokkos::ALL(), Kokkos::ALL()); cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, BlkSize, BlkSize, BlkSize, 1.0, (double*)aa.data(), aa.stride_0(), (double*)bb.data(), bb.stride_0(), 1.0, (double*)cc.data(), cc.stride_0()); }); DeviceSpaceType::fence(); const double t = timer.seconds(); tmin = std::min(tmin, t); tavg += (iter >= 0)*t; } tavg /= iter_end; std::cout << std::setw(12) << "MKL DGEMM" << " BlkSize = " << std::setw(3) << BlkSize << " time = " << std::scientific << tmin << " avg flop/s = " << (flop/tavg) << " max flop/s = " << (flop/tmin) << std::endl; cref = c; } } #if defined(__KOKKOSKERNELS_INTEL_MKL_BATCHED__) { typedef Kokkos::View<ValueType***,Kokkos::LayoutRight,HostSpaceType> ViewType; ViewType a("a", N*VectorLength, BlkSize, BlkSize), b("b", N*VectorLength, BlkSize, BlkSize), c("c", N*VectorLength, BlkSize, BlkSize); ValueType *aa[N*VectorLength], *bb[N*VectorLength], *cc[N*VectorLength]; for (int k=0;k<N*VectorLength;++k) { aa[k] = &a(k, 0, 0); bb[k] = &b(k, 0, 0); cc[k] = &c(k, 0, 0); } { double tavg = 0, tmin = tmax; MKL_INT blksize[1] = { BlkSize }; MKL_INT lda[1] = { a.stride_1() }; MKL_INT ldb[1] = { b.stride_1() }; MKL_INT ldc[1] = { c.stride_1() }; CBLAS_TRANSPOSE transA[1] = { CblasNoTrans }; CBLAS_TRANSPOSE transB[1] = { CblasNoTrans }; double one[1] = { 1.0 }; MKL_INT size_per_grp[1] = { N*VectorLength }; for (int iter=iter_begin;iter<iter_end;++iter) { // flush if (!hot) flush.run(); // initialize matrices if (!hot && iter == iter_begin) { Kokkos::deep_copy(a, amat); Kokkos::deep_copy(b, bmat); } Kokkos::deep_copy(c, 0); DeviceSpaceType::fence(); timer.reset(); cblas_dgemm_batch(CblasRowMajor, transA, transB, blksize, blksize, blksize, one, (const double**)aa, lda, (const double**)bb, ldb, one, cc, ldc, 1, size_per_grp); DeviceSpaceType::fence(); const double t = timer.seconds(); tmin = std::min(tmin, t); tavg += (iter >= 0)*t; } tavg /= iter_end; double diff = 0; for (int i=0;i<cref.dimension(0);++i) for (int j=0;j<cref.dimension(1);++j) for (int k=0;k<cref.dimension(2);++k) diff += std::abs(cref(i,j,k) - c(i,j,k)); std::cout << std::setw(12) << "MKL Batch" << " BlkSize = " << std::setw(3) << BlkSize << " time = " << std::scientific << tmin << " avg flop/s = " << (flop/tavg) << " max flop/s = " << (flop/tmin) << " diff to ref = " << diff << std::endl; } } #endif #if defined(__KOKKOSKERNELS_INTEL_MKL_COMPACT_BATCHED__) { Kokkos::View<VectorType***,Kokkos::LayoutRight,HostSpaceType> a("a", N, BlkSize, BlkSize), b("b", N, BlkSize, BlkSize), c("c", N, BlkSize, BlkSize); { double tavg = 0, tmin = tmax; MKL_INT blksize[1] = { BlkSize }; MKL_INT lda[1] = { a.stride_1() }; MKL_INT ldb[1] = { b.stride_1() }; MKL_INT ldc[1] = { c.stride_1() }; CBLAS_TRANSPOSE transA[1] = { CblasNoTrans }; CBLAS_TRANSPOSE transB[1] = { CblasNoTrans }; double one[1] = { 1.0 }; MKL_INT size_per_grp[1] = { N*VectorLength }; compact_t A_p, B_p, C_p; A_p.layout = CblasRowMajor; A_p.rows = blksize; A_p.cols = blksize; A_p.stride = lda; A_p.group_count = 1; A_p.size_per_group = size_per_grp; A_p.format = VectorLength; A_p.mat = (double*)a.data(); B_p.layout = CblasRowMajor; B_p.rows = blksize; B_p.cols = blksize; B_p.stride = ldb; B_p.group_count = 1; B_p.size_per_group = size_per_grp; B_p.format = VectorLength; B_p.mat = (double*)b.data(); C_p.layout = CblasRowMajor; C_p.rows = blksize; C_p.cols = blksize; C_p.stride = ldc; C_p.group_count = 1; C_p.size_per_group = size_per_grp; C_p.format = VectorLength; C_p.mat = (double*)c.data(); for (int iter=iter_begin;iter<iter_end;++iter) { // flush if (!hot) flush.run(); // initialize matrices if (!hot && iter == iter_begin) { Kokkos::deep_copy(a, amat_simd); Kokkos::deep_copy(b, bmat_simd); } Kokkos::deep_copy(c, 0); DeviceSpaceType::fence(); timer.reset(); cblas_dgemm_compute_batch(transA, transB, one, &A_p, &B_p, one, &C_p); DeviceSpaceType::fence(); const double t = timer.seconds(); tmin = std::min(tmin, t); tavg += (iter >= 0)*t; } tavg /= iter_end; double diff = 0; for (int i=0;i<cref.dimension(0);++i) for (int j=0;j<cref.dimension(1);++j) for (int k=0;k<cref.dimension(2);++k) diff += std::abs(cref(i,j,k) - c(i/VectorLength,j,k)[i%VectorLength]); std::cout << std::setw(12) << "MKL Cmpct" << " BlkSize = " << std::setw(3) << BlkSize << " time = " << std::scientific << tmin << " avg flop/s = " << (flop/tavg) << " max flop/s = " << (flop/tmin) << " diff to ref = " << diff << std::endl; } } #endif #endif #if defined(__KOKKOSKERNELS_LIBXSMM__) { libxsmm_init(); Kokkos::View<ValueType***,Kokkos::LayoutRight,HostSpaceType> a("a", N*VectorLength, BlkSize, BlkSize), b("b", N*VectorLength, BlkSize, BlkSize), c("c", N*VectorLength, BlkSize, BlkSize); libxsmm_blasint lda = a.stride_1(), ldb = b.stride_1(), ldc = c.stride_1(); { const Kokkos::RangePolicy<DeviceSpaceType,ScheduleType> policy(0, N*VectorLength); double tavg = 0, tmin = tmax; // adjust column major order in xsmm char transA = 'N', transB = 'N'; libxsmm_blasint blksize = BlkSize; double one = 1.0; for (int iter=iter_begin;iter<iter_end;++iter) { // flush if (!hot) flush.run(); // initialize matrices if (!hot && iter == iter_begin) { Kokkos::deep_copy(a, amat); Kokkos::deep_copy(b, bmat); } Kokkos::deep_copy(c, 0); DeviceSpaceType::fence(); timer.reset(); Kokkos::parallel_for (policy, KOKKOS_LAMBDA(const int k) { auto aa = Kokkos::subview(a, k, Kokkos::ALL(), Kokkos::ALL()); auto bb = Kokkos::subview(b, k, Kokkos::ALL(), Kokkos::ALL()); auto cc = Kokkos::subview(c, k, Kokkos::ALL(), Kokkos::ALL()); // column major libxsmm_gemm((const char*)&transA, (const char*)&transB, blksize, blksize, blksize, (const double*)&one, (const double*)bb.data(), (const libxsmm_blasint*)&ldb, (const double*)aa.data(), (const libxsmm_blasint*)&lda, (const double*)&one, (double*)cc.data(), (const libxsmm_blasint*)&ldc); }); DeviceSpaceType::fence(); const double t = timer.seconds(); tmin = std::min(tmin, t); tavg += (iter >= 0)*t; } tavg /= iter_end; // adjust transpose double diff = 0; for (int i=0;i<cref.dimension(0);++i) for (int j=0;j<cref.dimension(1);++j) for (int k=0;k<cref.dimension(2);++k) diff += std::abs(cref(i,j,k) - c(i,j,k)); std::cout << std::setw(12) << "libxsmm" << " BlkSize = " << std::setw(3) << BlkSize << " time = " << std::scientific << tmin << " avg flop/s = " << (flop/tavg) << " max flop/s = " << (flop/tmin) << " diff to ref = " << diff << std::endl; } libxsmm_finalize(); } #endif // /// // /// Plain version (comparable to micro BLAS version) // /// // if (!std::is_same<AlgoTagType,Algo::Gemm::CompactMKL>::value) { // Kokkos::View<ValueType***,Kokkos::LayoutRight,HostSpaceType> // a("a", N*VectorLength, BlkSize, BlkSize), // b("b", N*VectorLength, BlkSize, BlkSize), // c("c", N*VectorLength, BlkSize, BlkSize); // { // const Kokkos::RangePolicy<DeviceSpaceType,ScheduleType> policy(0, N*VectorLength); // double tavg = 0, tmin = tmax; // for (int iter=iter_begin;iter<iter_end;++iter) { // // flush // flush.run(); // // initialize matrices // Kokkos::deep_copy(a, amat); // Kokkos::deep_copy(b, bmat); // Kokkos::deep_copy(c, 0); // DeviceSpaceType::fence(); // timer.reset(); // Kokkos::parallel_for // (policy, // KOKKOS_LAMBDA(const int k) { // auto aa = Kokkos::subview(a, k, Kokkos::ALL(), Kokkos::ALL()); // auto bb = Kokkos::subview(b, k, Kokkos::ALL(), Kokkos::ALL()); // auto cc = Kokkos::subview(c, k, Kokkos::ALL(), Kokkos::ALL()); // KokkosKernels::Serial:: // Gemm<Trans::NoTranspose,Trans::NoTranspose,AlgoTagType>:: // invoke(1.0, aa, bb, 1.0, cc); // }); // DeviceSpaceType::fence(); // const double t = timer.seconds(); // tmin = std::min(tmin, t); // tavg += (iter >= 0)*t; // } // tavg /= iter_end; // double diff = 0; // for (int i=0;i<cref.dimension(0);++i) // for (int j=0;j<cref.dimension(1);++j) // for (int k=0;k<cref.dimension(2);++k) // diff += std::abs(cref(i,j,k) - c(i,j,k)); // std::cout << std::setw(12) << "Plain" // << " BlkSize = " << std::setw(3) << BlkSize // << " time = " << std::scientific << tmin // << " avg flop/s = " << (flop/tavg) // << " max flop/s = " << (flop/tmin) // << " diff to ref = " << diff // << std::endl; // } // } /// /// Serial SIMD with appropriate data layout /// { Kokkos::View<VectorType***,Kokkos::LayoutRight,HostSpaceType> a("a", N, BlkSize, BlkSize), b("b", N, BlkSize, BlkSize), c("c", N, BlkSize, BlkSize); { const Kokkos::RangePolicy<DeviceSpaceType,ScheduleType> policy(0, N); double tavg = 0, tmin = tmax; for (int iter=iter_begin;iter<iter_end;++iter) { // flush if (!hot) flush.run(); // initialize matrices if (!hot && iter == iter_begin) { Kokkos::deep_copy(a, amat_simd); Kokkos::deep_copy(b, bmat_simd); } Kokkos::deep_copy(c, 0); DeviceSpaceType::fence(); timer.reset(); Kokkos::parallel_for (policy, KOKKOS_LAMBDA(const int k) { auto aa = Kokkos::subview(a, k, Kokkos::ALL(), Kokkos::ALL()); auto bb = Kokkos::subview(b, k, Kokkos::ALL(), Kokkos::ALL()); auto cc = Kokkos::subview(c, k, Kokkos::ALL(), Kokkos::ALL()); KokkosKernels::Serial:: Gemm<Trans::NoTranspose,Trans::NoTranspose,AlgoTagType>:: invoke(1.0, aa, bb, 1.0, cc); }); DeviceSpaceType::fence(); const double t = timer.seconds(); tmin = std::min(tmin, t); tavg += (iter >= 0)*t; } tavg /= iter_end; double diff = 0; for (int i=0;i<cref.dimension(0);++i) for (int j=0;j<cref.dimension(1);++j) for (int k=0;k<cref.dimension(2);++k) diff += std::abs(cref(i,j,k) - c(i/VectorLength,j,k)[i%VectorLength]); std::cout << std::setw(12) << "Serial SIMD" << " BlkSize = " << std::setw(3) << BlkSize << " time = " << std::scientific << tmin << " avg flop/s = " << (flop/tavg) << " max flop/s = " << (flop/tmin) << " diff to ref = " << diff << std::endl; } } // /// // /// Team SIMD with appropriate data layout // /// // if (!std::is_same<AlgoTagType,Algo::Gemm::CompactMKL>::value) { // Kokkos::View<VectorType***,Kokkos::LayoutRight,HostSpaceType> // a("a", N, BlkSize, BlkSize), // b("b", N, BlkSize, BlkSize), // c("c", N, BlkSize, BlkSize); // { // double tavg = 0, tmin = tmax; // typedef Kokkos::TeamPolicy<DeviceSpaceType,ScheduleType> policy_type; // typedef typename policy_type::member_type member_type; // const policy_type policy(N, Kokkos::AUTO, VectorLength); // for (int iter=iter_begin;iter<iter_end;++iter) { // // flush // flush.run(); // // initialize matrices // Kokkos::deep_copy(a, amat_simd); // Kokkos::deep_copy(b, bmat_simd); // Kokkos::deep_copy(c, 0); // DeviceSpaceType::fence(); // timer.reset(); // Kokkos::parallel_for // (policy, // KOKKOS_LAMBDA(const member_type &member) { // const int k = member.league_rank(); // auto aa = Kokkos::subview(a, k, Kokkos::ALL(), Kokkos::ALL()); // auto bb = Kokkos::subview(b, k, Kokkos::ALL(), Kokkos::ALL()); // auto cc = Kokkos::subview(c, k, Kokkos::ALL(), Kokkos::ALL()); // KokkosKernels::Team:: // Gemm<member_type,Trans::NoTranspose,Trans::NoTranspose,AlgoTagType>:: // invoke(member, 1.0, aa, bb, 1.0, cc); // }); // DeviceSpaceType::fence(); // const double t = timer.seconds(); // tmin = std::min(tmin, t); // tavg += (iter >= 0)*t; // } // tavg /= iter_end; // double diff = 0; // for (int i=0;i<cref.dimension(0);++i) // for (int j=0;j<cref.dimension(1);++j) // for (int k=0;k<cref.dimension(2);++k) // diff += std::abs(cref(i,j,k) - c(i/VectorLength,j,k)[i%VectorLength]); // std::cout << std::setw(12) << "Team SIMD" // << " BlkSize = " << std::setw(3) << BlkSize // << " time = " << std::scientific << tmin // << " avg flop/s = " << (flop/tavg) // << " max flop/s = " << (flop/tmin) // << " diff to ref = " << diff // << std::endl << std::endl; // } // } } } } using namespace KokkosKernels; template<typename VectorType, typename AlgoTagType> void run(const int N) { typedef typename VectorType::exec_space ExecSpace; std::cout << "ExecSpace:: "; if (std::is_same<ExecSpace,Kokkos::Serial>::value) std::cout << "Kokkos::Serial " << std::endl; else ExecSpace::print_configuration(std::cout, false); // Test::Gemm< 4, ExecSpace,VectorType,AlgoTagType>(N); // Test::Gemm< 8, ExecSpace,VectorType,AlgoTagType>(N); // Test::Gemm<16, ExecSpace,VectorType,AlgoTagType>(N); // Test::Gemm<20, ExecSpace,VectorType,AlgoTagType>(N); // Test::Gemm<32, ExecSpace,VectorType,AlgoTagType>(N); // Test::Gemm<64, ExecSpace,VectorType,AlgoTagType>(N); Test::Gemm< 3, ExecSpace,VectorType,AlgoTagType>(N); Test::Gemm< 5, ExecSpace,VectorType,AlgoTagType>(N); Test::Gemm<10, ExecSpace,VectorType,AlgoTagType>(N); Test::Gemm<15, ExecSpace,VectorType,AlgoTagType>(N); } int main(int argc, char *argv[]) { Kokkos::initialize(argc, argv); const int ntest = 1; //const int N[6] = { 256, 512, 768, 1024, 1280, 1536 }; int N[1] = { 128*128 }; for (int i=1;i<argc;++i) { const std::string& token = argv[i]; if (token == std::string("-N")) N[0] = std::atoi(argv[++i]); if (token == std::string("-hot-cache")) hot = true; } #if defined(__AVX512F__) constexpr int VectorLength = 8; #elif defined(__AVX2__) || defined(__AVX__) constexpr int VectorLength = 4; #else static_assert(false, "AVX is not supported"); #endif { for (int i=0;i<ntest;++i) { std::cout << " N = " << N[i] << std::endl; // std::cout << "\n Testing SIMD-" << VectorLength << " and Algo::Gemm::Unblocked\n"; // run<VectorTag<SIMD<double>,VectorLength>,Algo::Gemm::Unblocked>(N[i]/VectorLength); // std::cout << "\n Testing AVX-" << VectorLength << " and Algo::Gemm::Unblocked\n"; // run<VectorTag<AVX<double>,VectorLength>,Algo::Gemm::Unblocked>(N[i]/VectorLength); // std::cout << "\n Testing SIMD-" << VectorLength << " and Algo::Gemm::Blocked\n"; // run<VectorTag<SIMD<double>,VectorLength>,Algo::Gemm::Blocked>(N[i]/VectorLength); std::cout << "\n Testing AVX-" << VectorLength << " and Algo::Gemm::Blocked\n"; run<VectorTag<AVX<double>,VectorLength>,Algo::Gemm::Blocked>(N[i]/VectorLength); // #if defined(__KOKKOSKERNELS_INTEL_MKL_COMPACT_BATCHED__) // std::cout << "\n Testing AVX-" << VectorLength << " and Algo::Gemm::CompactMKL\n"; // run<VectorTag<AVX<double>,VectorLength>,Algo::Gemm::CompactMKL>(N[i]/VectorLength); // #endif } } Kokkos::finalize(); return 0; }
34.976366
148
0.476287
crtrott