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 108 | 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 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
e3bb27a4cdd7a4e50c8b9e2c0789a40e4d550080 | 1,538 | cpp | C++ | ScreenBuffer.cpp | TmCrafz/TetrisTerminal | 1d527f068b356aafefeeffd669f61102cd7421c5 | [
"MIT"
] | 1 | 2021-03-16T13:54:52.000Z | 2021-03-16T13:54:52.000Z | ScreenBuffer.cpp | TmCrafz/QuadrisTerminal | 1d527f068b356aafefeeffd669f61102cd7421c5 | [
"MIT"
] | null | null | null | ScreenBuffer.cpp | TmCrafz/QuadrisTerminal | 1d527f068b356aafefeeffd669f61102cd7421c5 | [
"MIT"
] | null | null | null | #include "ScreenBuffer.h"
using namespace std;
ScreenBuffer::ScreenBuffer(const int screenWidth, const int screenHeight):
m_BufferHeight(screenHeight),
m_BufferWidth(screenWidth),
// Allocate the memory for the 2d array
m_screenBuffer(new char *[m_BufferHeight])
{
for (int i = 0; i != m_BufferHeight; i++)
{
m_screenBuffer[i] = new char[m_BufferWidth];
}
}
ScreenBuffer::~ScreenBuffer()
{
// Free the memory of the screenBuffer
for (int i = 0; i != m_BufferHeight; i++)
{
delete[] m_screenBuffer[i];
}
delete[] m_screenBuffer;
}
int ScreenBuffer::getHeight() const
{
return m_BufferHeight;
}
int ScreenBuffer::getWidth() const
{
return m_BufferWidth;
}
void ScreenBuffer::add(const int X, const int Y, const char C)
{
if (isInBufferArea(X, Y))
{
m_screenBuffer[Y][X] = C;
}
}
void ScreenBuffer::add(const int StartX, const int StartY, const string Text)
{
for (size_t x = StartX; x != StartX + Text.length(); x++)
{
if (isInBufferArea(x, StartY))
{
m_screenBuffer[StartY][x] = Text[x - StartX];
}
}
}
void ScreenBuffer::clear()
{
for (int y = 0; y != m_BufferHeight; y++)
{
for (int x = 0; x != m_BufferWidth; x++)
{
m_screenBuffer[y][x] = ' ';
}
}
}
void ScreenBuffer::display() const
{
for (int y = 0; y != m_BufferHeight; y++)
{
for (int x = 0; x != m_BufferWidth; x++)
{
cout << m_screenBuffer[y][x];
}
cout << endl;
}
}
bool ScreenBuffer::isInBufferArea(const int X, const int Y) const
{
return (X >= 0 && X < m_BufferWidth && Y >= 0 && Y < m_BufferHeight);
}
| 18.53012 | 77 | 0.650845 | TmCrafz |
e3bcf4734063d93fd38fa42a924716d708151ee6 | 1,037 | cpp | C++ | src/test/02_memory/main.cpp | Ubpa/USTL | 89acf7dbcb747d014516e7c67d632bbece22a184 | [
"MIT"
] | 1 | 2020-10-15T06:58:25.000Z | 2020-10-15T06:58:25.000Z | src/test/02_memory/main.cpp | Ubpa/USTL | 89acf7dbcb747d014516e7c67d632bbece22a184 | [
"MIT"
] | null | null | null | src/test/02_memory/main.cpp | Ubpa/USTL | 89acf7dbcb747d014516e7c67d632bbece22a184 | [
"MIT"
] | 1 | 2020-10-15T06:58:27.000Z | 2020-10-15T06:58:27.000Z | #include <USTL/memory.h>
#include <iostream>
using namespace Ubpa::USTL;
using namespace std;
#include <memory>
#include <map>
#include <unordered_map>
class A {
public:
virtual ~A() = default;
float x, y;
};
class B : public A {
public:
float z, w;
};
int main() {
{ // shared
shared_object<A> so0;
shared_object<A> so1{ nullptr };
const shared_object<A> so2{ new A };
auto so3 = make_shared_object<B>();
shared_object<A[]> so4{ new A[5] };
cout << so4[3].x << endl;
std::unordered_map<shared_object<int>, size_t> m1; // hash
std::map<shared_object<int>, size_t> m2; // <
std::map<shared_object<int>, size_t, std::owner_less<shared_object<int>>> m3; // owner_before
}
{ // unique
unique_object<int[]> uo0;
unique_object<int[]> uo1{ nullptr };
unique_object<int[]> uo2{ new int[5] };
cout << uo2[3] << endl;
auto uo3 = make_unique_object<B>();
unique_object<A[]> uo4{ new A[5] };
std::unordered_map<unique_object<int>, size_t> m1; // hash
std::map<unique_object<int>, size_t> m2; // <
}
}
| 23.044444 | 95 | 0.648023 | Ubpa |
e3bdf25943a1aa35fc3e64d3c83ed601106d89b8 | 4,107 | cc | C++ | gitiles_test.cc | dancerj/gitlstreefs | f5eca366643a47814d3a12bc458e64a6a093e315 | [
"BSD-3-Clause"
] | 2 | 2015-10-05T10:30:14.000Z | 2018-09-10T05:35:04.000Z | gitiles_test.cc | dancerj/gitlstreefs | f5eca366643a47814d3a12bc458e64a6a093e315 | [
"BSD-3-Clause"
] | 1 | 2015-10-04T16:58:10.000Z | 2015-10-18T08:53:04.000Z | gitiles_test.cc | dancerj/gitlstreefs | f5eca366643a47814d3a12bc458e64a6a093e315 | [
"BSD-3-Clause"
] | 1 | 2015-09-28T04:25:20.000Z | 2015-09-28T04:25:20.000Z | #include "base64decode.h"
#include "jsonparser.h"
#include "strutil.h"
#include <assert.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <functional>
#include <iostream>
#include <memory>
#include <string>
// This returns base64 data in text format.
// https://chromium.googlesource.com/chromiumos/third_party/kernel/+/chromeos-4.4/.gitignore?format=TEXT
std::string FetchBlob(const std::string& blob_text_string) {
return base64decode(blob_text_string);
}
void FetchBlobTest() {
std::string gitiles_blob(
ReadFromFileOrDie(AT_FDCWD, "testdata/gitiles-blob.txt"));
std::string fetched = FetchBlob(gitiles_blob);
assert(fetched.size() == 1325);
assert(fetched.find("NOTE!") != std::string::npos);
}
// Parses tree object from json, returns true on success.
//
// host_prject_branch_url needs to not end with a /. Should contain
// http://HOST/PROJECT/+/BRANCH that is used for the original tree
// request which should have been
// http://HOST/PROJECT/+/BRANCH/?format=JSON&recursive=TRUE&long=1
bool ParseTrees(
const std::string host_project_branch_url, const std::string& trees_string,
std::function<void(const std::string& path, int mode,
const std::string& sha, const int size,
const std::string& target, const std::string& url)>
file_handler) {
// I assume the URL doesn't end at /.
assert(host_project_branch_url[host_project_branch_url.size() - 1] != '/');
// Try parsing gitiles json output, which is similar to github api
// v3 trees output but not quite.
std::unique_ptr<jjson::Value> value = jjson::Parse(trees_string);
for (const auto& file : (*value)["entries"].get_array()) {
// "mode": 33188, // an actual number.
// "type": "blob",
// "id": "0eca3e92941236b77ad23a02dc0c000cd0da7a18",
// "name": ".gitignore",
// "size": 1325
// size can be none if mode is 40960, in which case 'target' contains the
// symlink target.
mode_t mode = file->get("mode").get_int();
int size = 0;
std::string target{};
if (S_ISLNK(mode)) {
target = file->get("target").get_string();
} else {
size = file->get("size").get_int();
}
/*
* Gitiles API seems to require a commit revision+path for obtaining a blob.
* according to https://github.com/google/gitiles/issues/51
* Make sure we have one.
*/
std::string name = file->get("name").get_string();
std::string url = host_project_branch_url + "/" + name + "?format=TEXT";
assert(file != nullptr);
file_handler(name, mode, std::string(file->get("id").get_string()), size,
target, url);
}
return true;
}
void GitilesParserTest() {
/*
Things I tried:
https://chromium.googlesource.com/chromiumos/third_party/kernel/+/chromeos-4.4?format=JSON
-- not useful, gives information about the diff.
https://chromium.googlesource.com/chromiumos/third_party/kernel/+/chromeos-4.4/?format=JSON
-- gives a single tree.
https://chromium.googlesource.com/chromiumos/third_party/kernel/+/chromeos-4.4/?format=JSON&recursive=TRUE&long=1
-- Recursive tree that contains size also:
Probably useful to read through:
https://github.com/google/gitiles/blob/master/java/com/google/gitiles/GitilesFilter.java
https://github.com/google/gitiles/blob/master/java/com/google/gitiles/TreeJsonData.java
*/
std::string gitiles_trees(
ReadFromFileOrDie(AT_FDCWD, "testdata/gitiles-tree-recursive.json"));
ParseTrees(
"https://chromium.googlesource.com/chromiumos/third_party/kernel/+/"
"chromeos-4.4",
gitiles_trees.substr(5),
[](const std::string& path, int mode, const std::string& sha, int size,
const std::string& target, const std::string& url) {
std::cout << "gitiles:" << path << " " << std::oct << mode << " " << sha
<< " " << std::dec << size << (target.empty() ? "" : "->")
<< " " << target << " " << url << std::endl;
});
}
int main(int argc, char** argv) {
GitilesParserTest();
FetchBlobTest();
return 0;
}
| 35.405172 | 117 | 0.654005 | dancerj |
e3be0f5447d30f9fa2dd4edb10f1d1152c0dcb77 | 754 | cpp | C++ | geeksforgeeks/Subarray with given sum.cpp | him1411/algorithmic-coding-and-data-structures | 685aa95539692daca68ce79c20467c335aa9bb7f | [
"MIT"
] | null | null | null | geeksforgeeks/Subarray with given sum.cpp | him1411/algorithmic-coding-and-data-structures | 685aa95539692daca68ce79c20467c335aa9bb7f | [
"MIT"
] | null | null | null | geeksforgeeks/Subarray with given sum.cpp | him1411/algorithmic-coding-and-data-structures | 685aa95539692daca68ce79c20467c335aa9bb7f | [
"MIT"
] | 2 | 2018-10-04T19:01:52.000Z | 2018-10-05T08:49:57.000Z | using namespace std;
int main()
{
int t;
cin>>t;
while(t--)
{
int n,sum=0;
cin>>n>>sum;
vector<int> v(n,0);
for(int i=0;i<n;i++)
{
cin>>v[i];
}
int cursum=v[0],start=0;
int flag =1;
for(int i =1;i<=n;i++)
{
while(cursum > sum && start <i-1)
{
cursum -= v[start];
start++;
}
if(cursum == sum)
{
cout<<start+1<<" "<<i<<endl;
flag =0;
break;
}
if(i<n)
cursum += v[i];
}
if(flag)
cout<<"-1"<<endl;
}
return 0;
} | 19.333333 | 45 | 0.298408 | him1411 |
e3bf9705ca79ecc27135a90b6f6aa53e5bd1ed6a | 10,125 | cpp | C++ | Cbc/Cbc/examples/sample5.cpp | fadi-alkhoury/coin-or-cbc-with-cmake | b4a216118d8e773b694b44c5f27cd75a251cc2cb | [
"MIT"
] | null | null | null | Cbc/Cbc/examples/sample5.cpp | fadi-alkhoury/coin-or-cbc-with-cmake | b4a216118d8e773b694b44c5f27cd75a251cc2cb | [
"MIT"
] | null | null | null | Cbc/Cbc/examples/sample5.cpp | fadi-alkhoury/coin-or-cbc-with-cmake | b4a216118d8e773b694b44c5f27cd75a251cc2cb | [
"MIT"
] | null | null | null | // $Id: sample5.cpp 2469 2019-01-06 23:17:46Z unxusr $
// Copyright (C) 2002, International Business Machines
// Corporation and others. All Rights Reserved.
// This code is licensed under the terms of the Eclipse Public License (EPL).
#include "CbcConfig.h"
#include "CoinPragma.hpp"
#include <cassert>
#include <iomanip>
// For Branch and bound
#include "OsiSolverInterface.hpp"
#include "CbcModel.hpp"
#include "CbcBranchUser.hpp"
#include "CbcCompareUser.hpp"
#include "CbcCutGenerator.hpp"
#include "CbcHeuristicLocal.hpp"
#include "OsiClpSolverInterface.hpp"
// Cuts
#include "CglGomory.hpp"
#include "CglProbing.hpp"
#include "CglKnapsackCover.hpp"
#include "CglOddHole.hpp"
#include "CglClique.hpp"
#include "CglFlowCover.hpp"
#include "CglMixedIntegerRounding.hpp"
// Heuristics
#include "CbcHeuristic.hpp"
// Methods of building
#include "CoinBuild.hpp"
#include "CoinModel.hpp"
#include "CoinTime.hpp"
/************************************************************************
This main program creates an integer model and then solves it
It then sets up some Cgl cut generators and calls branch and cut.
Branching is simple binary branching on integer variables.
Node selection is depth first until first solution is found and then
based on objective and number of unsatisfied integer variables.
In this example the functionality is the same as default but it is
a user comparison function.
Variable branching selection is on maximum minimum-of-up-down change
after strong branching on 5 variables closest to 0.5.
A simple rounding heuristic is used.
************************************************************************/
int main(int argc, const char *argv[])
{
/* Define your favorite OsiSolver.
CbcModel clones the solver so use solver1 up to the time you pass it
to CbcModel then use a pointer to cloned solver (model.solver())
*/
OsiClpSolverInterface solver1;
/* From now on we can build model in a solver independent way.
You can add rows one at a time but for large problems this is slow so
this example uses CoinBuild or CoinModel
*/
OsiSolverInterface *solver = &solver1;
// Data (is exmip1.mps in Mps/Sample
// Objective
double objValue[] = { 1.0, 2.0, 0.0, 0.0, 0.0, 0.0, 0.0, -1.0 };
// Lower bounds for columns
double columnLower[] = { 2.5, 0.0, 0.0, 0.0, 0.5, 0.0, 0.0, 0.0 };
// Upper bounds for columns
double columnUpper[] = { COIN_DBL_MAX, 4.1, 1.0, 1.0, 4.0,
COIN_DBL_MAX, COIN_DBL_MAX, 4.3 };
// Lower bounds for row activities
double rowLower[] = { 2.5, -COIN_DBL_MAX, -COIN_DBL_MAX, 1.8, 3.0 };
// Upper bounds for row activities
double rowUpper[] = { COIN_DBL_MAX, 2.1, 4.0, 5.0, 15.0 };
// Matrix stored packed
int column[] = { 0, 1, 3, 4, 7,
1, 2,
2, 5,
3, 6,
4, 7 };
double element[] = { 3.0, 1.0, -2.0, -1.0, -1.0,
2.0, 1.1,
1.0, 1.0,
2.8, -1.2,
1.0, 1.9 };
int starts[] = { 0, 5, 7, 9, 11, 13 };
// Integer variables (note upper bound already 1.0)
int whichInt[] = { 2, 3 };
int numberRows = (int)(sizeof(rowLower) / sizeof(double));
int numberColumns = (int)(sizeof(columnLower) / sizeof(double));
#define BUILD 2
#if BUILD == 1
// Using CoinBuild
// First do columns (objective and bounds)
int i;
// We are not adding elements
for (i = 0; i < numberColumns; i++) {
solver->addCol(0, NULL, NULL, columnLower[i], columnUpper[i],
objValue[i]);
}
// mark as integer
for (i = 0; i < (int)(sizeof(whichInt) / sizeof(int)); i++)
solver->setInteger(whichInt[i]);
// Now build rows
CoinBuild build;
for (i = 0; i < numberRows; i++) {
int startRow = starts[i];
int numberInRow = starts[i + 1] - starts[i];
build.addRow(numberInRow, column + startRow, element + startRow,
rowLower[i], rowUpper[i]);
}
// add rows into solver
solver->addRows(build);
#else
/* using CoinModel - more flexible but still beta.
Can do exactly same way but can mix and match much more.
Also all operations are on building object
*/
CoinModel build;
// First do columns (objective and bounds)
int i;
for (i = 0; i < numberColumns; i++) {
build.setColumnBounds(i, columnLower[i], columnUpper[i]);
build.setObjective(i, objValue[i]);
}
// mark as integer
for (i = 0; i < (int)(sizeof(whichInt) / sizeof(int)); i++)
build.setInteger(whichInt[i]);
// Now build rows
for (i = 0; i < numberRows; i++) {
int startRow = starts[i];
int numberInRow = starts[i + 1] - starts[i];
build.addRow(numberInRow, column + startRow, element + startRow,
rowLower[i], rowUpper[i]);
}
// add rows into solver
solver->loadFromCoinModel(build);
#endif
// Pass to solver
CbcModel model(*solver);
model.solver()->setHintParam(OsiDoReducePrint, true, OsiHintTry);
// Set up some cut generators and defaults
// Probing first as gets tight bounds on continuous
CglProbing generator1;
generator1.setUsingObjective(true);
generator1.setMaxPass(3);
generator1.setMaxProbe(100);
generator1.setMaxLook(50);
generator1.setRowCuts(3);
// generator1.snapshot(*model.solver());
//generator1.createCliques(*model.solver(),2,1000,true);
//generator1.setMode(0);
CglGomory generator2;
// try larger limit
generator2.setLimit(300);
CglKnapsackCover generator3;
CglOddHole generator4;
generator4.setMinimumViolation(0.005);
generator4.setMinimumViolationPer(0.00002);
// try larger limit
generator4.setMaximumEntries(200);
CglClique generator5;
generator5.setStarCliqueReport(false);
generator5.setRowCliqueReport(false);
CglMixedIntegerRounding mixedGen;
CglFlowCover flowGen;
// Add in generators
model.addCutGenerator(&generator1, -1, "Probing");
model.addCutGenerator(&generator2, -1, "Gomory");
model.addCutGenerator(&generator3, -1, "Knapsack");
model.addCutGenerator(&generator4, -1, "OddHole");
model.addCutGenerator(&generator5, -1, "Clique");
model.addCutGenerator(&flowGen, -1, "FlowCover");
model.addCutGenerator(&mixedGen, -1, "MixedIntegerRounding");
OsiClpSolverInterface *osiclp = dynamic_cast< OsiClpSolverInterface * >(model.solver());
// go faster stripes
if (osiclp->getNumRows() < 300 && osiclp->getNumCols() < 500) {
osiclp->setupForRepeatedUse(2, 0);
printf("trying slightly less reliable but faster version (? Gomory cuts okay?)\n");
printf("may not be safe if doing cuts in tree which need accuracy (level 2 anyway)\n");
}
// Allow rounding heuristic
CbcRounding heuristic1(model);
model.addHeuristic(&heuristic1);
// And local search when new solution found
CbcHeuristicLocal heuristic2(model);
model.addHeuristic(&heuristic2);
// Redundant definition of default branching (as Default == User)
CbcBranchUserDecision branch;
model.setBranchingMethod(&branch);
// Definition of node choice
CbcCompareUser compare;
model.setNodeComparison(compare);
// Do initial solve to continuous
model.initialSolve();
// Could tune more
model.setMinimumDrop(CoinMin(1.0,
fabs(model.getMinimizationObjValue()) * 1.0e-3 + 1.0e-4));
if (model.getNumCols() < 500)
model.setMaximumCutPassesAtRoot(-100); // always do 100 if possible
else if (model.getNumCols() < 5000)
model.setMaximumCutPassesAtRoot(100); // use minimum drop
else
model.setMaximumCutPassesAtRoot(20);
//model.setMaximumCutPasses(5);
// Switch off strong branching if wanted
// model.setNumberStrong(0);
// Do more strong branching if small
if (model.getNumCols() < 5000)
model.setNumberStrong(10);
model.solver()->setIntParam(OsiMaxNumIterationHotStart, 100);
// If time is given then stop after that number of minutes
if (argc > 2) {
int minutes = atoi(argv[2]);
std::cout << "Stopping after " << minutes << " minutes" << std::endl;
assert(minutes >= 0);
model.setDblParam(CbcModel::CbcMaximumSeconds, 60.0 * minutes);
}
// Switch off most output
if (model.getNumCols() < 3000) {
model.messageHandler()->setLogLevel(1);
//model.solver()->messageHandler()->setLogLevel(0);
} else {
model.messageHandler()->setLogLevel(2);
model.solver()->messageHandler()->setLogLevel(1);
}
double time1 = CoinCpuTime();
// Do complete search
model.branchAndBound();
std::cout << " Branch and cut took " << CoinCpuTime() - time1 << " seconds, "
<< model.getNodeCount() << " nodes with objective "
<< model.getObjValue()
<< (!model.status() ? " Finished" : " Not finished")
<< std::endl;
// Print more statistics
std::cout << "Cuts at root node changed objective from " << model.getContinuousObjective()
<< " to " << model.rootObjectiveAfterCuts() << std::endl;
int numberGenerators = model.numberCutGenerators();
for (int iGenerator = 0; iGenerator < numberGenerators; iGenerator++) {
CbcCutGenerator *generator = model.cutGenerator(iGenerator);
std::cout << generator->cutGeneratorName() << " was tried "
<< generator->numberTimesEntered() << " times and created "
<< generator->numberCutsInTotal() << " cuts of which "
<< generator->numberCutsActive() << " were active after adding rounds of cuts"
<< std::endl;
}
// Print solution if any - we can't get names from Osi!
if (model.getMinimizationObjValue() < 1.0e50) {
int numberColumns = model.solver()->getNumCols();
const double *solution = model.solver()->getColSolution();
int iColumn;
std::cout << std::setiosflags(std::ios::fixed | std::ios::showpoint) << std::setw(14);
std::cout << "--------------------------------------" << std::endl;
for (iColumn = 0; iColumn < numberColumns; iColumn++) {
double value = solution[iColumn];
if (fabs(value) > 1.0e-7 && model.solver()->isInteger(iColumn))
std::cout << std::setw(6) << iColumn << " " << value << std::endl;
}
std::cout << "--------------------------------------" << std::endl;
std::cout << std::resetiosflags(std::ios::fixed | std::ios::showpoint | std::ios::scientific);
}
return 0;
}
| 32.451923 | 98 | 0.660346 | fadi-alkhoury |
e3c1816d91d7faa2bcf93f381ed482e9d6bc7388 | 15,427 | hpp | C++ | Siv3D/include/Siv3D/Image.hpp | azaika/OpenSiv3D | 2e8258ea15741b7dafa6637b50b43637f7b9923a | [
"MIT"
] | null | null | null | Siv3D/include/Siv3D/Image.hpp | azaika/OpenSiv3D | 2e8258ea15741b7dafa6637b50b43637f7b9923a | [
"MIT"
] | null | null | null | Siv3D/include/Siv3D/Image.hpp | azaika/OpenSiv3D | 2e8258ea15741b7dafa6637b50b43637f7b9923a | [
"MIT"
] | 1 | 2019-10-06T17:09:26.000Z | 2019-10-06T17:09:26.000Z | //-----------------------------------------------
//
// This file is part of the Siv3D Engine.
//
// Copyright (c) 2008-2018 Ryo Suzuki
// Copyright (c) 2016-2018 OpenSiv3D Project
//
// Licensed under the MIT License.
//
//-----------------------------------------------
# pragma once
# include <memory.h>
# include "Fwd.hpp"
# include "Array.hpp"
# include "Color.hpp"
# include "NamedParameter.hpp"
# include "PointVector.hpp"
# include "Grid.hpp"
# include "ImageFormat.hpp"
namespace s3d
{
/// <summary>
/// 画像
/// </summary>
/// <remarks>
/// メモリ上に確保される画像データです。
/// ピクセル単位のアクセスや、変形、エフェクト処理を適用できます。
/// イメージを描画する場合は Texture に変換する必要があります。
/// </remarks>
class Image
{
private:
Array<Color> m_data;
uint32 m_width = 0;
uint32 m_height = 0;
static Image Generate(const size_t width, const size_t height, std::function<Color(void)> generator);
template <class Fty>
static Image Generate(const size_t width, const size_t height, Fty generator)
{
Image new_image(width, height);
if (!new_image.isEmpty())
{
Color* pDst = new_image[0];
for (uint32 y = 0; y < height; ++y)
{
for (uint32 x = 0; x < width; ++x)
{
(*pDst++) = generator({ x, y });
}
}
}
return new_image;
}
static Image Generate0_1(const size_t width, const size_t height, std::function<Color(Vec2)> generator);
static constexpr int32 Mod(int32 x, int32 y) noexcept
{
return x % y + ((x < 0) ? y : 0);
}
public:
/// <summary>
/// 画像の最大サイズ
/// </summary>
static constexpr int32 MaxWidth = 8192;
static constexpr int32 MaxHeight = 8192;
using iterator = Array<Color>::iterator;
using const_iterator = Array<Color>::const_iterator;
using reverse_iterator = Array<Color>::reverse_iterator;
using const_reverse_iterator = Array<Color>::const_reverse_iterator;
/// <summary>
/// デフォルトコンストラクタ
/// </summary>
Image() = default;
/// <summary>
/// 画像を別の画像からコピーして作成します。
/// </summary>
/// <param name="image">
/// コピーする画像
/// </param>
Image(const Image& image) = default;
/// <summary>
/// 画像を別の画像からムーブして作成します。
/// </summary>
/// <param name="image">
/// ムーブする画像
/// </param>
Image(Image&& image) noexcept;
/// <summary>
/// 指定したサイズの画像を作成します。
/// </summary>
/// <param name="size">
/// 画像のサイズ(ピクセル)
/// </param>
explicit Image(const Size& size)
: Image(size.x, size.y) {}
/// <summary>
/// 指定した色、サイズで塗りつぶされた画像を作成します。
/// </summary>
/// <param name="size">
/// 画像のサイズ(ピクセル)
/// </param>
/// <param name="color">
/// 塗りつぶしの色
/// </param>
Image(const Size& size, const Color& color)
: Image(size.x, size.y, color) {}
Image(const Size& size, Arg::generator_<std::function<Color(void)>> generator)
: Image(size.x, size.y, generator) {}
Image(const Size& size, Arg::generator_<std::function<Color(Point)>> generator)
: Image(size.x, size.y, generator) {}
Image(const Size& size, Arg::generator_<std::function<Color(Vec2)>> generator)
: Image(size.x, size.y, generator) {}
Image(const Size& size, Arg::generator0_1_<std::function<Color(Vec2)>> generator)
: Image(size.x, size.y, generator) {}
/// <summary>
/// 指定したサイズの画像を作成します。
/// </summary>
/// <param name="width">
/// 画像の幅(ピクセル)
/// </param>
/// <param name="height">
/// 画像の高さ(ピクセル)
/// </param>
Image(size_t width, size_t height);
Image(size_t width, size_t height, Arg::generator_<std::function<Color(void)>> generator)
: Image(Generate(width, height, *generator)) {}
Image(size_t width, size_t height, Arg::generator_<std::function<Color(Point)>> generator)
: Image(Generate(width, height, *generator)) {}
Image(size_t width, size_t height, Arg::generator_<std::function<Color(Vec2)>> generator)
: Image(Generate(width, height, *generator)) {}
Image(size_t width, size_t height, Arg::generator0_1_<std::function<Color(Vec2)>> generator)
: Image(Generate0_1(width, height, *generator)) {}
/// <summary>
/// 指定した色、サイズで塗りつぶされた画像を作成します。
/// </summary>
/// <param name="width">
/// 画像の幅(ピクセル)
/// </param>
/// <param name="height">
/// 画像の高さ(ピクセル)
/// </param>
/// <param name="color">
/// 塗りつぶしの色
/// </param>
Image(size_t width, size_t height, const Color& color);
/// <summary>
/// 画像ファイルから画像を作成します。
/// </summary>
/// <param name="path">
/// 画像ファイルのパス
/// </param>
explicit Image(const FilePath& path);
/// <summary>
/// Reader から画像を作成します。
/// </summary>
/// <param name="reader">
/// Reader
/// </param>
/// <param name="format">
/// 画像のフォーマット
/// </param>
explicit Image(IReader&& reader, ImageFormat format = ImageFormat::Unspecified);
/// <summary>
/// 2 つの画像ファイルから画像を作成します。
/// </summary>
/// <param name="rgb">
/// RGB を読み込む画像ファイルのパス
/// </param>
/// <param name="alpha">
/// アルファ値を読み込む画像ファイルのパス
/// </param>
Image(const FilePath& rgb, const FilePath& alpha);
/// <summary>
/// 画像ファイルからアルファ値を作成し、画像を作成します。
/// </summary>
/// <param name="rgb">
/// RGB 成分の色
/// </param>
/// <param name="alpha">
/// アルファ値を読み込む画像ファイルのパス
/// </param>
/// <remarks>
/// alpha の画像の R 成分を、テクスチャのアルファ値に設定します。
/// 画像ファイルの読み込みに失敗した場合、空のテクスチャを作成します。
/// </remarks>
Image(const Color& rgb, const FilePath& alpha);
explicit Image(const Emoji& emoji);
explicit Image(const Icon& icon);
explicit Image(const Grid<Color>& grid);
explicit Image(const Grid<ColorF>& grid);
template <class Type, class Fty>
explicit Image(const Grid<Type>& grid, Fty converter)
: Image(grid.width(), grid.height())
{
if (m_data.empty())
{
return;
}
const Type* pSrc = grid.data();
const Type* const pSrcEnd = pSrc + grid.size_elements();
Color* pDst = &m_data[0];
while (pSrc != pSrcEnd)
{
*pDst++ = converter(*pSrc++);
}
}
/// <summary>
/// 新しい画像を代入します。
/// </summary>
/// <param name="str">
/// 新しい画像
/// </param>
/// <returns>
/// *this
/// </returns>
Image& operator =(const Image& image) = default;
/// <summary>
/// 新しい画像を代入します。
/// </summary>
/// <param name="str">
/// 新しい画像
/// </param>
/// <returns>
/// *this
/// </returns>
Image& operator =(Image&& image);
Image& assign(const Image& image)
{
return operator =(image);
}
Image& assign(Image&& image)
{
return operator =(std::move(image));
}
/// <summary>
/// 画像の幅(ピクセル)
/// </summary>
int32 width() const noexcept
{
return m_width;
}
/// <summary>
/// 画像の高さ(ピクセル)
/// </summary>
int32 height() const noexcept
{
return m_height;
}
/// <summary>
/// 画像の幅と高さ(ピクセル)
/// </summary>
Size size() const noexcept
{
return{ m_width, m_height };
}
/// <summary>
/// 画像の各行のデータサイズ
/// </summary>
uint32 stride() const noexcept
{
return m_width * sizeof(Color);
}
/// <summary>
/// 画像のピクセル数
/// </summary>
uint32 num_pixels() const noexcept
{
return m_width * m_height;
}
/// <summary>
/// 画像のデータサイズ
/// </summary>
uint32 size_bytes() const
{
return stride() * m_height;
}
/// <summary>
/// 画像が空かどうかを示します。
/// </summary>
bool isEmpty() const
{
return m_data.empty();
}
/// <summary>
/// 画像が空ではないかを返します。
/// </summary>
/// <returns>
/// 画像が空ではない場合 true, それ以外の場合は false
/// </returns>
explicit operator bool() const
{
return !isEmpty();
}
/// <summary>
/// 画像の不要なメモリ消費を削除します。
/// </summary>
/// <returns>
/// なし
/// </returns>
void shrink_to_fit()
{
m_data.shrink_to_fit();
}
/// <summary>
/// 画像を消去し、空の画像にします。
/// </summary>
/// <remarks>
/// メモリを解放したい場合は shrink_to_fit() を呼びます。
/// </remarks>
/// <returns>
/// なし
/// </returns>
void clear()
{
m_data.clear();
m_width = m_height = 0;
}
void release()
{
clear();
shrink_to_fit();
}
/// <summary>
/// 画像を別の画像と交換します。
/// </summary>
/// <param name="image">
/// 交換する画像
/// </param>
/// <returns>
/// なし
/// </returns>
void swap(Image& image) noexcept
{
m_data.swap(image.m_data);
std::swap(m_width, image.m_width);
std::swap(m_height, image.m_height);
}
/// <summary>
/// 画像をコピーした新しい画像を返します。
/// </summary>
/// <returns>
/// コピーした新しい画像
/// </returns>
Image cloned() const
{
return *this;
}
/// <summary>
/// 指定した行の先頭ポインタを返します。
/// </summary>
/// <param name="y">
/// 位置(行)
/// </param>
/// <returns>
/// image[y][x] で指定したピクセルにアクセスします。
/// </returns>
/// <returns>
/// 指定した行の先頭ポインタ
/// </returns>
Color* operator[](size_t y)
{
return &m_data[m_width * y];
}
Color& operator[](const Point& pos)
{
return m_data[m_width * pos.y + pos.x];
}
/// <summary>
/// 指定した行の先頭ポインタを返します。
/// </summary>
/// <param name="y">
/// 位置(行)
/// </param>
/// <returns>
/// image[y][x] で指定したピクセルにアクセスします。
/// </returns>
/// <returns>
/// 指定した行の先頭ポインタ
/// </returns>
const Color* operator[](size_t y) const
{
return &m_data[m_width * y];
}
const Color& operator[](const Point& pos) const
{
return m_data[m_width * pos.y + pos.x];
}
/// <summary>
/// 画像データの先頭のポインタを返します。
/// </summary>
/// <returns>
/// 画像データの先頭へのポインタ
/// </returns>
Color* data()
{
return &m_data[0];
}
/// <summary>
/// 画像データの先頭のポインタを返します。
/// </summary>
/// <returns>
/// 画像データの先頭へのポインタ
/// </returns>
const Color* data() const
{
return &m_data[0];
}
/// <summary>
/// 画像データの先頭のポインタを返します。
/// </summary>
/// <returns>
/// 画像データの先頭へのポインタ
/// </returns>
uint8* dataAsUint8()
{
return static_cast<uint8*>(static_cast<void*>(&m_data[0]));
}
/// <summary>
/// 画像データの先頭のポインタを返します。
/// </summary>
/// <returns>
/// 画像データの先頭へのポインタ
/// </returns>
const uint8* dataAsUint8() const
{
return static_cast<const uint8*>(static_cast<const void*>(&m_data[0]));
}
/// <summary>
/// 画像の先頭位置のイテレータを取得します。
/// </summary>
/// <returns>
/// 画像の先頭位置のイテレータ
/// </returns>
iterator begin() noexcept { return m_data.begin(); }
/// <summary>
/// 画像の先頭位置のイテレータを取得します。
/// </summary>
/// <returns>
/// 画像の先頭位置のイテレータ
/// </returns>
const_iterator begin() const noexcept { return m_data.begin(); }
/// <summary>
/// 画像の先頭位置のイテレータを取得します。
/// </summary>
/// <returns>
/// 画像の先頭位置のイテレータ
/// </returns>
const_iterator cbegin() const noexcept { return m_data.cbegin(); }
/// <summary>
/// 画像の終了位置のイテレータを取得します。
/// </summary>
/// <returns>
/// 画像の終了位置のイテレータ
/// </returns>
iterator end() noexcept { return m_data.end(); }
/// <summary>
/// 画像の終了位置のイテレータを取得します。
/// </summary>
/// <returns>
/// 画像の終了位置のイテレータ
/// </returns>
const_iterator end() const noexcept { return m_data.end(); }
/// <summary>
/// 画像の終了位置のイテレータを取得します。
/// </summary>
/// <returns>
/// 画像の終了位置のイテレータ
/// </returns>
const_iterator cend() const noexcept { return m_data.cend(); }
/// <summary>
/// 画像の末尾へのリバースイテレータを取得します。
/// </summary>
/// <returns>
/// 画像の末尾へのリバースイテレータ
/// </returns>
reverse_iterator rbegin() noexcept { return m_data.rbegin(); }
/// <summary>
/// 画像の末尾へのリバースイテレータを取得します。
/// </summary>
/// <returns>
/// 画像の末尾へのリバースイテレータ
/// </returns>
const_reverse_iterator rbegin() const noexcept { return m_data.rbegin(); }
/// <summary>
/// 画像の末尾へのリバースイテレータを取得します。
/// </summary>
/// <returns>
/// 画像の末尾へのリバースイテレータ
/// </returns>
const_reverse_iterator crbegin() const noexcept { return m_data.crbegin(); }
/// <summary>
/// 画像の先頭の前へのリバースイテレータを取得します。
/// </summary>
/// <returns>
/// 画像の先頭の前へのリバースイテレータ
/// </returns>
reverse_iterator rend() noexcept { return m_data.rend(); }
/// <summary>
/// 画像の先頭の前へのリバースイテレータを取得します。
/// </summary>
/// <returns>
/// 画像の先頭の前へのリバースイテレータ
/// </returns>
const_reverse_iterator rend() const noexcept { return m_data.rend(); }
/// <summary>
/// 画像の先頭の前へのリバースイテレータを取得します。
/// </summary>
/// <returns>
/// 画像の先頭の前へのリバースイテレータ
/// </returns>
const_reverse_iterator crend() const noexcept { return m_data.crend(); }
/// <summary>
/// 画像を指定した色で塗りつぶします。
/// </summary>
/// <param name="color">
/// 塗りつぶしの色
/// </param>
/// <returns>
/// なし
/// </returns>
void fill(const Color& color)
{
for (auto& pixel : m_data)
{
pixel = color;
}
}
/// <summary>
/// 画像のサイズを変更します。
/// </summary>
/// <param name="width">
/// 新しい幅(ピクセル)
/// </param>
/// <param name="height">
/// 新しい高さ(ピクセル)
/// </param>
/// <remarks>
/// サイズの変更が必要ないときは何もしません。
/// サイズが変更された場合、すべての要素の値が不定になります。
/// 画像を拡大縮小する場合は scale() を使ってください。
/// </remarks>
/// <returns>
/// なし
/// </returns>
void resize(size_t width, size_t height);
/// <summary>
/// 画像のサイズを変更します。
/// </summary>
/// <param name="size">
/// 新しいサイズ(ピクセル)
/// </param>
/// <remarks>
/// サイズの変更が必要ないときは何もしません。
/// サイズが変更された場合、すべての要素の値が不定になります。
/// 画像を拡大縮小する場合は scale() を使ってください。
/// </remarks>
/// <returns>
/// なし
/// </returns>
void resize(const Size& size)
{
resize(size.x, size.y);
}
/// <summary>
/// 画像のサイズを変更します。
/// </summary>
/// <param name="width">
/// 新しい幅(ピクセル)
/// </param>
/// <param name="height">
/// 新しい高さ(ピクセル)
/// </param>
/// <param name="fillColor">
/// 塗りつぶしの色
/// </param>
/// <remarks>
/// サイズの変更が必要ないときは何もしません。
/// サイズが変更された場合、すべての要素が fillColor で塗りつぶされます。
/// 画像を拡大縮小する場合は scale() を使ってください。
/// </remarks>
/// <returns>
/// なし
/// </returns>
void resize(size_t width, size_t height, const Color& fillColor);
/// <summary>
/// 画像のサイズを変更します。
/// </summary>
/// <param name="size">
/// 新しいサイズ(ピクセル)
/// </param>
/// <param name="fillColor">
/// 塗りつぶしの色
/// </param>
/// <remarks>
/// サイズの変更が必要ないときは何もしません。
/// サイズが変更された場合、すべての要素が fillColor で塗りつぶされます。
/// 画像を拡大縮小する場合は scale() を使ってください。
/// </remarks>
/// <returns>
/// なし
/// </returns>
void resize(const Size& size, const Color& fillColor)
{
resize(size.x, size.y, fillColor);
}
void resizeRows(size_t rows, const Color& fillColor);
const Color& getPixel_Repeat(int32 x, int32 y) const
{
return m_data[m_width * Mod(y, m_height) + Mod(x, m_width)];
}
const Color& getPixel_Repeat(const Point& pos) const
{
return getPixel_Repeat(pos.x, pos.y);
}
/// <summary>
/// すべてのピクセルに変換関数を適用します。
/// </summary>
/// <param name="function">
/// 変換関数
/// </param>
/// <returns>
/// *this
/// </returns>
Image& forEach(std::function<void(Color&)> function)
{
for (auto& pixel : m_data)
{
function(pixel);
}
return *this;
}
Image& swapRB()
{
for (auto& pixel : m_data)
{
const uint32 t = pixel.r;
pixel.r = pixel.b;
pixel.b = t;
}
return *this;
}
bool applyAlphaFromRChannel(const FilePath& alpha);
Image& mirror();
Image& flip();
bool save(const FilePath& path, ImageFormat format = ImageFormat::Unspecified) const;
bool savePNG(const FilePath& path, PNGFilter::Flag filterFlag = PNGFilter::Default) const;
bool saveJPEG(const FilePath& path, int32 quality = 90) const;
bool savePPM(const FilePath& path, PPMType format = PPMType::AsciiRGB) const;
MemoryWriter encode(ImageFormat format = ImageFormat::PNG) const;
};
}
namespace std
{
inline void swap(s3d::Image& a, s3d::Image& b) noexcept
{
a.swap(b);
}
}
| 20.113429 | 106 | 0.586504 | azaika |
e3c4285bb9425bbeb1007299cd46aba3dc459ba1 | 1,832 | hpp | C++ | src/base/factory/AtmosphereFactory.hpp | ddj116/gmat | 39673be967d856f14616462fb6473b27b21b149f | [
"NASA-1.3"
] | 1 | 2020-05-16T16:58:21.000Z | 2020-05-16T16:58:21.000Z | src/base/factory/AtmosphereFactory.hpp | ddj116/gmat | 39673be967d856f14616462fb6473b27b21b149f | [
"NASA-1.3"
] | null | null | null | src/base/factory/AtmosphereFactory.hpp | ddj116/gmat | 39673be967d856f14616462fb6473b27b21b149f | [
"NASA-1.3"
] | null | null | null | //$Id: AtmosphereFactory.hpp 10639 2012-07-12 15:21:10Z djcinsb $
//------------------------------------------------------------------------------
// AtmosphereFactory
//------------------------------------------------------------------------------
// GMAT: General Mission Analysis Tool
//
// Copyright (c) 2002-2011 United States Government as represented by the
// Administrator of The National Aeronautics and Space Administration.
// All Other Rights Reserved.
//
// Developed jointly by NASA/GSFC and Thinking Systems, Inc. under contract
// number S-67573-G
//
// Author: Wendy Shoan
// Created: 2004/08/12
//
/**
* This class is the factory class for Atmospheres.
*/
//------------------------------------------------------------------------------
#ifndef AtmosphereFactory_hpp
#define AtmosphereFactory_hpp
#include "gmatdefs.hpp"
#include "Factory.hpp"
#include "AtmosphereModel.hpp"
class GMAT_API AtmosphereFactory : public Factory
{
public:
AtmosphereModel* CreateAtmosphereModel(const std::string &ofType,
const std::string &withName = "",
const std::string &forBody = "Earth");
// method to return list of types of objects that this factory can create
virtual StringArray GetListOfCreatableObjects(
const std::string &qualifier = "Earth");
// default constructor
AtmosphereFactory();
// constructor
AtmosphereFactory(StringArray createList);
// copy constructor
AtmosphereFactory(const AtmosphereFactory& fact);
// assignment operator
AtmosphereFactory& operator= (const AtmosphereFactory& fact);
// destructor
~AtmosphereFactory();
protected:
// protected data
private:
};
#endif // AtmosphereFactory_hpp
| 28.625 | 81 | 0.582969 | ddj116 |
e3c97f8161e298fb2458320d4cc636c60bc72d30 | 672 | cpp | C++ | Medusa/Medusa/Game/Settings/IJsonGameClientSettings.cpp | JamesLinus/Medusa | 243e1f67e76dba10a0b69d4154b47e884c3f191f | [
"MIT"
] | 1 | 2019-04-22T09:09:50.000Z | 2019-04-22T09:09:50.000Z | Medusa/Medusa/Game/Settings/IJsonGameClientSettings.cpp | JamesLinus/Medusa | 243e1f67e76dba10a0b69d4154b47e884c3f191f | [
"MIT"
] | null | null | null | Medusa/Medusa/Game/Settings/IJsonGameClientSettings.cpp | JamesLinus/Medusa | 243e1f67e76dba10a0b69d4154b47e884c3f191f | [
"MIT"
] | 1 | 2021-06-30T14:08:03.000Z | 2021-06-30T14:08:03.000Z | // Copyright (c) 2015 fjz13. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
#include "MedusaPreCompiled.h"
#include "IJsonGameClientSettings.h"
MEDUSA_BEGIN;
IJsonGameClientSettings::IJsonGameClientSettings(const FileIdRef& fileId)
{
}
IJsonGameClientSettings::~IJsonGameClientSettings()
{
}
void* IJsonGameClientSettings::GetAddress(const StringRef& name) const
{
return nullptr;
}
StringRef IJsonGameClientSettings::UpdateServerConfigName() const
{
return StringRef::Empty;
}
StringRef IJsonGameClientSettings::UpdateServerUrl() const
{
return StringRef::Empty;
}
MEDUSA_END;
| 17.684211 | 73 | 0.784226 | JamesLinus |
e3ca57227dce7f550a974332d997d4e6a380c9d8 | 1,664 | hpp | C++ | src/winthread.hpp | leavinel/BPG-Plugins | 1a017906bc1162779b95967f034d3b83bb730359 | [
"MIT"
] | 21 | 2015-09-09T13:45:08.000Z | 2021-11-24T05:56:00.000Z | src/winthread.hpp | leavinel/bpg_plugins | 1a017906bc1162779b95967f034d3b83bb730359 | [
"MIT"
] | 9 | 2015-11-23T12:46:36.000Z | 2017-12-18T09:50:26.000Z | src/winthread.hpp | leavinel/bpg_plugins | 1a017906bc1162779b95967f034d3b83bb730359 | [
"MIT"
] | 1 | 2017-01-23T23:38:33.000Z | 2017-01-23T23:38:33.000Z | /**
* @file
*
*
* @author Leav Wu (leavinel@gmail.com)
*/
#ifndef _WINTHREAD_HPP_
#define _WINTHREAD_HPP_
#include <windows.h>
#include <list>
#include <functional>
/**
* Subset of windows thread synchronization C++ wrapper
*/
namespace winthread {
/**
* Wrapper of windows HANDLE
*/
class handle
{
protected:
HANDLE h;
public:
handle(): h(NULL) {}
~handle();
void wait (DWORD timeout = INFINITE);
};
class mutex: private handle
{
public:
mutex();
void lock() { wait(); }
void unlock();
};
class lock_guard
{
private:
mutex &mtx;
public:
lock_guard (mutex &mtx): mtx(mtx) {
mtx.lock();
}
~lock_guard() {
mtx.unlock();
}
};
class event: private handle
{
public:
enum {
OPT_MANUAL_RESET = 1 << 0,
OPT_INIT_SIGNALED = 1 << 1,
};
event (int opts = 0);
void wait() { handle::wait(); }
void signal();
void reset();
};
class cond_var
{
private:
mutex waitMtx;
std::list<event*> waitList;
public:
cond_var() {}
/** Mutex must be locked before call */
void wait (mutex &mtx);
void notify_one();
void notify_all();
};
class thread: private handle
{
private:
std::function<void()> task;
volatile bool b_joinable;
unsigned threadId;
mutex joinMtx;
event beginEv;
public:
thread(): b_joinable(false), threadId(0), beginEv(event::OPT_MANUAL_RESET) {}
virtual ~thread();
bool joinable();
void start (std::function<void()> &task);
void join();
private:
unsigned procedure();
static unsigned WINAPI _procedure (void *_thiz);
};
}
#endif /* _WINTHREAD_HPP_ */
| 13.528455 | 81 | 0.59976 | leavinel |
e3ca99b624052f24f397568dc621e294be99c1b5 | 23,102 | hh | C++ | Core/MarchingCubes.hh | ThibaultReuille/raindance | 79f1f6aeeaf6cbe378e911cd510e6550ae34eb75 | [
"BSD-2-Clause"
] | 12 | 2015-01-15T03:30:10.000Z | 2022-02-24T21:25:29.000Z | Core/MarchingCubes.hh | ThibaultReuille/raindance | 79f1f6aeeaf6cbe378e911cd510e6550ae34eb75 | [
"BSD-2-Clause"
] | 1 | 2017-06-06T15:39:21.000Z | 2017-06-06T15:39:21.000Z | Core/MarchingCubes.hh | ThibaultReuille/raindance | 79f1f6aeeaf6cbe378e911cd510e6550ae34eb75 | [
"BSD-2-Clause"
] | 4 | 2015-07-02T22:06:56.000Z | 2022-02-24T21:25:30.000Z | #pragma once
#include <raindance/Core/Headers.hh>
static int g_EdgeTable[256]=
{
0x0 , 0x109, 0x203, 0x30a, 0x406, 0x50f, 0x605, 0x70c,
0x80c, 0x905, 0xa0f, 0xb06, 0xc0a, 0xd03, 0xe09, 0xf00,
0x190, 0x99 , 0x393, 0x29a, 0x596, 0x49f, 0x795, 0x69c,
0x99c, 0x895, 0xb9f, 0xa96, 0xd9a, 0xc93, 0xf99, 0xe90,
0x230, 0x339, 0x33 , 0x13a, 0x636, 0x73f, 0x435, 0x53c,
0xa3c, 0xb35, 0x83f, 0x936, 0xe3a, 0xf33, 0xc39, 0xd30,
0x3a0, 0x2a9, 0x1a3, 0xaa , 0x7a6, 0x6af, 0x5a5, 0x4ac,
0xbac, 0xaa5, 0x9af, 0x8a6, 0xfaa, 0xea3, 0xda9, 0xca0,
0x460, 0x569, 0x663, 0x76a, 0x66 , 0x16f, 0x265, 0x36c,
0xc6c, 0xd65, 0xe6f, 0xf66, 0x86a, 0x963, 0xa69, 0xb60,
0x5f0, 0x4f9, 0x7f3, 0x6fa, 0x1f6, 0xff , 0x3f5, 0x2fc,
0xdfc, 0xcf5, 0xfff, 0xef6, 0x9fa, 0x8f3, 0xbf9, 0xaf0,
0x650, 0x759, 0x453, 0x55a, 0x256, 0x35f, 0x55 , 0x15c,
0xe5c, 0xf55, 0xc5f, 0xd56, 0xa5a, 0xb53, 0x859, 0x950,
0x7c0, 0x6c9, 0x5c3, 0x4ca, 0x3c6, 0x2cf, 0x1c5, 0xcc ,
0xfcc, 0xec5, 0xdcf, 0xcc6, 0xbca, 0xac3, 0x9c9, 0x8c0,
0x8c0, 0x9c9, 0xac3, 0xbca, 0xcc6, 0xdcf, 0xec5, 0xfcc,
0xcc , 0x1c5, 0x2cf, 0x3c6, 0x4ca, 0x5c3, 0x6c9, 0x7c0,
0x950, 0x859, 0xb53, 0xa5a, 0xd56, 0xc5f, 0xf55, 0xe5c,
0x15c, 0x55 , 0x35f, 0x256, 0x55a, 0x453, 0x759, 0x650,
0xaf0, 0xbf9, 0x8f3, 0x9fa, 0xef6, 0xfff, 0xcf5, 0xdfc,
0x2fc, 0x3f5, 0xff , 0x1f6, 0x6fa, 0x7f3, 0x4f9, 0x5f0,
0xb60, 0xa69, 0x963, 0x86a, 0xf66, 0xe6f, 0xd65, 0xc6c,
0x36c, 0x265, 0x16f, 0x66 , 0x76a, 0x663, 0x569, 0x460,
0xca0, 0xda9, 0xea3, 0xfaa, 0x8a6, 0x9af, 0xaa5, 0xbac,
0x4ac, 0x5a5, 0x6af, 0x7a6, 0xaa , 0x1a3, 0x2a9, 0x3a0,
0xd30, 0xc39, 0xf33, 0xe3a, 0x936, 0x83f, 0xb35, 0xa3c,
0x53c, 0x435, 0x73f, 0x636, 0x13a, 0x33 , 0x339, 0x230,
0xe90, 0xf99, 0xc93, 0xd9a, 0xa96, 0xb9f, 0x895, 0x99c,
0x69c, 0x795, 0x49f, 0x596, 0x29a, 0x393, 0x99 , 0x190,
0xf00, 0xe09, 0xd03, 0xc0a, 0xb06, 0xa0f, 0x905, 0x80c,
0x70c, 0x605, 0x50f, 0x406, 0x30a, 0x203, 0x109, 0x0
};
static int g_TriTable[256][16] =
{
{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{0, 8, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{0, 1, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{1, 8, 3, 9, 8, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{1, 2, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{0, 8, 3, 1, 2, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{9, 2, 10, 0, 2, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{2, 8, 3, 2, 10, 8, 10, 9, 8, -1, -1, -1, -1, -1, -1, -1},
{3, 11, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{0, 11, 2, 8, 11, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{1, 9, 0, 2, 3, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{1, 11, 2, 1, 9, 11, 9, 8, 11, -1, -1, -1, -1, -1, -1, -1},
{3, 10, 1, 11, 10, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{0, 10, 1, 0, 8, 10, 8, 11, 10, -1, -1, -1, -1, -1, -1, -1},
{3, 9, 0, 3, 11, 9, 11, 10, 9, -1, -1, -1, -1, -1, -1, -1},
{9, 8, 10, 10, 8, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{4, 7, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{4, 3, 0, 7, 3, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{0, 1, 9, 8, 4, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{4, 1, 9, 4, 7, 1, 7, 3, 1, -1, -1, -1, -1, -1, -1, -1},
{1, 2, 10, 8, 4, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{3, 4, 7, 3, 0, 4, 1, 2, 10, -1, -1, -1, -1, -1, -1, -1},
{9, 2, 10, 9, 0, 2, 8, 4, 7, -1, -1, -1, -1, -1, -1, -1},
{2, 10, 9, 2, 9, 7, 2, 7, 3, 7, 9, 4, -1, -1, -1, -1},
{8, 4, 7, 3, 11, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{11, 4, 7, 11, 2, 4, 2, 0, 4, -1, -1, -1, -1, -1, -1, -1},
{9, 0, 1, 8, 4, 7, 2, 3, 11, -1, -1, -1, -1, -1, -1, -1},
{4, 7, 11, 9, 4, 11, 9, 11, 2, 9, 2, 1, -1, -1, -1, -1},
{3, 10, 1, 3, 11, 10, 7, 8, 4, -1, -1, -1, -1, -1, -1, -1},
{1, 11, 10, 1, 4, 11, 1, 0, 4, 7, 11, 4, -1, -1, -1, -1},
{4, 7, 8, 9, 0, 11, 9, 11, 10, 11, 0, 3, -1, -1, -1, -1},
{4, 7, 11, 4, 11, 9, 9, 11, 10, -1, -1, -1, -1, -1, -1, -1},
{9, 5, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{9, 5, 4, 0, 8, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{0, 5, 4, 1, 5, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{8, 5, 4, 8, 3, 5, 3, 1, 5, -1, -1, -1, -1, -1, -1, -1},
{1, 2, 10, 9, 5, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{3, 0, 8, 1, 2, 10, 4, 9, 5, -1, -1, -1, -1, -1, -1, -1},
{5, 2, 10, 5, 4, 2, 4, 0, 2, -1, -1, -1, -1, -1, -1, -1},
{2, 10, 5, 3, 2, 5, 3, 5, 4, 3, 4, 8, -1, -1, -1, -1},
{9, 5, 4, 2, 3, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{0, 11, 2, 0, 8, 11, 4, 9, 5, -1, -1, -1, -1, -1, -1, -1},
{0, 5, 4, 0, 1, 5, 2, 3, 11, -1, -1, -1, -1, -1, -1, -1},
{2, 1, 5, 2, 5, 8, 2, 8, 11, 4, 8, 5, -1, -1, -1, -1},
{10, 3, 11, 10, 1, 3, 9, 5, 4, -1, -1, -1, -1, -1, -1, -1},
{4, 9, 5, 0, 8, 1, 8, 10, 1, 8, 11, 10, -1, -1, -1, -1},
{5, 4, 0, 5, 0, 11, 5, 11, 10, 11, 0, 3, -1, -1, -1, -1},
{5, 4, 8, 5, 8, 10, 10, 8, 11, -1, -1, -1, -1, -1, -1, -1},
{9, 7, 8, 5, 7, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{9, 3, 0, 9, 5, 3, 5, 7, 3, -1, -1, -1, -1, -1, -1, -1},
{0, 7, 8, 0, 1, 7, 1, 5, 7, -1, -1, -1, -1, -1, -1, -1},
{1, 5, 3, 3, 5, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{9, 7, 8, 9, 5, 7, 10, 1, 2, -1, -1, -1, -1, -1, -1, -1},
{10, 1, 2, 9, 5, 0, 5, 3, 0, 5, 7, 3, -1, -1, -1, -1},
{8, 0, 2, 8, 2, 5, 8, 5, 7, 10, 5, 2, -1, -1, -1, -1},
{2, 10, 5, 2, 5, 3, 3, 5, 7, -1, -1, -1, -1, -1, -1, -1},
{7, 9, 5, 7, 8, 9, 3, 11, 2, -1, -1, -1, -1, -1, -1, -1},
{9, 5, 7, 9, 7, 2, 9, 2, 0, 2, 7, 11, -1, -1, -1, -1},
{2, 3, 11, 0, 1, 8, 1, 7, 8, 1, 5, 7, -1, -1, -1, -1},
{11, 2, 1, 11, 1, 7, 7, 1, 5, -1, -1, -1, -1, -1, -1, -1},
{9, 5, 8, 8, 5, 7, 10, 1, 3, 10, 3, 11, -1, -1, -1, -1},
{5, 7, 0, 5, 0, 9, 7, 11, 0, 1, 0, 10, 11, 10, 0, -1},
{11, 10, 0, 11, 0, 3, 10, 5, 0, 8, 0, 7, 5, 7, 0, -1},
{11, 10, 5, 7, 11, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{10, 6, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{0, 8, 3, 5, 10, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{9, 0, 1, 5, 10, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{1, 8, 3, 1, 9, 8, 5, 10, 6, -1, -1, -1, -1, -1, -1, -1},
{1, 6, 5, 2, 6, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{1, 6, 5, 1, 2, 6, 3, 0, 8, -1, -1, -1, -1, -1, -1, -1},
{9, 6, 5, 9, 0, 6, 0, 2, 6, -1, -1, -1, -1, -1, -1, -1},
{5, 9, 8, 5, 8, 2, 5, 2, 6, 3, 2, 8, -1, -1, -1, -1},
{2, 3, 11, 10, 6, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{11, 0, 8, 11, 2, 0, 10, 6, 5, -1, -1, -1, -1, -1, -1, -1},
{0, 1, 9, 2, 3, 11, 5, 10, 6, -1, -1, -1, -1, -1, -1, -1},
{5, 10, 6, 1, 9, 2, 9, 11, 2, 9, 8, 11, -1, -1, -1, -1},
{6, 3, 11, 6, 5, 3, 5, 1, 3, -1, -1, -1, -1, -1, -1, -1},
{0, 8, 11, 0, 11, 5, 0, 5, 1, 5, 11, 6, -1, -1, -1, -1},
{3, 11, 6, 0, 3, 6, 0, 6, 5, 0, 5, 9, -1, -1, -1, -1},
{6, 5, 9, 6, 9, 11, 11, 9, 8, -1, -1, -1, -1, -1, -1, -1},
{5, 10, 6, 4, 7, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{4, 3, 0, 4, 7, 3, 6, 5, 10, -1, -1, -1, -1, -1, -1, -1},
{1, 9, 0, 5, 10, 6, 8, 4, 7, -1, -1, -1, -1, -1, -1, -1},
{10, 6, 5, 1, 9, 7, 1, 7, 3, 7, 9, 4, -1, -1, -1, -1},
{6, 1, 2, 6, 5, 1, 4, 7, 8, -1, -1, -1, -1, -1, -1, -1},
{1, 2, 5, 5, 2, 6, 3, 0, 4, 3, 4, 7, -1, -1, -1, -1},
{8, 4, 7, 9, 0, 5, 0, 6, 5, 0, 2, 6, -1, -1, -1, -1},
{7, 3, 9, 7, 9, 4, 3, 2, 9, 5, 9, 6, 2, 6, 9, -1},
{3, 11, 2, 7, 8, 4, 10, 6, 5, -1, -1, -1, -1, -1, -1, -1},
{5, 10, 6, 4, 7, 2, 4, 2, 0, 2, 7, 11, -1, -1, -1, -1},
{0, 1, 9, 4, 7, 8, 2, 3, 11, 5, 10, 6, -1, -1, -1, -1},
{9, 2, 1, 9, 11, 2, 9, 4, 11, 7, 11, 4, 5, 10, 6, -1},
{8, 4, 7, 3, 11, 5, 3, 5, 1, 5, 11, 6, -1, -1, -1, -1},
{5, 1, 11, 5, 11, 6, 1, 0, 11, 7, 11, 4, 0, 4, 11, -1},
{0, 5, 9, 0, 6, 5, 0, 3, 6, 11, 6, 3, 8, 4, 7, -1},
{6, 5, 9, 6, 9, 11, 4, 7, 9, 7, 11, 9, -1, -1, -1, -1},
{10, 4, 9, 6, 4, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{4, 10, 6, 4, 9, 10, 0, 8, 3, -1, -1, -1, -1, -1, -1, -1},
{10, 0, 1, 10, 6, 0, 6, 4, 0, -1, -1, -1, -1, -1, -1, -1},
{8, 3, 1, 8, 1, 6, 8, 6, 4, 6, 1, 10, -1, -1, -1, -1},
{1, 4, 9, 1, 2, 4, 2, 6, 4, -1, -1, -1, -1, -1, -1, -1},
{3, 0, 8, 1, 2, 9, 2, 4, 9, 2, 6, 4, -1, -1, -1, -1},
{0, 2, 4, 4, 2, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{8, 3, 2, 8, 2, 4, 4, 2, 6, -1, -1, -1, -1, -1, -1, -1},
{10, 4, 9, 10, 6, 4, 11, 2, 3, -1, -1, -1, -1, -1, -1, -1},
{0, 8, 2, 2, 8, 11, 4, 9, 10, 4, 10, 6, -1, -1, -1, -1},
{3, 11, 2, 0, 1, 6, 0, 6, 4, 6, 1, 10, -1, -1, -1, -1},
{6, 4, 1, 6, 1, 10, 4, 8, 1, 2, 1, 11, 8, 11, 1, -1},
{9, 6, 4, 9, 3, 6, 9, 1, 3, 11, 6, 3, -1, -1, -1, -1},
{8, 11, 1, 8, 1, 0, 11, 6, 1, 9, 1, 4, 6, 4, 1, -1},
{3, 11, 6, 3, 6, 0, 0, 6, 4, -1, -1, -1, -1, -1, -1, -1},
{6, 4, 8, 11, 6, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{7, 10, 6, 7, 8, 10, 8, 9, 10, -1, -1, -1, -1, -1, -1, -1},
{0, 7, 3, 0, 10, 7, 0, 9, 10, 6, 7, 10, -1, -1, -1, -1},
{10, 6, 7, 1, 10, 7, 1, 7, 8, 1, 8, 0, -1, -1, -1, -1},
{10, 6, 7, 10, 7, 1, 1, 7, 3, -1, -1, -1, -1, -1, -1, -1},
{1, 2, 6, 1, 6, 8, 1, 8, 9, 8, 6, 7, -1, -1, -1, -1},
{2, 6, 9, 2, 9, 1, 6, 7, 9, 0, 9, 3, 7, 3, 9, -1},
{7, 8, 0, 7, 0, 6, 6, 0, 2, -1, -1, -1, -1, -1, -1, -1},
{7, 3, 2, 6, 7, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{2, 3, 11, 10, 6, 8, 10, 8, 9, 8, 6, 7, -1, -1, -1, -1},
{2, 0, 7, 2, 7, 11, 0, 9, 7, 6, 7, 10, 9, 10, 7, -1},
{1, 8, 0, 1, 7, 8, 1, 10, 7, 6, 7, 10, 2, 3, 11, -1},
{11, 2, 1, 11, 1, 7, 10, 6, 1, 6, 7, 1, -1, -1, -1, -1},
{8, 9, 6, 8, 6, 7, 9, 1, 6, 11, 6, 3, 1, 3, 6, -1},
{0, 9, 1, 11, 6, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{7, 8, 0, 7, 0, 6, 3, 11, 0, 11, 6, 0, -1, -1, -1, -1},
{7, 11, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{7, 6, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{3, 0, 8, 11, 7, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{0, 1, 9, 11, 7, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{8, 1, 9, 8, 3, 1, 11, 7, 6, -1, -1, -1, -1, -1, -1, -1},
{10, 1, 2, 6, 11, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{1, 2, 10, 3, 0, 8, 6, 11, 7, -1, -1, -1, -1, -1, -1, -1},
{2, 9, 0, 2, 10, 9, 6, 11, 7, -1, -1, -1, -1, -1, -1, -1},
{6, 11, 7, 2, 10, 3, 10, 8, 3, 10, 9, 8, -1, -1, -1, -1},
{7, 2, 3, 6, 2, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{7, 0, 8, 7, 6, 0, 6, 2, 0, -1, -1, -1, -1, -1, -1, -1},
{2, 7, 6, 2, 3, 7, 0, 1, 9, -1, -1, -1, -1, -1, -1, -1},
{1, 6, 2, 1, 8, 6, 1, 9, 8, 8, 7, 6, -1, -1, -1, -1},
{10, 7, 6, 10, 1, 7, 1, 3, 7, -1, -1, -1, -1, -1, -1, -1},
{10, 7, 6, 1, 7, 10, 1, 8, 7, 1, 0, 8, -1, -1, -1, -1},
{0, 3, 7, 0, 7, 10, 0, 10, 9, 6, 10, 7, -1, -1, -1, -1},
{7, 6, 10, 7, 10, 8, 8, 10, 9, -1, -1, -1, -1, -1, -1, -1},
{6, 8, 4, 11, 8, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{3, 6, 11, 3, 0, 6, 0, 4, 6, -1, -1, -1, -1, -1, -1, -1},
{8, 6, 11, 8, 4, 6, 9, 0, 1, -1, -1, -1, -1, -1, -1, -1},
{9, 4, 6, 9, 6, 3, 9, 3, 1, 11, 3, 6, -1, -1, -1, -1},
{6, 8, 4, 6, 11, 8, 2, 10, 1, -1, -1, -1, -1, -1, -1, -1},
{1, 2, 10, 3, 0, 11, 0, 6, 11, 0, 4, 6, -1, -1, -1, -1},
{4, 11, 8, 4, 6, 11, 0, 2, 9, 2, 10, 9, -1, -1, -1, -1},
{10, 9, 3, 10, 3, 2, 9, 4, 3, 11, 3, 6, 4, 6, 3, -1},
{8, 2, 3, 8, 4, 2, 4, 6, 2, -1, -1, -1, -1, -1, -1, -1},
{0, 4, 2, 4, 6, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{1, 9, 0, 2, 3, 4, 2, 4, 6, 4, 3, 8, -1, -1, -1, -1},
{1, 9, 4, 1, 4, 2, 2, 4, 6, -1, -1, -1, -1, -1, -1, -1},
{8, 1, 3, 8, 6, 1, 8, 4, 6, 6, 10, 1, -1, -1, -1, -1},
{10, 1, 0, 10, 0, 6, 6, 0, 4, -1, -1, -1, -1, -1, -1, -1},
{4, 6, 3, 4, 3, 8, 6, 10, 3, 0, 3, 9, 10, 9, 3, -1},
{10, 9, 4, 6, 10, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{4, 9, 5, 7, 6, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{0, 8, 3, 4, 9, 5, 11, 7, 6, -1, -1, -1, -1, -1, -1, -1},
{5, 0, 1, 5, 4, 0, 7, 6, 11, -1, -1, -1, -1, -1, -1, -1},
{11, 7, 6, 8, 3, 4, 3, 5, 4, 3, 1, 5, -1, -1, -1, -1},
{9, 5, 4, 10, 1, 2, 7, 6, 11, -1, -1, -1, -1, -1, -1, -1},
{6, 11, 7, 1, 2, 10, 0, 8, 3, 4, 9, 5, -1, -1, -1, -1},
{7, 6, 11, 5, 4, 10, 4, 2, 10, 4, 0, 2, -1, -1, -1, -1},
{3, 4, 8, 3, 5, 4, 3, 2, 5, 10, 5, 2, 11, 7, 6, -1},
{7, 2, 3, 7, 6, 2, 5, 4, 9, -1, -1, -1, -1, -1, -1, -1},
{9, 5, 4, 0, 8, 6, 0, 6, 2, 6, 8, 7, -1, -1, -1, -1},
{3, 6, 2, 3, 7, 6, 1, 5, 0, 5, 4, 0, -1, -1, -1, -1},
{6, 2, 8, 6, 8, 7, 2, 1, 8, 4, 8, 5, 1, 5, 8, -1},
{9, 5, 4, 10, 1, 6, 1, 7, 6, 1, 3, 7, -1, -1, -1, -1},
{1, 6, 10, 1, 7, 6, 1, 0, 7, 8, 7, 0, 9, 5, 4, -1},
{4, 0, 10, 4, 10, 5, 0, 3, 10, 6, 10, 7, 3, 7, 10, -1},
{7, 6, 10, 7, 10, 8, 5, 4, 10, 4, 8, 10, -1, -1, -1, -1},
{6, 9, 5, 6, 11, 9, 11, 8, 9, -1, -1, -1, -1, -1, -1, -1},
{3, 6, 11, 0, 6, 3, 0, 5, 6, 0, 9, 5, -1, -1, -1, -1},
{0, 11, 8, 0, 5, 11, 0, 1, 5, 5, 6, 11, -1, -1, -1, -1},
{6, 11, 3, 6, 3, 5, 5, 3, 1, -1, -1, -1, -1, -1, -1, -1},
{1, 2, 10, 9, 5, 11, 9, 11, 8, 11, 5, 6, -1, -1, -1, -1},
{0, 11, 3, 0, 6, 11, 0, 9, 6, 5, 6, 9, 1, 2, 10, -1},
{11, 8, 5, 11, 5, 6, 8, 0, 5, 10, 5, 2, 0, 2, 5, -1},
{6, 11, 3, 6, 3, 5, 2, 10, 3, 10, 5, 3, -1, -1, -1, -1},
{5, 8, 9, 5, 2, 8, 5, 6, 2, 3, 8, 2, -1, -1, -1, -1},
{9, 5, 6, 9, 6, 0, 0, 6, 2, -1, -1, -1, -1, -1, -1, -1},
{1, 5, 8, 1, 8, 0, 5, 6, 8, 3, 8, 2, 6, 2, 8, -1},
{1, 5, 6, 2, 1, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{1, 3, 6, 1, 6, 10, 3, 8, 6, 5, 6, 9, 8, 9, 6, -1},
{10, 1, 0, 10, 0, 6, 9, 5, 0, 5, 6, 0, -1, -1, -1, -1},
{0, 3, 8, 5, 6, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{10, 5, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{11, 5, 10, 7, 5, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{11, 5, 10, 11, 7, 5, 8, 3, 0, -1, -1, -1, -1, -1, -1, -1},
{5, 11, 7, 5, 10, 11, 1, 9, 0, -1, -1, -1, -1, -1, -1, -1},
{10, 7, 5, 10, 11, 7, 9, 8, 1, 8, 3, 1, -1, -1, -1, -1},
{11, 1, 2, 11, 7, 1, 7, 5, 1, -1, -1, -1, -1, -1, -1, -1},
{0, 8, 3, 1, 2, 7, 1, 7, 5, 7, 2, 11, -1, -1, -1, -1},
{9, 7, 5, 9, 2, 7, 9, 0, 2, 2, 11, 7, -1, -1, -1, -1},
{7, 5, 2, 7, 2, 11, 5, 9, 2, 3, 2, 8, 9, 8, 2, -1},
{2, 5, 10, 2, 3, 5, 3, 7, 5, -1, -1, -1, -1, -1, -1, -1},
{8, 2, 0, 8, 5, 2, 8, 7, 5, 10, 2, 5, -1, -1, -1, -1},
{9, 0, 1, 5, 10, 3, 5, 3, 7, 3, 10, 2, -1, -1, -1, -1},
{9, 8, 2, 9, 2, 1, 8, 7, 2, 10, 2, 5, 7, 5, 2, -1},
{1, 3, 5, 3, 7, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{0, 8, 7, 0, 7, 1, 1, 7, 5, -1, -1, -1, -1, -1, -1, -1},
{9, 0, 3, 9, 3, 5, 5, 3, 7, -1, -1, -1, -1, -1, -1, -1},
{9, 8, 7, 5, 9, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{5, 8, 4, 5, 10, 8, 10, 11, 8, -1, -1, -1, -1, -1, -1, -1},
{5, 0, 4, 5, 11, 0, 5, 10, 11, 11, 3, 0, -1, -1, -1, -1},
{0, 1, 9, 8, 4, 10, 8, 10, 11, 10, 4, 5, -1, -1, -1, -1},
{10, 11, 4, 10, 4, 5, 11, 3, 4, 9, 4, 1, 3, 1, 4, -1},
{2, 5, 1, 2, 8, 5, 2, 11, 8, 4, 5, 8, -1, -1, -1, -1},
{0, 4, 11, 0, 11, 3, 4, 5, 11, 2, 11, 1, 5, 1, 11, -1},
{0, 2, 5, 0, 5, 9, 2, 11, 5, 4, 5, 8, 11, 8, 5, -1},
{9, 4, 5, 2, 11, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{2, 5, 10, 3, 5, 2, 3, 4, 5, 3, 8, 4, -1, -1, -1, -1},
{5, 10, 2, 5, 2, 4, 4, 2, 0, -1, -1, -1, -1, -1, -1, -1},
{3, 10, 2, 3, 5, 10, 3, 8, 5, 4, 5, 8, 0, 1, 9, -1},
{5, 10, 2, 5, 2, 4, 1, 9, 2, 9, 4, 2, -1, -1, -1, -1},
{8, 4, 5, 8, 5, 3, 3, 5, 1, -1, -1, -1, -1, -1, -1, -1},
{0, 4, 5, 1, 0, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{8, 4, 5, 8, 5, 3, 9, 0, 5, 0, 3, 5, -1, -1, -1, -1},
{9, 4, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{4, 11, 7, 4, 9, 11, 9, 10, 11, -1, -1, -1, -1, -1, -1, -1},
{0, 8, 3, 4, 9, 7, 9, 11, 7, 9, 10, 11, -1, -1, -1, -1},
{1, 10, 11, 1, 11, 4, 1, 4, 0, 7, 4, 11, -1, -1, -1, -1},
{3, 1, 4, 3, 4, 8, 1, 10, 4, 7, 4, 11, 10, 11, 4, -1},
{4, 11, 7, 9, 11, 4, 9, 2, 11, 9, 1, 2, -1, -1, -1, -1},
{9, 7, 4, 9, 11, 7, 9, 1, 11, 2, 11, 1, 0, 8, 3, -1},
{11, 7, 4, 11, 4, 2, 2, 4, 0, -1, -1, -1, -1, -1, -1, -1},
{11, 7, 4, 11, 4, 2, 8, 3, 4, 3, 2, 4, -1, -1, -1, -1},
{2, 9, 10, 2, 7, 9, 2, 3, 7, 7, 4, 9, -1, -1, -1, -1},
{9, 10, 7, 9, 7, 4, 10, 2, 7, 8, 7, 0, 2, 0, 7, -1},
{3, 7, 10, 3, 10, 2, 7, 4, 10, 1, 10, 0, 4, 0, 10, -1},
{1, 10, 2, 8, 7, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{4, 9, 1, 4, 1, 7, 7, 1, 3, -1, -1, -1, -1, -1, -1, -1},
{4, 9, 1, 4, 1, 7, 0, 8, 1, 8, 7, 1, -1, -1, -1, -1},
{4, 0, 3, 7, 4, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{4, 8, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{9, 10, 8, 10, 11, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{3, 0, 9, 3, 9, 11, 11, 9, 10, -1, -1, -1, -1, -1, -1, -1},
{0, 1, 10, 0, 10, 8, 8, 10, 11, -1, -1, -1, -1, -1, -1, -1},
{3, 1, 10, 11, 3, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{1, 2, 11, 1, 11, 9, 9, 11, 8, -1, -1, -1, -1, -1, -1, -1},
{3, 0, 9, 3, 9, 11, 1, 2, 9, 2, 11, 9, -1, -1, -1, -1},
{0, 2, 11, 8, 0, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{3, 2, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{2, 3, 8, 2, 8, 10, 10, 8, 9, -1, -1, -1, -1, -1, -1, -1},
{9, 10, 2, 0, 9, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{2, 3, 8, 2, 8, 10, 0, 1, 8, 1, 10, 8, -1, -1, -1, -1},
{1, 10, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{1, 3, 8, 9, 1, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{0, 9, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{0, 3, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}
};
class MarchingCubes
{
public:
struct Cell
{
float Scalar;
};
class Grid
{
public:
Grid(unsigned int x, unsigned int y, unsigned int z, const glm::vec3& min, const glm::vec3& max)
{
m_Dimension[0] = x;
m_Dimension[1] = y;
m_Dimension[2] = z;
m_Min = min;
m_Max = max;
m_Step.x = fabs(max.x - min.x) / (float) x;
m_Step.y = fabs(max.y - min.y) / (float) y;
m_Step.z = fabs(max.z - min.z) / (float) z;
m_Cells = new Cell[x * y * z];
}
~Grid()
{
if (m_Cells != NULL)
delete[] m_Cells;
}
inline Cell& cell(unsigned x, unsigned int y, unsigned int z)
{
return m_Cells[x + y * m_Dimension[0] + z * m_Dimension[0] * m_Dimension[1]];
}
inline glm::vec3 getPosition(unsigned x, unsigned int y, unsigned int z)
{
return m_Min + glm::vec3((float) x, (float) y, (float) z) * m_Step;
}
glm::vec3 interpolatePoints (unsigned int x, unsigned int y, unsigned int z, const unsigned int p1[3], const unsigned int p2[3], float isolevel)
{
const float epsilon = std::numeric_limits<float>::epsilon();
glm::vec3 v1, v2;
float w1, w2;
v1 = getPosition(x + p1[0], y + p1[1], z + p1[2]);
v2 = getPosition(x + p2[0], y + p2[1], z + p2[2]);
w1 = cell(x + p1[0], y + p1[1], z + p1[2]).Scalar;
w2 = cell(x + p2[0], y + p2[1], z + p2[2]).Scalar;
if (fabs (isolevel - w1) < epsilon)
return v1;
if (fabs (isolevel - w2) < epsilon)
return v2;
if (fabs (w1 - w2) < epsilon)
return (v1);
return v1 + ((isolevel - w1) / (w2 - w1)) * (v2 - v1);
}
inline unsigned int getWidth() { return m_Dimension[0]; }
inline unsigned int getHeight() { return m_Dimension[1]; }
inline unsigned int getDepth() { return m_Dimension[2]; }
inline glm::vec3 getStep() { return m_Step; }
private:
Cell* m_Cells;
unsigned int m_Dimension[3];
glm::vec3 m_Min;
glm::vec3 m_Max;
glm::vec3 m_Step;
};
MarchingCubes()
{
m_Grid = NULL;
}
virtual ~MarchingCubes()
{
SAFE_DELETE(m_Grid);
}
void buildGrid(PointCloud* isovolume, unsigned int dimension[3], const glm::vec3& min, const glm::vec3& max)
{
LOG("[MARCHINGCUBES] Building Grid : dim (%u, %u, %u), min(%f, %f, %f), max(%f, %f, %f) ...\n", dimension[0], dimension[1], dimension[2], min.x, min.y, min.z, max.x, max.x, max.z);
SAFE_DELETE(m_Grid);
m_Grid = new Grid(dimension[0], dimension[1], dimension[2], min, max);
glm::vec3 pos;
for (unsigned int z = 0; z < dimension[2]; z++)
for (unsigned int y = 0; y < dimension[1]; y++)
for (unsigned int x = 0; x < dimension[0]; x++)
{
pos = m_Grid->getPosition(x, y, z);
m_Grid->cell(x, y, z).Scalar = isovolume->computeScalar(pos);
LOG("Grid(%u, %u, %u) : pos(%f, %f, %f) = %f\n", x, y, z, pos.x, pos.y, pos.z, m_Grid->cell(x, y, z).Scalar);
}
}
void polygonize(float isolevel, Mesh& mesh)
{
LOG("[MARCHINGCUBES] Polygonizing (isolevel = %f) ...\n", isolevel);
const unsigned int points[8][3] =
{
{0, 0, 0},
{1, 0, 0},
{1, 0, 1},
{0, 0, 1},
{0, 1, 0},
{1, 1, 0},
{1, 1, 1},
{0, 1, 1}
};
for (unsigned int z = 0; z < m_Grid->getDepth() - 1; z++)
for (unsigned int y = 0; y < m_Grid->getHeight() - 1; y++)
for (unsigned int x = 0; x < m_Grid->getWidth() - 1; x++)
{
// Determine the index into the edge table which
// tells us which vertices are inside of the surface
int cubeindex = 0;
for (int i = 0; i < 8; i++)
if (m_Grid->cell(x + points[i][0], y + points[i][1], z + points[i][2]).Scalar < isolevel)
cubeindex |= 1 << i;
LOG("Cell (%u, %u, %u) : cubeindex = %u\n", x, y, z, cubeindex);
// Cube is entirely in/out of the surface
if (g_EdgeTable[cubeindex] == 0)
continue;
glm::vec3 v[8];
for (int i = 0 ; i < 8; i++)
v[i] = m_Grid->getPosition(x + points[i][0], y + points[i][1], z + points[i][2]);
glm::vec3 ce[12];
if (g_EdgeTable[cubeindex] & 1)
ce[0] = m_Grid->interpolatePoints(x, y, z, points[0], points[1], isolevel);
if (g_EdgeTable[cubeindex] & 2)
ce[1] = m_Grid->interpolatePoints(x, y, z, points[1], points[2], isolevel);
if (g_EdgeTable[cubeindex] & 4)
ce[2] = m_Grid->interpolatePoints(x, y, z, points[2], points[3], isolevel);
if (g_EdgeTable[cubeindex] & 8)
ce[3] = m_Grid->interpolatePoints(x, y, z, points[3], points[0], isolevel);
if (g_EdgeTable[cubeindex] & 16)
ce[4] = m_Grid->interpolatePoints(x, y, z, points[4], points[5], isolevel);
if (g_EdgeTable[cubeindex] & 32)
ce[5] = m_Grid->interpolatePoints(x, y, z, points[5], points[6], isolevel);
if (g_EdgeTable[cubeindex] & 64)
ce[6] = m_Grid->interpolatePoints(x, y, z, points[6], points[7], isolevel);
if (g_EdgeTable[cubeindex] & 128)
ce[7] = m_Grid->interpolatePoints(x, y, z, points[7], points[4], isolevel);
if (g_EdgeTable[cubeindex] & 256)
ce[8] = m_Grid->interpolatePoints(x, y, z, points[0], points[4], isolevel);
if (g_EdgeTable[cubeindex] & 512)
ce[9] = m_Grid->interpolatePoints(x, y, z, points[1], points[5], isolevel);
if (g_EdgeTable[cubeindex] & 1024)
ce[10] = m_Grid->interpolatePoints(x, y, z, points[2], points[6], isolevel);
if (g_EdgeTable[cubeindex] & 2048)
ce[11] = m_Grid->interpolatePoints(x, y, z, points[3], points[7], isolevel);
for (int i = 0; g_TriTable[cubeindex][i] != -1 ; i += 3)
{
glm::vec3 p1 = ce[g_TriTable[cubeindex][i]];
glm::vec3 p2 = ce[g_TriTable[cubeindex][i + 1]];
glm::vec3 p3 = ce[g_TriTable[cubeindex][i + 2]];
glm::vec3 n = glm::cross(p3 - p1, p2 - p1);
Mesh::Vertex::ID v1 = mesh.addVertex(Mesh::Vertex(p1, n));
LOG("addVertex(%f, %f, %f)\n", p1.x, p1.y, p1.z);
Mesh::Vertex::ID v2 = mesh.addVertex(Mesh::Vertex(p2, n));
LOG("addVertex(%f, %f, %f)\n", p2.x, p2.y, p2.z);
Mesh::Vertex::ID v3 = mesh.addVertex(Mesh::Vertex(p3, n));
LOG("addVertex(%f, %f, %f)\n", p3.x, p3.y, p3.z);
Mesh::Triangle::ID t = mesh.addTriangle(Mesh::Triangle(v1, v2, v3));
LOG("addTriangle(%u, %u, %u) : %u\n", v1, v2, v3, t);
}
}
}
private:
Grid* m_Grid;
};
| 45.928429 | 182 | 0.407194 | ThibaultReuille |
e3cd0ee0048780f429888ecae49256d4ef095d7c | 3,856 | hpp | C++ | include/UnityEngine/EventSystems/AxisEventData.hpp | darknight1050/BeatSaber-Quest-Codegen | a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032 | [
"Unlicense"
] | null | null | null | include/UnityEngine/EventSystems/AxisEventData.hpp | darknight1050/BeatSaber-Quest-Codegen | a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032 | [
"Unlicense"
] | null | null | null | include/UnityEngine/EventSystems/AxisEventData.hpp | darknight1050/BeatSaber-Quest-Codegen | a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032 | [
"Unlicense"
] | null | null | null | // Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "extern/beatsaber-hook/shared/utils/typedefs.h"
// Including type: UnityEngine.EventSystems.BaseEventData
#include "UnityEngine/EventSystems/BaseEventData.hpp"
// Including type: UnityEngine.Vector2
#include "UnityEngine/Vector2.hpp"
// Including type: UnityEngine.EventSystems.MoveDirection
#include "UnityEngine/EventSystems/MoveDirection.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "extern/beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Begin forward declares
// Forward declaring namespace: UnityEngine::EventSystems
namespace UnityEngine::EventSystems {
// Forward declaring type: EventSystem
class EventSystem;
}
// Completed forward declares
// Type namespace: UnityEngine.EventSystems
namespace UnityEngine::EventSystems {
// Size: 0x2C
#pragma pack(push, 1)
// Autogenerated type: UnityEngine.EventSystems.AxisEventData
class AxisEventData : public UnityEngine::EventSystems::BaseEventData {
public:
// [CompilerGeneratedAttribute] Offset: 0xDC8B1C
// private UnityEngine.Vector2 <moveVector>k__BackingField
// Size: 0x8
// Offset: 0x20
UnityEngine::Vector2 moveVector;
// Field size check
static_assert(sizeof(UnityEngine::Vector2) == 0x8);
// [CompilerGeneratedAttribute] Offset: 0xDC8B2C
// private UnityEngine.EventSystems.MoveDirection <moveDir>k__BackingField
// Size: 0x4
// Offset: 0x28
UnityEngine::EventSystems::MoveDirection moveDir;
// Field size check
static_assert(sizeof(UnityEngine::EventSystems::MoveDirection) == 0x4);
// Creating value type constructor for type: AxisEventData
AxisEventData(UnityEngine::Vector2 moveVector_ = {}, UnityEngine::EventSystems::MoveDirection moveDir_ = {}) noexcept : moveVector{moveVector_}, moveDir{moveDir_} {}
// public UnityEngine.Vector2 get_moveVector()
// Offset: 0x1412178
UnityEngine::Vector2 get_moveVector();
// public System.Void set_moveVector(UnityEngine.Vector2 value)
// Offset: 0x1412180
void set_moveVector(UnityEngine::Vector2 value);
// public UnityEngine.EventSystems.MoveDirection get_moveDir()
// Offset: 0x1412188
UnityEngine::EventSystems::MoveDirection get_moveDir();
// public System.Void set_moveDir(UnityEngine.EventSystems.MoveDirection value)
// Offset: 0x1412190
void set_moveDir(UnityEngine::EventSystems::MoveDirection value);
// public System.Void .ctor(UnityEngine.EventSystems.EventSystem eventSystem)
// Offset: 0x1412198
// Implemented from: UnityEngine.EventSystems.BaseEventData
// Base method: System.Void BaseEventData::.ctor(UnityEngine.EventSystems.EventSystem eventSystem)
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static AxisEventData* New_ctor(UnityEngine::EventSystems::EventSystem* eventSystem) {
static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::EventSystems::AxisEventData::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<AxisEventData*, creationType>(eventSystem)));
}
}; // UnityEngine.EventSystems.AxisEventData
#pragma pack(pop)
static check_size<sizeof(AxisEventData), 40 + sizeof(UnityEngine::EventSystems::MoveDirection)> __UnityEngine_EventSystems_AxisEventDataSizeCheck;
static_assert(sizeof(AxisEventData) == 0x2C);
}
DEFINE_IL2CPP_ARG_TYPE(UnityEngine::EventSystems::AxisEventData*, "UnityEngine.EventSystems", "AxisEventData");
| 51.413333 | 170 | 0.741961 | darknight1050 |
e3d8a7ea15e6304f260f358d216549c0884bc5d7 | 53,201 | cc | C++ | components/exo/shell_surface_base.cc | zipated/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 2,151 | 2020-04-18T07:31:17.000Z | 2022-03-31T08:39:18.000Z | components/exo/shell_surface_base.cc | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 395 | 2020-04-18T08:22:18.000Z | 2021-12-08T13:04:49.000Z | components/exo/shell_surface_base.cc | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 338 | 2020-04-18T08:03:10.000Z | 2022-03-29T12:33:22.000Z | // Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/exo/shell_surface_base.h"
#include <algorithm>
#include "ash/frame/custom_frame_view_ash.h"
#include "ash/public/cpp/config.h"
#include "ash/public/cpp/shelf_types.h"
#include "ash/public/cpp/shell_window_ids.h"
#include "ash/public/cpp/window_properties.h"
#include "ash/public/cpp/window_state_type.h"
#include "ash/public/interfaces/window_pin_type.mojom.h"
#include "ash/shell.h"
#include "ash/wm/drag_window_resizer.h"
#include "ash/wm/window_resizer.h"
#include "ash/wm/window_state.h"
#include "ash/wm/window_state_delegate.h"
#include "ash/wm/window_util.h"
#include "base/logging.h"
#include "base/macros.h"
#include "base/memory/ptr_util.h"
#include "base/strings/utf_string_conversions.h"
#include "base/trace_event/trace_event.h"
#include "base/trace_event/trace_event_argument.h"
#include "cc/trees/layer_tree_frame_sink.h"
#include "components/exo/surface.h"
#include "components/exo/wm_helper.h"
#include "services/ui/public/interfaces/window_tree_constants.mojom.h"
#include "ui/aura/client/aura_constants.h"
#include "ui/aura/client/cursor_client.h"
#include "ui/aura/window.h"
#include "ui/aura/window_event_dispatcher.h"
#include "ui/aura/window_targeter.h"
#include "ui/aura/window_tree_host.h"
#include "ui/base/accelerators/accelerator.h"
#include "ui/base/class_property.h"
#include "ui/compositor/compositor.h"
#include "ui/compositor/dip_util.h"
#include "ui/compositor_extra/shadow.h"
#include "ui/display/display.h"
#include "ui/display/screen.h"
#include "ui/gfx/geometry/vector2d_conversions.h"
#include "ui/gfx/path.h"
#include "ui/views/widget/widget.h"
#include "ui/wm/core/coordinate_conversion.h"
#include "ui/wm/core/shadow_controller.h"
#include "ui/wm/core/shadow_types.h"
#include "ui/wm/core/window_animations.h"
#include "ui/wm/core/window_util.h"
namespace exo {
namespace {
DEFINE_LOCAL_UI_CLASS_PROPERTY_KEY(Surface*, kMainSurfaceKey, nullptr)
// Application Id set by the client.
DEFINE_OWNED_UI_CLASS_PROPERTY_KEY(std::string, kApplicationIdKey, nullptr);
// Application Id set by the client.
DEFINE_OWNED_UI_CLASS_PROPERTY_KEY(std::string, kStartupIdKey, nullptr);
// The accelerator keys used to close ShellSurfaces.
const struct {
ui::KeyboardCode keycode;
int modifiers;
} kCloseWindowAccelerators[] = {
{ui::VKEY_W, ui::EF_CONTROL_DOWN},
{ui::VKEY_W, ui::EF_SHIFT_DOWN | ui::EF_CONTROL_DOWN},
{ui::VKEY_F4, ui::EF_ALT_DOWN}};
class ShellSurfaceWidget : public views::Widget {
public:
explicit ShellSurfaceWidget(ShellSurfaceBase* shell_surface)
: shell_surface_(shell_surface) {}
// Overridden from views::Widget:
void Close() override { shell_surface_->Close(); }
void OnKeyEvent(ui::KeyEvent* event) override {
// Handle only accelerators. Do not call Widget::OnKeyEvent that eats focus
// management keys (like the tab key) as well.
if (GetFocusManager()->ProcessAccelerator(ui::Accelerator(*event)))
event->SetHandled();
}
private:
ShellSurfaceBase* const shell_surface_;
DISALLOW_COPY_AND_ASSIGN(ShellSurfaceWidget);
};
class CustomFrameView : public ash::CustomFrameViewAsh {
public:
using ShapeRects = std::vector<gfx::Rect>;
CustomFrameView(views::Widget* widget,
ShellSurfaceBase* shell_surface,
bool enabled,
bool client_controlled_move_resize)
: CustomFrameViewAsh(widget),
shell_surface_(shell_surface),
client_controlled_move_resize_(client_controlled_move_resize) {
SetEnabled(enabled);
SetVisible(enabled);
if (!enabled)
CustomFrameViewAsh::SetShouldPaintHeader(false);
}
~CustomFrameView() override {}
// Overridden from ash::CustomFrameViewAsh:
void SetShouldPaintHeader(bool paint) override {
if (visible()) {
CustomFrameViewAsh::SetShouldPaintHeader(paint);
return;
}
// TODO(oshima): The caption area will be unknown
// if a client draw a caption. (It may not even be
// rectangular). Remove mask.
aura::Window* window = GetWidget()->GetNativeWindow();
ui::Layer* layer = window->layer();
if (paint) {
if (layer->alpha_shape()) {
layer->SetAlphaShape(nullptr);
layer->SetMasksToBounds(false);
}
return;
}
int inset = window->GetProperty(aura::client::kTopViewInset);
if (inset <= 0)
return;
gfx::Rect bound(bounds().size());
bound.Inset(0, inset, 0, 0);
std::unique_ptr<ShapeRects> shape = std::make_unique<ShapeRects>();
shape->push_back(bound);
layer->SetAlphaShape(std::move(shape));
layer->SetMasksToBounds(true);
}
// Overridden from aura::WindowObserver:
void OnWindowBoundsChanged(aura::Window* window,
const gfx::Rect& old_bounds,
const gfx::Rect& new_bounds,
ui::PropertyChangeReason reason) override {
// When window bounds are changed, we need to update the header view so that
// the window mask layer bounds can be set correctly in function
// SetShouldPaintHeader(). Note: this can be removed if the layer mask in
// CustomFrameView becomes unnecessary.
CustomFrameViewAsh::UpdateHeaderView();
}
// Overridden from views::NonClientFrameView:
gfx::Rect GetBoundsForClientView() const override {
if (visible())
return ash::CustomFrameViewAsh::GetBoundsForClientView();
return bounds();
}
gfx::Rect GetWindowBoundsForClientBounds(
const gfx::Rect& client_bounds) const override {
if (visible()) {
return ash::CustomFrameViewAsh::GetWindowBoundsForClientBounds(
client_bounds);
}
return client_bounds;
}
int NonClientHitTest(const gfx::Point& point) override {
if (visible() || !client_controlled_move_resize_)
return ash::CustomFrameViewAsh::NonClientHitTest(point);
return GetWidget()->client_view()->NonClientHitTest(point);
}
void GetWindowMask(const gfx::Size& size, gfx::Path* window_mask) override {
if (visible())
return ash::CustomFrameViewAsh::GetWindowMask(size, window_mask);
}
void ResetWindowControls() override {
if (visible())
return ash::CustomFrameViewAsh::ResetWindowControls();
}
void UpdateWindowIcon() override {
if (visible())
return ash::CustomFrameViewAsh::ResetWindowControls();
}
void UpdateWindowTitle() override {
if (visible())
return ash::CustomFrameViewAsh::UpdateWindowTitle();
}
void SizeConstraintsChanged() override {
if (visible())
return ash::CustomFrameViewAsh::SizeConstraintsChanged();
}
gfx::Size GetMinimumSize() const override {
gfx::Size minimum_size = shell_surface_->GetMinimumSize();
if (visible()) {
return ash::CustomFrameViewAsh::GetWindowBoundsForClientBounds(
gfx::Rect(minimum_size))
.size();
}
return minimum_size;
}
private:
ShellSurfaceBase* const shell_surface_;
// TODO(oshima): Remove this once the transition to new drag/resize
// is complete. https://crbug.com/801666.
const bool client_controlled_move_resize_;
DISALLOW_COPY_AND_ASSIGN(CustomFrameView);
};
class CustomWindowTargeter : public aura::WindowTargeter {
public:
CustomWindowTargeter(views::Widget* widget,
bool client_controlled_move_resize)
: widget_(widget),
client_controlled_move_resize_(client_controlled_move_resize) {}
~CustomWindowTargeter() override {}
// Overridden from aura::WindowTargeter:
bool EventLocationInsideBounds(aura::Window* window,
const ui::LocatedEvent& event) const override {
gfx::Point local_point = event.location();
if (window->parent()) {
aura::Window::ConvertPointToTarget(window->parent(), window,
&local_point);
}
if (IsInResizeHandle(window, event, local_point))
return true;
Surface* surface = ShellSurfaceBase::GetMainSurface(window);
if (!surface)
return false;
int component = widget_->non_client_view()->NonClientHitTest(local_point);
if (component != HTNOWHERE && component != HTCLIENT &&
component != HTBORDER) {
return true;
}
aura::Window::ConvertPointToTarget(window, surface->window(), &local_point);
return surface->HitTest(local_point);
}
private:
bool IsInResizeHandle(aura::Window* window,
const ui::LocatedEvent& event,
const gfx::Point& local_point) const {
if (window != widget_->GetNativeWindow() ||
!widget_->widget_delegate()->CanResize()) {
return false;
}
// Use ash's resize handle detection logic if
// a) ClientControlledShellSurface uses server side resize or
// b) xdg shell is using the server side decoration.
if (ash::wm::GetWindowState(widget_->GetNativeWindow())
->allow_set_bounds_direct()
? client_controlled_move_resize_
: !widget_->non_client_view()->frame_view()->visible()) {
return false;
}
ui::EventTarget* parent =
static_cast<ui::EventTarget*>(window)->GetParentTarget();
if (parent) {
aura::WindowTargeter* parent_targeter =
static_cast<aura::WindowTargeter*>(parent->GetEventTargeter());
if (parent_targeter) {
gfx::Rect mouse_rect;
gfx::Rect touch_rect;
if (parent_targeter->GetHitTestRects(window, &mouse_rect,
&touch_rect)) {
const gfx::Vector2d offset = -window->bounds().OffsetFromOrigin();
mouse_rect.Offset(offset);
touch_rect.Offset(offset);
if (event.IsTouchEvent() || event.IsGestureEvent()
? touch_rect.Contains(local_point)
: mouse_rect.Contains(local_point)) {
return true;
}
}
}
}
return false;
}
views::Widget* const widget_;
const bool client_controlled_move_resize_;
DISALLOW_COPY_AND_ASSIGN(CustomWindowTargeter);
};
// A place holder to disable default implementation created by
// ash::CustomFrameViewAsh, which triggers immersive fullscreen etc, which
// we don't need.
class CustomWindowStateDelegate : public ash::wm::WindowStateDelegate {
public:
CustomWindowStateDelegate() {}
~CustomWindowStateDelegate() override {}
// Overridden from ash::wm::WindowStateDelegate:
bool ToggleFullscreen(ash::wm::WindowState* window_state) override {
return false;
}
bool RestoreAlwaysOnTop(ash::wm::WindowState* window_state) override {
return false;
}
private:
DISALLOW_COPY_AND_ASSIGN(CustomWindowStateDelegate);
};
} // namespace
// Surface state associated with each configure request.
struct ShellSurfaceBase::Config {
Config(uint32_t serial,
const gfx::Vector2d& origin_offset,
int resize_component,
std::unique_ptr<ui::CompositorLock> compositor_lock);
~Config();
uint32_t serial;
gfx::Vector2d origin_offset;
int resize_component;
std::unique_ptr<ui::CompositorLock> compositor_lock;
};
////////////////////////////////////////////////////////////////////////////////
// ShellSurfaceBase, Config:
ShellSurfaceBase::Config::Config(
uint32_t serial,
const gfx::Vector2d& origin_offset,
int resize_component,
std::unique_ptr<ui::CompositorLock> compositor_lock)
: serial(serial),
origin_offset(origin_offset),
resize_component(resize_component),
compositor_lock(std::move(compositor_lock)) {}
ShellSurfaceBase::Config::~Config() {}
////////////////////////////////////////////////////////////////////////////////
// ShellSurfaceBase, ScopedConfigure:
ShellSurfaceBase::ScopedConfigure::ScopedConfigure(
ShellSurfaceBase* shell_surface,
bool force_configure)
: shell_surface_(shell_surface), force_configure_(force_configure) {
// ScopedConfigure instances cannot be nested.
DCHECK(!shell_surface_->scoped_configure_);
shell_surface_->scoped_configure_ = this;
}
ShellSurfaceBase::ScopedConfigure::~ScopedConfigure() {
DCHECK_EQ(shell_surface_->scoped_configure_, this);
shell_surface_->scoped_configure_ = nullptr;
if (needs_configure_ || force_configure_)
shell_surface_->Configure();
// ScopedConfigure instance might have suppressed a widget bounds update.
if (shell_surface_->widget_) {
shell_surface_->UpdateWidgetBounds();
shell_surface_->UpdateShadow();
}
}
////////////////////////////////////////////////////////////////////////////////
// ShellSurfaceBase, public:
ShellSurfaceBase::ShellSurfaceBase(Surface* surface,
const gfx::Point& origin,
bool activatable,
bool can_minimize,
int container)
: SurfaceTreeHost("ExoShellSurfaceHost"),
origin_(origin),
container_(container),
activatable_(activatable),
can_minimize_(can_minimize) {
WMHelper::GetInstance()->AddActivationObserver(this);
surface->AddSurfaceObserver(this);
SetRootSurface(surface);
host_window()->Show();
set_owned_by_client();
}
ShellSurfaceBase::~ShellSurfaceBase() {
DCHECK(!scoped_configure_);
if (resizer_)
EndDrag(false /* revert */);
// Remove activation observer before hiding widget to prevent it from
// casuing the configure callback to be called.
WMHelper::GetInstance()->RemoveActivationObserver(this);
if (widget_) {
widget_->GetNativeWindow()->RemoveObserver(this);
// Remove transient children so they are not automatically destroyed.
for (auto* child : wm::GetTransientChildren(widget_->GetNativeWindow()))
wm::RemoveTransientChild(widget_->GetNativeWindow(), child);
if (widget_->IsVisible())
widget_->Hide();
widget_->CloseNow();
}
if (parent_)
parent_->RemoveObserver(this);
if (root_surface())
root_surface()->RemoveSurfaceObserver(this);
}
void ShellSurfaceBase::AcknowledgeConfigure(uint32_t serial) {
TRACE_EVENT1("exo", "ShellSurfaceBase::AcknowledgeConfigure", "serial",
serial);
// Apply all configs that are older or equal to |serial|. The result is that
// the origin of the main surface will move and the resize direction will
// change to reflect the acknowledgement of configure request with |serial|
// at the next call to Commit().
while (!pending_configs_.empty()) {
std::unique_ptr<Config> config = std::move(pending_configs_.front());
pending_configs_.pop_front();
// Add the config offset to the accumulated offset that will be applied when
// Commit() is called.
pending_origin_offset_ += config->origin_offset;
// Set the resize direction that will be applied when Commit() is called.
pending_resize_component_ = config->resize_component;
if (config->serial == serial)
break;
}
if (widget_) {
UpdateWidgetBounds();
UpdateShadow();
}
}
void ShellSurfaceBase::Activate() {
TRACE_EVENT0("exo", "ShellSurfaceBase::Activate");
if (!widget_ || widget_->IsActive())
return;
widget_->Activate();
}
void ShellSurfaceBase::SetTitle(const base::string16& title) {
TRACE_EVENT1("exo", "ShellSurfaceBase::SetTitle", "title",
base::UTF16ToUTF8(title));
title_ = title;
if (widget_)
widget_->UpdateWindowTitle();
}
void ShellSurfaceBase::SetIcon(const gfx::ImageSkia& icon) {
TRACE_EVENT0("exo", "ShellSurfaceBase::SetIcon");
icon_ = icon;
if (widget_)
widget_->UpdateWindowIcon();
}
void ShellSurfaceBase::SetSystemModal(bool system_modal) {
// System modal container is used by clients to implement client side
// managed system modal dialogs using a single ShellSurface instance.
// Hit-test region will be non-empty when at least one dialog exists on
// the client side. Here we detect the transition between no client side
// dialog and at least one dialog so activatable state is properly
// updated.
if (container_ != ash::kShellWindowId_SystemModalContainer) {
LOG(ERROR)
<< "Only a window in SystemModalContainer can change the modality";
return;
}
if (system_modal == system_modal_)
return;
bool non_system_modal_window_was_active =
!system_modal_ && widget_ && widget_->IsActive();
system_modal_ = system_modal;
if (widget_) {
UpdateSystemModal();
// Deactivate to give the focus back to normal windows.
if (!system_modal_ && !non_system_modal_window_was_active_) {
widget_->Deactivate();
}
}
non_system_modal_window_was_active_ = non_system_modal_window_was_active;
}
void ShellSurfaceBase::Move() {
TRACE_EVENT0("exo", "ShellSurfaceBase::Move");
if (!widget_)
return;
AttemptToStartDrag(HTCAPTION);
}
void ShellSurfaceBase::UpdateSystemModal() {
DCHECK(widget_);
DCHECK_EQ(container_, ash::kShellWindowId_SystemModalContainer);
widget_->GetNativeWindow()->SetProperty(
aura::client::kModalKey,
system_modal_ ? ui::MODAL_TYPE_SYSTEM : ui::MODAL_TYPE_NONE);
}
// static
void ShellSurfaceBase::SetApplicationId(aura::Window* window,
const base::Optional<std::string>& id) {
TRACE_EVENT1("exo", "ShellSurfaceBase::SetApplicationId", "application_id",
id ? *id : "null");
if (id)
window->SetProperty(kApplicationIdKey, new std::string(*id));
else
window->ClearProperty(kApplicationIdKey);
}
// static
const std::string* ShellSurfaceBase::GetApplicationId(
const aura::Window* window) {
return window->GetProperty(kApplicationIdKey);
}
void ShellSurfaceBase::SetApplicationId(const char* application_id) {
// Store the value in |application_id_| in case the window does not exist yet.
if (application_id)
application_id_ = std::string(application_id);
else
application_id_.reset();
if (widget_ && widget_->GetNativeWindow())
SetApplicationId(widget_->GetNativeWindow(), application_id_);
}
// static
void ShellSurfaceBase::SetStartupId(aura::Window* window,
const base::Optional<std::string>& id) {
TRACE_EVENT1("exo", "ShellSurfaceBase::SetStartupId", "startup_id",
id ? *id : "null");
if (id)
window->SetProperty(kStartupIdKey, new std::string(*id));
else
window->ClearProperty(kStartupIdKey);
}
// static
const std::string* ShellSurfaceBase::GetStartupId(aura::Window* window) {
return window->GetProperty(kStartupIdKey);
}
void ShellSurfaceBase::SetStartupId(const char* startup_id) {
// Store the value in |startup_id_| in case the window does not exist yet.
if (startup_id)
startup_id_ = std::string(startup_id);
else
startup_id_.reset();
if (widget_ && widget_->GetNativeWindow())
SetStartupId(widget_->GetNativeWindow(), startup_id_);
}
void ShellSurfaceBase::Close() {
if (!close_callback_.is_null())
close_callback_.Run();
}
void ShellSurfaceBase::SetGeometry(const gfx::Rect& geometry) {
TRACE_EVENT1("exo", "ShellSurfaceBase::SetGeometry", "geometry",
geometry.ToString());
if (geometry.IsEmpty()) {
DLOG(WARNING) << "Surface geometry must be non-empty";
return;
}
pending_geometry_ = geometry;
}
void ShellSurfaceBase::SetOrigin(const gfx::Point& origin) {
TRACE_EVENT1("exo", "ShellSurfaceBase::SetOrigin", "origin",
origin.ToString());
origin_ = origin;
}
void ShellSurfaceBase::SetActivatable(bool activatable) {
TRACE_EVENT1("exo", "ShellSurfaceBase::SetActivatable", "activatable",
activatable);
activatable_ = activatable;
}
void ShellSurfaceBase::SetContainer(int container) {
TRACE_EVENT1("exo", "ShellSurfaceBase::SetContainer", "container", container);
container_ = container;
}
void ShellSurfaceBase::SetMaximumSize(const gfx::Size& size) {
TRACE_EVENT1("exo", "ShellSurfaceBase::SetMaximumSize", "size",
size.ToString());
pending_maximum_size_ = size;
}
void ShellSurfaceBase::SetMinimumSize(const gfx::Size& size) {
TRACE_EVENT1("exo", "ShellSurfaceBase::SetMinimumSize", "size",
size.ToString());
pending_minimum_size_ = size;
}
void ShellSurfaceBase::SetCanMinimize(bool can_minimize) {
TRACE_EVENT1("exo", "ShellSurfaceBase::SetCanMinimize", "can_minimize",
can_minimize);
can_minimize_ = can_minimize;
}
void ShellSurfaceBase::DisableMovement() {
movement_disabled_ = true;
if (widget_)
widget_->set_movement_disabled(true);
}
// static
void ShellSurfaceBase::SetMainSurface(aura::Window* window, Surface* surface) {
window->SetProperty(kMainSurfaceKey, surface);
}
// static
Surface* ShellSurfaceBase::GetMainSurface(const aura::Window* window) {
return window->GetProperty(kMainSurfaceKey);
}
std::unique_ptr<base::trace_event::TracedValue>
ShellSurfaceBase::AsTracedValue() const {
std::unique_ptr<base::trace_event::TracedValue> value(
new base::trace_event::TracedValue());
value->SetString("title", base::UTF16ToUTF8(title_));
if (GetWidget() && GetWidget()->GetNativeWindow()) {
const std::string* application_id =
GetApplicationId(GetWidget()->GetNativeWindow());
if (application_id)
value->SetString("application_id", *application_id);
const std::string* startup_id =
GetStartupId(GetWidget()->GetNativeWindow());
if (startup_id)
value->SetString("startup_id", *startup_id);
}
return value;
}
////////////////////////////////////////////////////////////////////////////////
// SurfaceDelegate overrides:
void ShellSurfaceBase::OnSurfaceCommit() {
// SetShadowBounds requires synchronizing shadow bounds with the next frame,
// so submit the next frame to a new surface and let the host window use the
// new surface.
if (shadow_bounds_changed_)
host_window()->AllocateLocalSurfaceId();
SurfaceTreeHost::OnSurfaceCommit();
if (enabled() && !widget_) {
// Defer widget creation until surface contains some contents.
if (host_window()->bounds().IsEmpty()) {
Configure();
return;
}
CreateShellSurfaceWidget(ui::SHOW_STATE_NORMAL);
}
// Apply the accumulated pending origin offset to reflect acknowledged
// configure requests.
origin_offset_ += pending_origin_offset_;
pending_origin_offset_ = gfx::Vector2d();
// Update resize direction to reflect acknowledged configure requests.
resize_component_ = pending_resize_component_;
// Apply new window geometry.
geometry_ = pending_geometry_;
// Apply new minimum/maximium size.
bool size_constraint_changed = minimum_size_ != pending_minimum_size_ ||
maximum_size_ != pending_maximum_size_;
minimum_size_ = pending_minimum_size_;
maximum_size_ = pending_maximum_size_;
if (widget_) {
UpdateWidgetBounds();
UpdateShadow();
// System modal container is used by clients to implement overlay
// windows using a single ShellSurface instance. If hit-test
// region is empty, then it is non interactive window and won't be
// activated.
if (container_ == ash::kShellWindowId_SystemModalContainer) {
// Prevent window from being activated when hit test region is empty.
bool activatable = activatable_ && HasHitTestRegion();
if (activatable != CanActivate()) {
set_can_activate(activatable);
// Activate or deactivate window if activation state changed.
if (activatable) {
// Automatically activate only if the window is modal.
// Non modal window should be activated by a user action.
// TODO(oshima): Non modal system window does not have an associated
// task ID, and as a result, it cannot be activated from client side.
// Fix this (b/65460424) and remove this if condition.
if (system_modal_)
wm::ActivateWindow(widget_->GetNativeWindow());
} else if (widget_->IsActive()) {
wm::DeactivateWindow(widget_->GetNativeWindow());
}
}
}
UpdateSurfaceBounds();
// Show widget if needed.
if (pending_show_widget_) {
DCHECK(!widget_->IsClosed());
DCHECK(!widget_->IsVisible());
pending_show_widget_ = false;
widget_->Show();
if (container_ == ash::kShellWindowId_SystemModalContainer)
UpdateSystemModal();
}
}
SubmitCompositorFrame();
if (size_constraint_changed)
widget_->OnSizeConstraintsChanged();
}
bool ShellSurfaceBase::IsInputEnabled(Surface*) const {
return true;
}
void ShellSurfaceBase::OnSetFrame(SurfaceFrameType frame_type) {
bool frame_was_disabled = !frame_enabled();
frame_type_ = frame_type;
switch (frame_type) {
case SurfaceFrameType::NONE:
shadow_bounds_.reset();
break;
case SurfaceFrameType::NORMAL:
case SurfaceFrameType::AUTOHIDE:
case SurfaceFrameType::OVERLAY:
// Initialize the shadow if it didn't exist. Do not reset if
// the frame type just switched from another enabled type.
if (!shadow_bounds_ || frame_was_disabled)
shadow_bounds_ = gfx::Rect();
break;
case SurfaceFrameType::SHADOW:
shadow_bounds_ = gfx::Rect();
break;
}
if (!widget_)
return;
CustomFrameView* frame_view =
static_cast<CustomFrameView*>(widget_->non_client_view()->frame_view());
if (frame_view->enabled() == frame_enabled())
return;
frame_view->SetEnabled(frame_enabled());
frame_view->SetVisible(frame_enabled());
frame_view->SetShouldPaintHeader(frame_enabled());
frame_view->SetHeaderHeight(base::nullopt);
widget_->GetRootView()->Layout();
// TODO(oshima): We probably should wait applying these if the
// window is animating.
UpdateWidgetBounds();
UpdateSurfaceBounds();
}
void ShellSurfaceBase::OnSetFrameColors(SkColor active_color,
SkColor inactive_color) {
has_frame_colors_ = true;
active_frame_color_ = SkColorSetA(active_color, SK_AlphaOPAQUE);
inactive_frame_color_ = SkColorSetA(inactive_color, SK_AlphaOPAQUE);
if (widget_) {
widget_->GetNativeWindow()->SetProperty(ash::kFrameActiveColorKey,
active_frame_color_);
widget_->GetNativeWindow()->SetProperty(ash::kFrameInactiveColorKey,
inactive_frame_color_);
}
}
void ShellSurfaceBase::OnSetParent(Surface* parent,
const gfx::Point& position) {
views::Widget* parent_widget =
parent ? views::Widget::GetTopLevelWidgetForNativeView(parent->window())
: nullptr;
if (parent_widget) {
// Set parent window if using default container and the container itself
// is not the parent.
if (container_ == ash::kShellWindowId_DefaultContainer)
SetParentWindow(parent_widget->GetNativeWindow());
if (resizer_)
return;
origin_ = position;
views::View::ConvertPointToScreen(
parent_widget->widget_delegate()->GetContentsView(), &origin_);
if (!widget_)
return;
gfx::Rect widget_bounds = widget_->GetWindowBoundsInScreen();
gfx::Rect new_widget_bounds(origin_, widget_bounds.size());
if (new_widget_bounds != widget_bounds) {
base::AutoReset<bool> auto_ignore_window_bounds_changes(
&ignore_window_bounds_changes_, true);
widget_->SetBounds(new_widget_bounds);
UpdateSurfaceBounds();
}
} else {
SetParentWindow(nullptr);
}
}
void ShellSurfaceBase::OnSetStartupId(const char* startup_id) {
SetStartupId(startup_id);
}
void ShellSurfaceBase::OnSetApplicationId(const char* application_id) {
SetApplicationId(application_id);
}
////////////////////////////////////////////////////////////////////////////////
// SurfaceObserver overrides:
void ShellSurfaceBase::OnSurfaceDestroying(Surface* surface) {
DCHECK_EQ(root_surface(), surface);
surface->RemoveSurfaceObserver(this);
SetRootSurface(nullptr);
if (resizer_)
EndDrag(false /* revert */);
if (widget_)
SetMainSurface(widget_->GetNativeWindow(), nullptr);
// Hide widget before surface is destroyed. This allows hide animations to
// run using the current surface contents.
if (widget_) {
// Remove transient children so they are not automatically hidden.
for (auto* child : wm::GetTransientChildren(widget_->GetNativeWindow()))
wm::RemoveTransientChild(widget_->GetNativeWindow(), child);
widget_->Hide();
}
// Note: In its use in the Wayland server implementation, the surface
// destroyed callback may destroy the ShellSurface instance. This call needs
// to be last so that the instance can be destroyed.
if (!surface_destroyed_callback_.is_null())
std::move(surface_destroyed_callback_).Run();
}
////////////////////////////////////////////////////////////////////////////////
// views::WidgetDelegate overrides:
bool ShellSurfaceBase::CanResize() const {
if (movement_disabled_)
return false;
// The shell surface is resizable by default when min/max size is empty,
// othersize it's resizable when min size != max size.
return minimum_size_.IsEmpty() || minimum_size_ != maximum_size_;
}
bool ShellSurfaceBase::CanMaximize() const {
// Shell surfaces in system modal container cannot be maximized.
if (container_ != ash::kShellWindowId_DefaultContainer)
return false;
// Non-transient shell surfaces can be maximized.
return !parent_;
}
bool ShellSurfaceBase::CanMinimize() const {
// Non-transient shell surfaces can be minimized.
return !parent_ && can_minimize_;
}
base::string16 ShellSurfaceBase::GetWindowTitle() const {
if (extra_title_.empty())
return title_;
// TODO(estade): revisit how the extra title is shown in the window frame and
// other surfaces like overview mode.
return title_ + base::ASCIIToUTF16(" (") + extra_title_ +
base::ASCIIToUTF16(")");
}
bool ShellSurfaceBase::ShouldShowWindowTitle() const {
return !extra_title_.empty();
}
gfx::ImageSkia ShellSurfaceBase::GetWindowIcon() {
return icon_;
}
void ShellSurfaceBase::WindowClosing() {
if (resizer_)
EndDrag(true /* revert */);
SetEnabled(false);
widget_ = nullptr;
}
views::Widget* ShellSurfaceBase::GetWidget() {
return widget_;
}
const views::Widget* ShellSurfaceBase::GetWidget() const {
return widget_;
}
views::View* ShellSurfaceBase::GetContentsView() {
return this;
}
views::NonClientFrameView* ShellSurfaceBase::CreateNonClientFrameView(
views::Widget* widget) {
aura::Window* window = widget_->GetNativeWindow();
// ShellSurfaces always use immersive mode.
window->SetProperty(aura::client::kImmersiveFullscreenKey, true);
ash::wm::WindowState* window_state = ash::wm::GetWindowState(window);
if (!frame_enabled() && !window_state->HasDelegate()) {
window_state->SetDelegate(std::make_unique<CustomWindowStateDelegate>());
}
CustomFrameView* frame_view = new CustomFrameView(
widget, this, frame_enabled(), client_controlled_move_resize_);
if (has_frame_colors_)
frame_view->SetFrameColors(active_frame_color_, inactive_frame_color_);
return frame_view;
}
bool ShellSurfaceBase::WidgetHasHitTestMask() const {
return true;
}
void ShellSurfaceBase::GetWidgetHitTestMask(gfx::Path* mask) const {
GetHitTestMask(mask);
gfx::Point origin = host_window()->bounds().origin();
SkMatrix matrix;
float scale = GetScale();
matrix.setScaleTranslate(
SkFloatToScalar(1.0f / scale), SkFloatToScalar(1.0f / scale),
SkIntToScalar(origin.x()), SkIntToScalar(origin.y()));
mask->transform(matrix);
}
////////////////////////////////////////////////////////////////////////////////
// views::Views overrides:
gfx::Size ShellSurfaceBase::CalculatePreferredSize() const {
if (!geometry_.IsEmpty())
return geometry_.size();
return host_window()->bounds().size();
}
gfx::Size ShellSurfaceBase::GetMinimumSize() const {
return minimum_size_.IsEmpty() ? gfx::Size(1, 1) : minimum_size_;
}
gfx::Size ShellSurfaceBase::GetMaximumSize() const {
// On ChromeOS, non empty maximum size will make the window
// non maximizable.
return maximum_size_;
}
////////////////////////////////////////////////////////////////////////////////
// aura::WindowObserver overrides:
void ShellSurfaceBase::OnWindowBoundsChanged(aura::Window* window,
const gfx::Rect& old_bounds,
const gfx::Rect& new_bounds,
ui::PropertyChangeReason reason) {
if (!widget_ || !root_surface() || ignore_window_bounds_changes_)
return;
if (window == widget_->GetNativeWindow()) {
if (new_bounds.size() == old_bounds.size())
return;
// If size changed then give the client a chance to produce new contents
// before origin on screen is changed. Retain the old origin by reverting
// the origin delta until the next configure is acknowledged.
gfx::Vector2d delta = new_bounds.origin() - old_bounds.origin();
origin_offset_ -= delta;
pending_origin_offset_accumulator_ += delta;
UpdateSurfaceBounds();
// The shadow size may be updated to match the widget. Change it back
// to the shadow content size. Note that this relies on wm::ShadowController
// being notified of the change before |this|.
UpdateShadow();
Configure();
}
}
void ShellSurfaceBase::OnWindowDestroying(aura::Window* window) {
if (window == parent_) {
parent_ = nullptr;
// |parent_| being set to null effects the ability to maximize the window.
if (widget_)
widget_->OnSizeConstraintsChanged();
}
window->RemoveObserver(this);
}
////////////////////////////////////////////////////////////////////////////////
// wm::ActivationChangeObserver overrides:
void ShellSurfaceBase::OnWindowActivated(ActivationReason reason,
aura::Window* gained_active,
aura::Window* lost_active) {
if (!widget_)
return;
if (gained_active == widget_->GetNativeWindow() ||
lost_active == widget_->GetNativeWindow()) {
DCHECK(activatable_);
Configure();
UpdateShadow();
}
}
////////////////////////////////////////////////////////////////////////////////
// ui::EventHandler overrides:
void ShellSurfaceBase::OnKeyEvent(ui::KeyEvent* event) {
if (!resizer_) {
views::View::OnKeyEvent(event);
return;
}
if (event->type() == ui::ET_KEY_PRESSED &&
event->key_code() == ui::VKEY_ESCAPE) {
EndDrag(true /* revert */);
}
}
////////////////////////////////////////////////////////////////////////////////
// ui::EventHandler overrides:
void ShellSurfaceBase::OnMouseEvent(ui::MouseEvent* event) {
if (!resizer_) {
views::View::OnMouseEvent(event);
return;
}
if (event->handled())
return;
if ((event->flags() &
(ui::EF_MIDDLE_MOUSE_BUTTON | ui::EF_RIGHT_MOUSE_BUTTON)) != 0)
return;
if (event->type() == ui::ET_MOUSE_CAPTURE_CHANGED) {
// We complete the drag instead of reverting it, as reverting it will
// result in a weird behavior when a client produces a modal dialog
// while the drag is in progress.
EndDrag(false /* revert */);
return;
}
switch (event->type()) {
case ui::ET_MOUSE_DRAGGED: {
if (OnMouseDragged(*event))
event->StopPropagation();
break;
}
case ui::ET_MOUSE_RELEASED: {
ScopedConfigure scoped_configure(this, false);
EndDrag(false /* revert */);
break;
}
case ui::ET_MOUSE_MOVED:
case ui::ET_MOUSE_PRESSED:
case ui::ET_MOUSE_ENTERED:
case ui::ET_MOUSE_EXITED:
case ui::ET_MOUSEWHEEL:
case ui::ET_MOUSE_CAPTURE_CHANGED:
break;
default:
NOTREACHED();
break;
}
}
void ShellSurfaceBase::OnGestureEvent(ui::GestureEvent* event) {
if (!resizer_) {
views::View::OnGestureEvent(event);
return;
}
if (event->handled())
return;
// TODO(domlaskowski): Handle touch dragging/resizing. See crbug.com/738606.
switch (event->type()) {
case ui::ET_GESTURE_END: {
ScopedConfigure scoped_configure(this, false);
EndDrag(false /* revert */);
break;
}
case ui::ET_GESTURE_SCROLL_BEGIN:
case ui::ET_GESTURE_SCROLL_END:
case ui::ET_GESTURE_SCROLL_UPDATE:
case ui::ET_GESTURE_TAP:
case ui::ET_GESTURE_TAP_DOWN:
case ui::ET_GESTURE_TAP_CANCEL:
case ui::ET_GESTURE_TAP_UNCONFIRMED:
case ui::ET_GESTURE_DOUBLE_TAP:
case ui::ET_GESTURE_BEGIN:
case ui::ET_GESTURE_TWO_FINGER_TAP:
case ui::ET_GESTURE_PINCH_BEGIN:
case ui::ET_GESTURE_PINCH_END:
case ui::ET_GESTURE_PINCH_UPDATE:
case ui::ET_GESTURE_LONG_PRESS:
case ui::ET_GESTURE_LONG_TAP:
case ui::ET_GESTURE_SWIPE:
case ui::ET_GESTURE_SHOW_PRESS:
case ui::ET_SCROLL:
case ui::ET_SCROLL_FLING_START:
case ui::ET_SCROLL_FLING_CANCEL:
break;
default:
NOTREACHED();
break;
}
}
////////////////////////////////////////////////////////////////////////////////
// ui::AcceleratorTarget overrides:
bool ShellSurfaceBase::AcceleratorPressed(const ui::Accelerator& accelerator) {
for (const auto& entry : kCloseWindowAccelerators) {
if (ui::Accelerator(entry.keycode, entry.modifiers) == accelerator) {
if (!close_callback_.is_null())
close_callback_.Run();
return true;
}
}
return views::View::AcceleratorPressed(accelerator);
}
////////////////////////////////////////////////////////////////////////////////
// ShellSurfaceBase, protected:
void ShellSurfaceBase::CreateShellSurfaceWidget(
ui::WindowShowState show_state) {
DCHECK(enabled());
DCHECK(!widget_);
views::Widget::InitParams params;
params.type = views::Widget::InitParams::TYPE_WINDOW;
params.ownership = views::Widget::InitParams::NATIVE_WIDGET_OWNS_WIDGET;
params.delegate = this;
params.shadow_type = views::Widget::InitParams::SHADOW_TYPE_NONE;
params.opacity = views::Widget::InitParams::TRANSLUCENT_WINDOW;
params.show_state = show_state;
// Make shell surface a transient child if |parent_| has been set.
params.parent =
parent_ ? parent_
: WMHelper::GetInstance()->GetPrimaryDisplayContainer(container_);
params.bounds = gfx::Rect(origin_, gfx::Size());
bool activatable = activatable_;
// ShellSurfaces in system modal container are only activatable if input
// region is non-empty. See OnCommitSurface() for more details.
if (container_ == ash::kShellWindowId_SystemModalContainer)
activatable &= HasHitTestRegion();
params.activatable = activatable ? views::Widget::InitParams::ACTIVATABLE_YES
: views::Widget::InitParams::ACTIVATABLE_NO;
// Note: NativeWidget owns this widget.
widget_ = new ShellSurfaceWidget(this);
widget_->Init(params);
aura::Window* window = widget_->GetNativeWindow();
window->SetName("ExoShellSurface");
window->SetProperty(aura::client::kAccessibilityFocusFallsbackToWidgetKey,
false);
window->AddChild(host_window());
// Use DESCENDANTS_ONLY event targeting policy for mus/mash.
// TODO(https://crbug.com/839521): Revisit after event dispatching code is
// changed for mus/mash.
window->SetEventTargetingPolicy(
ash::Shell::GetAshConfig() == ash::Config::CLASSIC
? ui::mojom::EventTargetingPolicy::TARGET_AND_DESCENDANTS
: ui::mojom::EventTargetingPolicy::DESCENDANTS_ONLY);
window->SetEventTargeter(base::WrapUnique(
new CustomWindowTargeter(widget_, client_controlled_move_resize_)));
SetApplicationId(window, application_id_);
SetStartupId(window, startup_id_);
SetMainSurface(window, root_surface());
// Start tracking changes to window bounds and window state.
window->AddObserver(this);
ash::wm::WindowState* window_state = ash::wm::GetWindowState(window);
InitializeWindowState(window_state);
// AutoHide shelf in fullscreen state.
window_state->SetHideShelfWhenFullscreen(false);
// Fade visibility animations for non-activatable windows.
if (!activatable_) {
wm::SetWindowVisibilityAnimationType(
window, wm::WINDOW_VISIBILITY_ANIMATION_TYPE_FADE);
}
// Register close window accelerators.
views::FocusManager* focus_manager = widget_->GetFocusManager();
for (const auto& entry : kCloseWindowAccelerators) {
focus_manager->RegisterAccelerator(
ui::Accelerator(entry.keycode, entry.modifiers),
ui::AcceleratorManager::kNormalPriority, this);
}
// Show widget next time Commit() is called.
pending_show_widget_ = true;
}
void ShellSurfaceBase::Configure() {
// Delay configure callback if |scoped_configure_| is set.
if (scoped_configure_) {
scoped_configure_->set_needs_configure();
return;
}
gfx::Vector2d origin_offset = pending_origin_offset_accumulator_;
pending_origin_offset_accumulator_ = gfx::Vector2d();
int resize_component = HTCAPTION;
if (widget_) {
ash::wm::WindowState* window_state =
ash::wm::GetWindowState(widget_->GetNativeWindow());
// If surface is being resized, save the resize direction.
if (window_state->is_dragged())
resize_component = window_state->drag_details()->window_component;
}
uint32_t serial = 0;
if (!configure_callback_.is_null()) {
if (widget_) {
const views::NonClientView* non_client_view = widget_->non_client_view();
serial = configure_callback_.Run(
non_client_view->frame_view()->GetBoundsForClientView().size(),
ash::wm::GetWindowState(widget_->GetNativeWindow())->GetStateType(),
IsResizing(), widget_->IsActive(), origin_offset);
} else {
serial = configure_callback_.Run(gfx::Size(),
ash::mojom::WindowStateType::NORMAL,
false, false, origin_offset);
}
}
if (!serial) {
pending_origin_offset_ += origin_offset;
pending_resize_component_ = resize_component;
return;
}
// Apply origin offset and resize component at the first Commit() after this
// configure request has been acknowledged.
pending_configs_.push_back(
std::make_unique<Config>(serial, origin_offset, resize_component,
std::move(configure_compositor_lock_)));
LOG_IF(WARNING, pending_configs_.size() > 100)
<< "Number of pending configure acks for shell surface has reached: "
<< pending_configs_.size();
}
bool ShellSurfaceBase::IsResizing() const {
ash::wm::WindowState* window_state =
ash::wm::GetWindowState(widget_->GetNativeWindow());
if (!window_state->is_dragged())
return false;
return window_state->drag_details()->bounds_change &
ash::WindowResizer::kBoundsChange_Resizes;
}
void ShellSurfaceBase::UpdateWidgetBounds() {
DCHECK(widget_);
aura::Window* window = widget_->GetNativeWindow();
ash::wm::WindowState* window_state = ash::wm::GetWindowState(window);
// Return early if the shell is currently managing the bounds of the widget.
if (!window_state->allow_set_bounds_direct()) {
// 1) When a window is either maximized/fullscreen/pinned.
if (window_state->IsMaximizedOrFullscreenOrPinned())
return;
// 2) When a window is snapped.
if (window_state->IsSnapped())
return;
// 3) When a window is being interactively resized.
if (IsResizing())
return;
// 4) When a window's bounds are being animated.
if (window->layer()->GetAnimator()->IsAnimatingProperty(
ui::LayerAnimationElement::BOUNDS))
return;
}
// Return early if there is pending configure requests.
if (!pending_configs_.empty() || scoped_configure_)
return;
gfx::Rect new_widget_bounds = GetWidgetBounds();
// Set |ignore_window_bounds_changes_| as this change to window bounds
// should not result in a configure request.
DCHECK(!ignore_window_bounds_changes_);
ignore_window_bounds_changes_ = true;
if (new_widget_bounds != widget_->GetWindowBoundsInScreen())
SetWidgetBounds(new_widget_bounds);
ignore_window_bounds_changes_ = false;
}
void ShellSurfaceBase::SetWidgetBounds(const gfx::Rect& bounds) {
widget_->SetBounds(bounds);
UpdateSurfaceBounds();
}
void ShellSurfaceBase::UpdateSurfaceBounds() {
gfx::Point origin = widget_->non_client_view()
->frame_view()
->GetBoundsForClientView()
.origin();
origin += GetSurfaceOrigin().OffsetFromOrigin();
origin -= ToFlooredVector2d(ScaleVector2d(
root_surface_origin().OffsetFromOrigin(), 1.f / GetScale()));
host_window()->SetBounds(gfx::Rect(origin, host_window()->bounds().size()));
// The host window might have not been added to the widget yet.
if (host_window()->parent()) {
ui::SnapLayerToPhysicalPixelBoundary(widget_->GetNativeWindow()->layer(),
host_window()->layer());
}
}
void ShellSurfaceBase::UpdateShadow() {
if (!widget_ || !root_surface())
return;
shadow_bounds_changed_ = false;
aura::Window* window = widget_->GetNativeWindow();
if (!shadow_bounds_) {
wm::SetShadowElevation(window, wm::kShadowElevationNone);
} else {
wm::SetShadowElevation(window, wm::kShadowElevationDefault);
ui::Shadow* shadow = wm::ShadowController::GetShadowForWindow(window);
// Maximized/Fullscreen window does not create a shadow.
if (!shadow)
return;
shadow->SetContentBounds(GetShadowBounds());
// Surfaces that can't be activated are usually menus and tooltips. Use a
// small style shadow for them.
if (!activatable_)
shadow->SetElevation(wm::kShadowElevationMenuOrTooltip);
// We don't have rounded corners unless frame is enabled.
if (!frame_enabled())
shadow->SetRoundedCornerRadius(0);
}
}
gfx::Rect ShellSurfaceBase::GetVisibleBounds() const {
// Use |geometry_| if set, otherwise use the visual bounds of the surface.
if (!geometry_.IsEmpty())
return geometry_;
return root_surface() ? gfx::Rect(root_surface()->content_size())
: gfx::Rect();
}
gfx::Point ShellSurfaceBase::GetMouseLocation() const {
aura::Window* const root_window = widget_->GetNativeWindow()->GetRootWindow();
gfx::Point location =
root_window->GetHost()->dispatcher()->GetLastMouseLocationInRoot();
aura::Window::ConvertPointToTarget(
root_window, widget_->GetNativeWindow()->parent(), &location);
return location;
}
gfx::Rect ShellSurfaceBase::GetShadowBounds() const {
return shadow_bounds_->IsEmpty()
? gfx::Rect(widget_->GetNativeWindow()->bounds().size())
: gfx::ScaleToEnclosedRect(*shadow_bounds_, 1.f / GetScale());
}
////////////////////////////////////////////////////////////////////////////////
// ShellSurfaceBase, private:
float ShellSurfaceBase::GetScale() const {
return 1.f;
}
aura::Window* ShellSurfaceBase::GetDragWindow() {
return movement_disabled_ ? nullptr : widget_->GetNativeWindow();
}
std::unique_ptr<ash::WindowResizer> ShellSurfaceBase::CreateWindowResizer(
aura::Window* window,
int component) {
// Set the cursor before calling CreateWindowResizer, as that will
// eventually call LockCursor and prevent the cursor from changing.
aura::client::CursorClient* cursor_client =
aura::client::GetCursorClient(window->GetRootWindow());
if (!cursor_client)
return nullptr;
switch (component) {
case HTCAPTION:
cursor_client->SetCursor(ui::CursorType::kPointer);
break;
case HTTOP:
cursor_client->SetCursor(ui::CursorType::kNorthResize);
break;
case HTTOPRIGHT:
cursor_client->SetCursor(ui::CursorType::kNorthEastResize);
break;
case HTRIGHT:
cursor_client->SetCursor(ui::CursorType::kEastResize);
break;
case HTBOTTOMRIGHT:
cursor_client->SetCursor(ui::CursorType::kSouthEastResize);
break;
case HTBOTTOM:
cursor_client->SetCursor(ui::CursorType::kSouthResize);
break;
case HTBOTTOMLEFT:
cursor_client->SetCursor(ui::CursorType::kSouthWestResize);
break;
case HTLEFT:
cursor_client->SetCursor(ui::CursorType::kWestResize);
break;
case HTTOPLEFT:
cursor_client->SetCursor(ui::CursorType::kNorthWestResize);
break;
default:
NOTREACHED();
break;
}
std::unique_ptr<ash::WindowResizer> resizer = ash::CreateWindowResizer(
window, GetMouseLocation(), component, wm::WINDOW_MOVE_SOURCE_MOUSE);
if (!resizer)
return nullptr;
// Apply pending origin offsets and resize direction before starting a
// new resize operation. These can still be pending if the client has
// acknowledged the configure request but has not yet committed.
origin_offset_ += pending_origin_offset_;
pending_origin_offset_ = gfx::Vector2d();
resize_component_ = pending_resize_component_;
return resizer;
}
bool ShellSurfaceBase::OnMouseDragged(const ui::MouseEvent& event) {
gfx::Point location(event.location());
aura::Window::ConvertPointToTarget(widget_->GetNativeWindow(),
widget_->GetNativeWindow()->parent(),
&location);
ScopedConfigure scoped_configure(this, false);
resizer_->Drag(location, event.flags());
return true;
}
void ShellSurfaceBase::AttemptToStartDrag(int component) {
DCHECK(widget_);
// Cannot start another drag if one is already taking place.
if (resizer_)
return;
aura::Window* window = GetDragWindow();
if (!window || window->HasCapture())
return;
resizer_ = CreateWindowResizer(window, component);
if (!resizer_)
return;
WMHelper::GetInstance()->AddPreTargetHandler(this);
window->SetCapture();
// Notify client that resizing state has changed.
if (IsResizing())
Configure();
}
void ShellSurfaceBase::EndDrag(bool revert) {
DCHECK(widget_);
DCHECK(resizer_);
aura::Window* window = GetDragWindow();
DCHECK(window);
DCHECK(window->HasCapture());
bool was_resizing = IsResizing();
if (revert)
resizer_->RevertDrag();
else
resizer_->CompleteDrag();
WMHelper::GetInstance()->RemovePreTargetHandler(this);
window->ReleaseCapture();
resizer_.reset();
// Notify client that resizing state has changed.
if (was_resizing)
Configure();
UpdateWidgetBounds();
}
gfx::Rect ShellSurfaceBase::GetWidgetBounds() const {
gfx::Rect visible_bounds = GetVisibleBounds();
gfx::Rect new_widget_bounds =
widget_->non_client_view()->GetWindowBoundsForClientBounds(
visible_bounds);
if (movement_disabled_) {
new_widget_bounds.set_origin(origin_);
} else if (resize_component_ == HTCAPTION) {
// Preserve widget position.
new_widget_bounds.set_origin(widget_->GetWindowBoundsInScreen().origin());
} else {
// Compute widget origin using surface origin if the current location of
// surface is being anchored to one side of the widget as a result of a
// resize operation.
gfx::Rect visible_bounds = GetVisibleBounds();
gfx::Point origin = GetSurfaceOrigin() + visible_bounds.OffsetFromOrigin();
wm::ConvertPointToScreen(widget_->GetNativeWindow(), &origin);
new_widget_bounds.set_origin(origin);
}
return new_widget_bounds;
}
gfx::Point ShellSurfaceBase::GetSurfaceOrigin() const {
DCHECK(!movement_disabled_ || resize_component_ == HTCAPTION);
gfx::Rect visible_bounds = GetVisibleBounds();
gfx::Rect client_bounds =
widget_->non_client_view()->frame_view()->GetBoundsForClientView();
switch (resize_component_) {
case HTCAPTION:
return gfx::Point() + origin_offset_ - visible_bounds.OffsetFromOrigin();
case HTBOTTOM:
case HTRIGHT:
case HTBOTTOMRIGHT:
return gfx::Point() - visible_bounds.OffsetFromOrigin();
case HTTOP:
case HTTOPRIGHT:
return gfx::Point(0, client_bounds.height() - visible_bounds.height()) -
visible_bounds.OffsetFromOrigin();
case HTLEFT:
case HTBOTTOMLEFT:
return gfx::Point(client_bounds.width() - visible_bounds.width(), 0) -
visible_bounds.OffsetFromOrigin();
case HTTOPLEFT:
return gfx::Point(client_bounds.width() - visible_bounds.width(),
client_bounds.height() - visible_bounds.height()) -
visible_bounds.OffsetFromOrigin();
default:
NOTREACHED();
return gfx::Point();
}
}
void ShellSurfaceBase::SetParentWindow(aura::Window* parent) {
if (parent_) {
parent_->RemoveObserver(this);
if (widget_)
wm::RemoveTransientChild(parent_, widget_->GetNativeWindow());
}
parent_ = parent;
if (parent_) {
parent_->AddObserver(this);
if (widget_)
wm::AddTransientChild(parent_, widget_->GetNativeWindow());
}
// If |parent_| is set effects the ability to maximize the window.
if (widget_)
widget_->OnSizeConstraintsChanged();
}
} // namespace exo
| 32.678747 | 80 | 0.679442 | zipated |
e3d8ca87b7ffd8735aa24d0b5e6d7f87e6cae262 | 5,434 | cc | C++ | drivers/bluetooth/lib/l2cap/pdu.cc | kong1191/garnet | 609c727895e477ac086db38c1cee654dc10f2008 | [
"BSD-3-Clause"
] | null | null | null | drivers/bluetooth/lib/l2cap/pdu.cc | kong1191/garnet | 609c727895e477ac086db38c1cee654dc10f2008 | [
"BSD-3-Clause"
] | null | null | null | drivers/bluetooth/lib/l2cap/pdu.cc | kong1191/garnet | 609c727895e477ac086db38c1cee654dc10f2008 | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2017 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "pdu.h"
#include "garnet/drivers/bluetooth/lib/common/log.h"
#include "garnet/drivers/bluetooth/lib/hci/acl_data_packet.h"
namespace btlib {
namespace l2cap {
PDU::Reader::Reader(const PDU* pdu)
: offset_(sizeof(BasicHeader)),
frag_offset_(sizeof(BasicHeader)),
pdu_(pdu) {
ZX_DEBUG_ASSERT(pdu_);
ZX_DEBUG_ASSERT(pdu_->is_valid());
cur_fragment_ = pdu_->fragments_.cbegin();
}
bool PDU::Reader::ReadNext(size_t size, const ReadFunc& func) {
ZX_DEBUG_ASSERT(func);
if (!size)
return false;
if (cur_fragment_ == pdu_->fragments_.cend() ||
offset_ + size > pdu_->length() + sizeof(BasicHeader)) {
return false;
}
// Return a view to avoid copying if the fragment boundary is not being
// crossed.
size_t frag_size = cur_fragment_->view().payload_size();
if (frag_offset_ + size <= frag_size) {
auto data_view =
cur_fragment_->view().payload_data().view(frag_offset_, size);
offset_ += size;
frag_offset_ += size;
if (frag_offset_ == frag_size) {
frag_offset_ = 0u;
++cur_fragment_;
}
func(data_view);
return true;
}
// TODO(armansito): This will work fine for small sizes but we'll need to
// dynamically allocate for packets that are large. Fix this once L2CAP slab
// allocators have been wired up.
if (size > 1024) {
bt_log(WARN, "l2cap", "need to dynamically allocate buffer (size: %zu)",
size);
return false;
}
uint8_t buffer[size];
common::MutableBufferView out(buffer, size);
size_t remaining = size;
while (cur_fragment_ != pdu_->fragments_.cend() && remaining) {
// Calculate how much to copy from the current fragment.
auto payload = cur_fragment_->view().payload_data();
size_t copy_size = std::min(payload.size() - frag_offset_, remaining);
out.Write(payload.data() + frag_offset_, copy_size, size - remaining);
offset_ += copy_size;
frag_offset_ += copy_size;
remaining -= copy_size;
// Reset fragment offset if we processed an entire fragment.
ZX_DEBUG_ASSERT(frag_offset_ <= payload.size());
if (frag_offset_ == payload.size()) {
frag_offset_ = 0u;
++cur_fragment_;
}
}
func(out);
return true;
}
PDU::PDU() : fragment_count_(0u) {}
// NOTE: The order in which these are initialized matters, as
// other.ReleaseFragments() resets |other.fragment_count_|.
PDU::PDU(PDU&& other)
: fragment_count_(other.fragment_count_),
fragments_(other.ReleaseFragments()) {}
PDU& PDU::operator=(PDU&& other) {
// NOTE: The order in which these are initialized matters, as
// other.ReleaseFragments() resets |other.fragment_count_|.
fragment_count_ = other.fragment_count_;
fragments_ = other.ReleaseFragments();
return *this;
}
size_t PDU::Copy(common::MutableByteBuffer* out_buffer, size_t pos,
size_t size) const {
ZX_DEBUG_ASSERT(out_buffer);
ZX_DEBUG_ASSERT(pos < length());
ZX_DEBUG_ASSERT(is_valid());
size_t remaining = std::min(size, length() - pos);
ZX_DEBUG_ASSERT(out_buffer->size() >= remaining);
bool found = false;
size_t offset = 0u;
for (auto iter = fragments_.begin(); iter != fragments_.end() && remaining;
++iter) {
auto payload = iter->view().payload_data();
// Skip the Basic L2CAP header for the first fragment.
if (iter == fragments_.begin()) {
payload = payload.view(sizeof(BasicHeader));
}
// We first find the beginning fragment based on |pos|.
if (!found) {
size_t fragment_size = payload.size();
if (pos >= fragment_size) {
pos -= fragment_size;
continue;
}
// The beginning fragment has been found.
found = true;
}
// Calculate how much to read from the current fragment
size_t write_size = std::min(payload.size() - pos, remaining);
// Read the fragment into out_buffer->mutable_data() + offset.
out_buffer->Write(payload.data() + pos, write_size, offset);
// Clear |pos| after using it on the first fragment as all successive
// fragments are read from the beginning.
if (pos)
pos = 0u;
offset += write_size;
remaining -= write_size;
}
return offset;
}
const common::BufferView PDU::ViewFirstFragment(size_t size) const {
ZX_DEBUG_ASSERT(is_valid());
return fragments_.begin()->view().payload_data().view(sizeof(BasicHeader),
size);
}
PDU::FragmentList PDU::ReleaseFragments() {
auto out_list = std::move(fragments_);
fragment_count_ = 0u;
ZX_DEBUG_ASSERT(!is_valid());
return out_list;
}
const BasicHeader& PDU::basic_header() const {
ZX_DEBUG_ASSERT(!fragments_.is_empty());
const auto& fragment = *fragments_.begin();
ZX_DEBUG_ASSERT(fragment.packet_boundary_flag() !=
hci::ACLPacketBoundaryFlag::kContinuingFragment);
return fragment.view().payload<BasicHeader>();
}
void PDU::AppendFragment(hci::ACLDataPacketPtr fragment) {
ZX_DEBUG_ASSERT(fragment);
ZX_DEBUG_ASSERT(!is_valid() || fragments_.begin()->connection_handle() ==
fragment->connection_handle());
fragments_.push_back(std::move(fragment));
fragment_count_++;
}
} // namespace l2cap
} // namespace btlib
| 29.215054 | 78 | 0.667464 | kong1191 |
e3deaf89af220730a8d634c149ac01b7ac64f888 | 1,215 | cpp | C++ | SPOJ/BLINNET.cpp | Alipashaimani/Competitive-programming | 5d55567b71ea61e69a6450cda7323c41956d3cb9 | [
"MIT"
] | null | null | null | SPOJ/BLINNET.cpp | Alipashaimani/Competitive-programming | 5d55567b71ea61e69a6450cda7323c41956d3cb9 | [
"MIT"
] | null | null | null | SPOJ/BLINNET.cpp | Alipashaimani/Competitive-programming | 5d55567b71ea61e69a6450cda7323c41956d3cb9 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
#define F first
#define S second
const int MAX = 10001;
vector< pair< int, pair<int , int > > > adj;
int parent[MAX];
int find(int u);
int main() {
int t;
cin >> t;
while(t--) {
int n;
cin >> n;
adj.clear();
for (int i = 1; i <= n; i++) {
int weight, k , v;
string X;
cin >> X >> k;
parent[i] = i;
while(k--) {
cin >> v >> weight;
if(v > i)
adj.push_back({weight,{i, v}});
}
}
sort(adj.begin(), adj.end());
int cost = 0;
for (int i = 0; i < adj.size(); i++){
int x,y,z;
x = find(adj[i].S.F);
y = find(adj[i].S.S);
z = adj[i].F;
if(x != y){
cost += z;
parent[x] = y;
}
}
cout << cost << '\n' ;
}
return 0;
}
int find(int u){
if(u != parent[u])
parent[u] = find(parent[u]);
return parent[u];
}
| 17.608696 | 51 | 0.33251 | Alipashaimani |
e3df2d2d575b18eab4fb98cd299cba8372dc9e0a | 860 | cpp | C++ | ProfilerHost/MetadataRegistry.cpp | varunramc/clr-profiling | 461a9dc834ad2791c0889a7ec843674a2be2b47c | [
"MIT"
] | 8 | 2018-03-27T09:35:23.000Z | 2022-01-31T06:26:04.000Z | ProfilerHost/MetadataRegistry.cpp | varunramc/clr-profiling | 461a9dc834ad2791c0889a7ec843674a2be2b47c | [
"MIT"
] | 1 | 2018-08-07T11:00:26.000Z | 2020-04-04T12:38:23.000Z | ProfilerHost/MetadataRegistry.cpp | varunramc/clr-profiling | 461a9dc834ad2791c0889a7ec843674a2be2b47c | [
"MIT"
] | 4 | 2018-10-11T17:43:49.000Z | 2021-06-23T06:58:58.000Z | #include "stdafx.h"
#include "MetadataRegistry.h"
MetadataRegistry::MetadataRegistry()
: tokenCounter(0)
{
}
MetadataRegistry::~MetadataRegistry()
{
}
MethodMetadata MetadataRegistry::RegisterMethod(
std::wstring assemblyName,
std::wstring typeName,
std::wstring signature)
{
MethodMetadata metadata;
metadata.token = InterlockedIncrement64((volatile LONG64*)(&this->tokenCounter));
metadata.assemblyName = assemblyName;
metadata.typeName = typeName;
metadata.signature = signature;
this->methodMetadatas.push_back(metadata);
if (this->methodRegistrationCallback)
{
this->methodRegistrationCallback(metadata);
}
return metadata;
}
void MetadataRegistry::SetMethodRegistrationCallback(std::function<void(const MethodMetadata&)> callback)
{
this->methodRegistrationCallback = callback;
}
| 23.243243 | 105 | 0.739535 | varunramc |
e3df90b8594e87e4a78002e94de2534eda4f5abc | 1,368 | cpp | C++ | src/Users/User.cpp | DoStini/FEUP-AEDA-proj | ccd23c1aba4f041ea09cc5f5d75d555d8c1a591a | [
"MIT"
] | null | null | null | src/Users/User.cpp | DoStini/FEUP-AEDA-proj | ccd23c1aba4f041ea09cc5f5d75d555d8c1a591a | [
"MIT"
] | 4 | 2021-01-22T09:26:24.000Z | 2021-02-18T09:57:11.000Z | src/Users/User.cpp | DoStini/FEUP-AEDA-proj | ccd23c1aba4f041ea09cc5f5d75d555d8c1a591a | [
"MIT"
] | null | null | null | //
// Created by andre on 10/17/2020.
//
#include "User.h"
#include "InvalidPassword.h"
#include "StreamZ.h"
#include <utility>
#include "StreamZ.h"
User::User( std::string name, std::string nickName,std::string password, const Date &birthDate) :
name(std::move(name)), nickName(std::move(nickName)),password(std::move(password)), birthDate(birthDate) {
Date currDate; currDate.setSystemDate();
joinedPlatformDate = currDate;
}
User::User(const std::string & nick) : nickName(nick) {}
const std::string &User::getName() const {
return name;
}
const std::string &User::getNickName() const {
return nickName;
}
const Date &User::getBirthDate() const {
return birthDate;
}
const Date &User::getJoinedPlatformDate() const {
return joinedPlatformDate;
}
const std::string &User::getPassword() const {
return password;
}
bool User::changePassword(const std::string& newPassword) {
if(newPassword == password || newPassword.empty()){
return false; // Later throw an exception
}
password = newPassword;
return true;
}
void User::changeName(const std::string & newName) {
name = newName;
}
void User::setStreamZ(StreamZ *streamZ) {
this->streamZ = streamZ;
}
unsigned User::age() const{
Date currDate; currDate.setSystemDate();
return currDate.getYearDifference(birthDate);
}
| 20.117647 | 118 | 0.682749 | DoStini |
e3e26925d34bd5cffa298f585bdd1bb7138735d7 | 976 | cpp | C++ | sources/2020/2020_25.cpp | tbielak/AoC_cpp | 69f36748536e60a1b88f9d44a285feff20df8470 | [
"MIT"
] | 2 | 2021-02-01T13:19:37.000Z | 2021-02-25T10:39:46.000Z | sources/2020/2020_25.cpp | tbielak/AoC_cpp | 69f36748536e60a1b88f9d44a285feff20df8470 | [
"MIT"
] | null | null | null | sources/2020/2020_25.cpp | tbielak/AoC_cpp | 69f36748536e60a1b88f9d44a285feff20df8470 | [
"MIT"
] | null | null | null | #include "2020_24.h"
namespace Day25_2020
{
uintmax_t find_loop_size(uintmax_t key)
{
uintmax_t v = 1;
uintmax_t sn = 7;
uintmax_t i = 0;
while (1)
{
v = (v * sn) % 20201227;
i++;
if (v == key)
return i;
}
}
uintmax_t calculate(uintmax_t key, uintmax_t loop)
{
uintmax_t v = 1;
for (uintmax_t i = 0; i < loop; i++)
v = (v * key) % 20201227;
return v;
}
uintmax_t part_one(uintmax_t card_public_key, uintmax_t door_public_key)
{
return calculate(door_public_key, find_loop_size(card_public_key));
}
t_output main(const t_input& input)
{
uintmax_t card_public_key = stoi(input[0]);
uintmax_t door_public_key = stoi(input[1]);
auto t0 = chrono::steady_clock::now();
auto p1 = part_one(card_public_key, door_public_key);
auto t1 = chrono::steady_clock::now();
vector<string> solutions;
solutions.push_back(to_string(p1));
return make_pair(solutions, chrono::duration<double>((t1 - t0) * 1000).count());
}
}
| 20.765957 | 82 | 0.671107 | tbielak |
e3e395994946d108f173b5a54682b69d9c3f8233 | 10,552 | cpp | C++ | sources/apps/sample_apps/deepstream-transfer-learning-app/capture_time_rules.cpp | mdegans/deepstream-5.1 | 0e3a0bf4aab4bc957f73749d7b8e93c25f384360 | [
"Apache-2.0"
] | 2 | 2021-09-01T00:45:33.000Z | 2021-09-01T23:47:58.000Z | sources/apps/sample_apps/deepstream-transfer-learning-app/capture_time_rules.cpp | mdegans/deepstream-5.1 | 0e3a0bf4aab4bc957f73749d7b8e93c25f384360 | [
"Apache-2.0"
] | 1 | 2022-01-07T05:38:17.000Z | 2022-01-07T05:38:17.000Z | xcore/dsx/ds51/sample_apps/deepstream-transfer-learning-app/capture_time_rules.cpp | baidu-research/hydra-gocean | bbf7e749a995160cf19fe6c91fc06b3cc6f4a8ca | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2020, NVIDIA CORPORATION. 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, 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 <fstream>
#include <sstream>
#include <iomanip>
#include "capture_time_rules.h"
constexpr unsigned seconds_in_day = 86400;
static std::vector<std::string> split_string(const std::string &str, char split_char) {
std::vector<std::string> elems;
std::stringstream ss(str);
std::string item;
while (std::getline(ss, item, split_char))
elems.push_back(item);
return elems;
}
CaptureTimeRules::ParseResult
CaptureTimeRules::stoi_err_handling(unsigned &dst, const std::string &src, unsigned max_bound) {
if (src.empty())
return PARSE_RESULT_EMPTY;
unsigned size_number = 0;
unsigned zeros = 0;
unsigned idx = 0;
while (src[idx] == ' ')
idx++;
while (src[idx] == '0') {
zeros++;
idx++;
}
while (src[idx] >= '0' && src[idx] <= '9') {
size_number++;
idx++;
}
while (src[idx] == ' ')
idx++;
if (src.size() != idx)
return PARSE_RESULT_BAD_CHARS;
if (size_number > 3)
return PARSE_RESULT_OUT_OF_BOUND;
if (size_number == 0 && zeros == 0)
return PARSE_RESULT_BAD_CHARS;
else
dst = std::stoi(src);
if (dst >= max_bound)
return PARSE_RESULT_OUT_OF_BOUND;
return PARSE_RESULT_OK;
}
bool CaptureTimeRules::parsing_contains_error(const std::vector<ParseResult> &parse_res_list,
const std::vector<std::string> &str_list,
const std::string &curr_line,
unsigned int line_number) {
static const std::vector<unsigned> max_time_list = {24, 60, 24, 60, 24, 60, 60};
bool contains_error = false;
std::stringstream ss;
int shift = 0;
for (unsigned i = 0; i < 7; ++i) {
unsigned tab_nb = 0;
for (const auto& elm: str_list[i])
if(elm == '\t')
tab_nb++;
if (parse_res_list[i] == PARSE_RESULT_OK) {
shift += str_list[i].size() + 1;
continue;
}
contains_error = true;
ss << curr_line << " <-- line " << line_number << "\n";
for (int j = 0; j < shift - 1; ++j)
ss << ' ';
if (parse_res_list[i] == PARSE_RESULT_EMPTY)
ss << '^';
else if (shift > 0)
ss << ' ';
for (unsigned k = 0; k < str_list[i].size(); ++k) {
ss << '^';
}
ss << '\n';
for (int j = 0; j < shift; ++j)
ss << ' ';
switch (parse_res_list[i]) {
case PARSE_RESULT_OK: // should not happen
break;
case PARSE_RESULT_BAD_CHARS:
ss << "replace this part by ";
break;
case PARSE_RESULT_OUT_OF_BOUND:
ss << "replace this number by ";
break;
case PARSE_RESULT_EMPTY:
ss << "after that character add ";
break;
}
ss << "a number bounded between 0 (included) and "
<< max_time_list[i] << " (excluded).\n\n";
shift += str_list[i].size() + 1;
}
std::cerr << ss.str();
return contains_error;
}
bool CaptureTimeRules::single_time_rule_parser(const std::string &path, const std::string &line,
unsigned line_number) {
if (line.empty()) {
return true;
}
bool parse_error_line = false;
std::vector<std::string> time1;
std::vector<std::string> time2;
std::vector<std::string> time_to_skip;
do {
auto split_line = split_string(line, ',');
if (split_line.size() != 3) {
parse_error_line = true;
break;
}
time1 = split_string(split_line[0], ':');
if (time1.size() != 2) {
parse_error_line = true;
break;
}
time2 = split_string(split_line[1], ':');
if (time2.size() != 2) {
parse_error_line = true;
break;
}
time_to_skip = split_string(split_line[2], ':');
if (time_to_skip.size() != 3) {
parse_error_line = true;
break;
}
} while (false);
if (parse_error_line) {
std::cerr << "Parsing error " << path << ":" << (line_number) << "\n"
<< line << "\n"
<< "Each line from the second one should have the following format:\n"
<< "<hours>:<minutes>,<hours>:<minutes>,<hours>:<minutes>:<seconds>\n";
return false;
}
unsigned tts_h;
unsigned tts_m;
unsigned tts_s;
TimeRule t;
std::vector<ParseResult> parse_res_list;
parse_res_list.push_back(stoi_err_handling(t.begin_time_hour, time1[0], 24));
parse_res_list.push_back(stoi_err_handling(t.begin_time_minute, time1[1], 60));
parse_res_list.push_back(stoi_err_handling(t.end_time_hour, time2[0], 24));
parse_res_list.push_back(stoi_err_handling(t.end_time_minute, time2[1], 60));
parse_res_list.push_back(stoi_err_handling(tts_h, time_to_skip[0], 24));
parse_res_list.push_back(stoi_err_handling(tts_m, time_to_skip[1], 60));
parse_res_list.push_back(stoi_err_handling(tts_s, time_to_skip[2], 60));
std::vector<std::string> elm_list = {time1[0], time1[1], time2[0], time2[1],
time_to_skip[0], time_to_skip[1], time_to_skip[2]};
if (parsing_contains_error(parse_res_list, elm_list, line, line_number)) {
return false;
}
t.end_time_is_next_day = (t.end_time_hour < t.begin_time_hour
|| (t.end_time_hour == t.begin_time_hour
&& t.end_time_minute <= t.begin_time_minute));
t.interval_between_frame_capture_seconds = ((tts_h * 60) + tts_m) * 60 + tts_s;
rules_.push_back(t);
return true;
}
void CaptureTimeRules::init(const std::string &path, unsigned int default_second_interval) {
default_duration_ = std::chrono::seconds(default_second_interval);
end_of_current_time_interval_ = std::chrono::system_clock::now() - default_duration_;
std::ifstream file(path);
if (!file.good()) {
std::cerr << "Could not open " << path << ".\n";
return;
}
std::string line;
// discarding first line
std::getline(file, line);
bool no_error = true;
unsigned line_number = 2;
while (std::getline(file, line)) {
no_error &= single_time_rule_parser(path, line, line_number);
line_number++;
}
init_ = no_error;
}
CaptureTimeRules::t_duration CaptureTimeRules::getCurrentTimeInterval() {
auto now = std::chrono::system_clock::now();
if (now < end_of_current_time_interval_) {
return current_time_interval_;
}
time_t tt = std::chrono::system_clock::to_time_t(now);
tm local_tm = *localtime(&tt);
for (const auto &elm: rules_) {
if (isInTimeRule(elm, local_tm)) {
local_tm.tm_hour = elm.end_time_hour;
local_tm.tm_min = elm.end_time_minute;
auto tp = std::chrono::system_clock::from_time_t(std::mktime(&local_tm));
if (elm.end_time_is_next_day)
tp += std::chrono::hours(24);
end_of_current_time_interval_ = tp;
current_time_interval_ = std::chrono::seconds(elm.interval_between_frame_capture_seconds);
return current_time_interval_;
}
}
current_time_interval_ = default_duration_;
tm tmp_tm = *localtime(&tt);
t_duration time_diff = std::chrono::seconds(seconds_in_day);
for (const auto &elm: rules_) {
tmp_tm.tm_hour = elm.begin_time_hour;
tmp_tm.tm_min = elm.begin_time_minute;
auto tp = std::chrono::system_clock::from_time_t(std::mktime(&tmp_tm));
if (now > tp)
continue;
t_duration diff = std::chrono::duration_cast<std::chrono::seconds>(tp - now);
if (diff < time_diff)
time_diff = diff;
}
if (time_diff < std::chrono::seconds(seconds_in_day - 1)) {
end_of_current_time_interval_ = now + time_diff;
}
return current_time_interval_;
}
bool CaptureTimeRules::isInTimeRule(const CaptureTimeRules::TimeRule &t, const tm &now) {
unsigned n_h = static_cast<unsigned>(now.tm_hour);
unsigned n_m = static_cast<unsigned>(now.tm_min);
bool is_after_begin = n_h > t.begin_time_hour
|| (n_h == t.begin_time_hour
&& n_m >= t.begin_time_minute);
bool is_before_end = n_h < t.end_time_hour
|| (n_h == t.end_time_hour
&& n_m < t.end_time_minute);
if (!t.end_time_is_next_day)
return is_after_begin && is_before_end;
bool is_after_begin_plus_24 = (n_h + 24) > t.begin_time_hour
|| ((n_h + 24) == t.begin_time_hour
&& n_m >= t.begin_time_minute);
bool is_before_end_plus_24 = n_h < (t.end_time_hour + 24)
|| (n_h == (t.end_time_hour + 24)
&& n_m < t.end_time_minute);
bool next_day_condition = (is_after_begin && is_before_end_plus_24)
|| (is_after_begin_plus_24 && is_before_end);
return next_day_condition;
}
bool CaptureTimeRules::is_init_() {
return init_;
}
| 37.024561 | 102 | 0.589367 | mdegans |
e3e71ac9a0114c2d0e799298dbaf28d42e4e8ffc | 3,205 | cpp | C++ | bindings/python/src/OpenSpaceToolkitAstrodynamicsPy/Trajectory/Orbit/Model.cpp | oygx210/open-space-toolkit-astrodynamics | 81b76d78bbe76719a34801778d4fb685cc67648f | [
"Apache-2.0"
] | 13 | 2020-05-11T02:22:15.000Z | 2022-01-27T09:42:18.000Z | bindings/python/src/OpenSpaceToolkitAstrodynamicsPy/Trajectory/Orbit/Model.cpp | oygx210/open-space-toolkit-astrodynamics | 81b76d78bbe76719a34801778d4fb685cc67648f | [
"Apache-2.0"
] | 10 | 2018-09-11T05:27:04.000Z | 2020-01-06T03:48:28.000Z | bindings/python/src/OpenSpaceToolkitAstrodynamicsPy/Trajectory/Orbit/Model.cpp | open-space-collective/open-space-toolkit-astrodynamics | d709f5237f25e5ef40eafa5f87e39c00b8acbae1 | [
"Apache-2.0"
] | 4 | 2020-03-05T18:19:03.000Z | 2021-06-24T04:25:05.000Z | ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @project Open Space Toolkit ▸ Astrodynamics
/// @file bindings/python/src/OpenSpaceToolkitAstrodynamicsPy/Trajectory/Orbit/Model.cpp
/// @author Lucas Brémond <lucas@loftorbital.com>
/// @license Apache License 2.0
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#include <OpenSpaceToolkit/Astrodynamics/Trajectory/Orbit/Models/SGP4.hpp>
#include <OpenSpaceToolkit/Astrodynamics/Trajectory/Orbit/Models/Kepler.hpp>
#include <OpenSpaceToolkit/Astrodynamics/Trajectory/Orbit/Model.hpp>
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
inline void OpenSpaceToolkitAstrodynamicsPy_Trajectory_Orbit_Model ( pybind11::module& aModule )
{
using namespace pybind11 ;
// using BaseModel = ostk::astro::trajectory::Model ;
using ostk::astro::trajectory::orbit::Model ;
using ostk::astro::trajectory::orbit::models::Kepler ;
using ostk::astro::trajectory::orbit::models::SGP4 ;
// scope in_Model = class_<Model, bases<ostk::astro::trajectory::Model>, boost::noncopyable>("OrbitModel", no_init)
// scope in_Model = class_<Model, bases<ostk::astro::trajectory::Model>>("OrbitModel", no_init)
class_<Model>(aModule, "OrbitModel")
// no init
// .def(self == self)
// .def(self != self)
.def("__eq__", [](const Model &self, const Model &other){ return self == other; })
.def("__ne__", [](const Model &self, const Model &other){ return self != other; })
.def("__str__", &(shiftToString<Model>))
.def("is_defined", &Model::isDefined)
.def("is_kepler", +[] (const Model& aModel) -> bool { return aModel.is<Kepler>() ; })
.def("is_sgp4", +[] (const Model& aModel) -> bool { return aModel.is<SGP4>() ; })
// .def("as_kepler", +[] (const Model& aModel) -> const Kepler& { return aModel.as<Kepler>() ; }, return_value_policy<reference_existing_object>())
// .def("as_sgp4", +[] (const Model& aModel) -> const SGP4& { return aModel.as<SGP4>() ; }, return_value_policy<reference_existing_object>())
.def("as_kepler", +[] (const Model& aModel) -> const Kepler& { return aModel.as<Kepler>() ; }, return_value_policy::reference)
.def("as_sgp4", +[] (const Model& aModel) -> const SGP4& { return aModel.as<SGP4>() ; }, return_value_policy::reference)
.def("get_epoch", &Model::getEpoch)
.def("get_revolution_number_at_epoch", &Model::getRevolutionNumberAtEpoch)
.def("calculate_state_at", &Model::calculateStateAt)
.def("calculate_revolution_number_at", &Model::calculateRevolutionNumberAt)
;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
| 53.416667 | 161 | 0.516381 | oygx210 |
e3e8449efe48fa22a9cd1a203b74a038aa07f0e8 | 3,405 | cpp | C++ | torch_mlu/csrc/aten/operators/cnnl/internal/linspace_internal.cpp | Cambricon/catch | 2625da389f25a67066d20fb6b0c38250ef98f8ab | [
"BSD-2-Clause"
] | 20 | 2022-03-01T11:40:51.000Z | 2022-03-30T08:17:47.000Z | torch_mlu/csrc/aten/operators/cnnl/internal/linspace_internal.cpp | Cambricon/catch | 2625da389f25a67066d20fb6b0c38250ef98f8ab | [
"BSD-2-Clause"
] | null | null | null | torch_mlu/csrc/aten/operators/cnnl/internal/linspace_internal.cpp | Cambricon/catch | 2625da389f25a67066d20fb6b0c38250ef98f8ab | [
"BSD-2-Clause"
] | null | null | null | /*
All modification made by Cambricon Corporation: © 2022 Cambricon Corporation
All rights reserved.
All other contributions:
Copyright (c) 2014--2022, the respective contributors
All rights reserved.
For the list of contributors go to https://github.com/pytorch/pytorch/graphs/contributors
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 Intel Corporation nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL 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.
*/
#include "aten/operators/cnnl/internal/cnnl_internal.h"
namespace torch_mlu {
namespace cnnl {
namespace ops {
template <typename T>
void linspace_kernel(at::Scalar start, at::Scalar end, int64_t steps, at::Tensor& output) {
auto start_val = start.to<T>();
auto end_val = end.to<T>();
auto steps_val = (end_val - start_val) / (steps - 1);
auto end_change = end_val + steps_val;
auto* output_impl = getMluTensorImpl(output);
auto output_ptr = output_impl->cnnlMalloc();
auto handle = getCurrentHandle();
auto output_type = output_impl->getCnnlType();
TORCH_CNNL_CHECK(cnnlArange(handle, static_cast<void*>(&start_val),
static_cast<void*>(&end_change),
static_cast<void*>(&steps_val),
output_type,
output_ptr));
}
at::Tensor cnnl_linspace_internal(at::Tensor& output, at::Scalar start,
at::Scalar end, int64_t steps) {
if (output.numel() != steps) {
output.resize_({steps});
}
if (steps == 0) {
// skip
} else if (steps == 1) {
output.fill_(start);
} else {
if (at::isFloatingType(output.scalar_type())) {
linspace_kernel<float>(start, end, steps, output);
} else if (at::isIntegralType(output.scalar_type())) {
linspace_kernel<int>(start, end, steps, output);
} else {
auto output_float = at::empty(output.sizes(), output.options().dtype(at::kFloat));
linspace_kernel<float>(start, end, steps, output);
cnnl_cast_internal(output_float, output);
}
}
return output;
}
} // namespace ops
} // namespace cnnl
} // namespace torch_mlu
| 42.5625 | 91 | 0.717768 | Cambricon |
e3ece2fa5b3d964b1099df00f727e4f6ac9163c0 | 557 | hpp | C++ | B-OOP-400-LYN-4-1-tekspice/include/Tools.hpp | Neotoxic-off/Epitech2024 | 8b3dd04fa9ac2b7019c0b5b1651975a7252d929b | [
"Apache-2.0"
] | 2 | 2022-02-07T12:44:51.000Z | 2022-02-08T12:04:08.000Z | B-OOP-400-LYN-4-1-tekspice/include/Tools.hpp | Neotoxic-off/Epitech2024 | 8b3dd04fa9ac2b7019c0b5b1651975a7252d929b | [
"Apache-2.0"
] | null | null | null | B-OOP-400-LYN-4-1-tekspice/include/Tools.hpp | Neotoxic-off/Epitech2024 | 8b3dd04fa9ac2b7019c0b5b1651975a7252d929b | [
"Apache-2.0"
] | 1 | 2022-01-23T21:26:06.000Z | 2022-01-23T21:26:06.000Z | #ifndef _TOOLS_HPP_
#define _TOOLS_HPP_
#include <iostream>
#include <sstream>
#include <string>
#include <fstream>
class Tools
{
public:
Tools();
~Tools();
std::string f_line(std::string, int);
int f_count(std::string);
bool check_command(std::string);
int count_char(std::string, char);
int strlen(char *);
char *phase_insert(char *, char);
char **split(std::string, char);
};
#endif /* _TOOLS_HPP_ */ | 21.423077 | 49 | 0.518851 | Neotoxic-off |
e3ef5e373754de7dba0179cef669d8f43bdf3d59 | 1,823 | hpp | C++ | src/engine/processing/PoissonFiller.hpp | kosua20/Rendu | 6b8e730f16658738572bc2f49e08fc4a2c59df07 | [
"MIT"
] | 399 | 2019-05-25T16:05:59.000Z | 2022-03-31T23:38:04.000Z | src/engine/processing/PoissonFiller.hpp | kosua20/Rendu | 6b8e730f16658738572bc2f49e08fc4a2c59df07 | [
"MIT"
] | 3 | 2019-07-23T21:03:33.000Z | 2020-12-14T12:47:51.000Z | src/engine/processing/PoissonFiller.hpp | kosua20/Rendu | 6b8e730f16658738572bc2f49e08fc4a2c59df07 | [
"MIT"
] | 20 | 2019-06-08T17:15:01.000Z | 2022-03-21T11:20:14.000Z | #pragma once
#include "processing/ConvolutionPyramid.hpp"
#include "graphics/Framebuffer.hpp"
#include "resources/ResourcesManager.hpp"
#include "Common.hpp"
/**
\brief Solve a membrane interpolation ("Poisson filling") problem, using a filter as described in Convolution Pyramids, Farbman et al., 2011.
\ingroup Processing
*/
class PoissonFiller {
public:
/** Constructor.
\param width internal processing width
\param height internal processing height
\param downscaling downscaling factor for the internal convolution pyramid resolution
*/
PoissonFiller(unsigned int width, unsigned int height, unsigned int downscaling);
/** Fill black regions of an image in a smooth fashion, first computing its border color before performing filling.
\param texture the GPU ID of the texture
*/
void process(const Texture * texture);
/** Resize the internal buffers.
\param width the new width
\param height the new height
*/
void resize(unsigned int width, unsigned int height);
/** The ID of the texture containing the filled result.
\return the result texture ID.
*/
const Texture * texture() const { return _compo->texture(); }
/** The ID of the texture containing the colored border.
\return the border texture ID.
*/
const Texture * preprocId() const { return _preproc->texture(); }
private:
ConvolutionPyramid _pyramid; ///< The convolution pyramid.
Program * _prepare; ///< Shader to compute the colored border of black regions in the input image.
Program * _composite; ///< Composite the filled field with the input image.
std::unique_ptr<Framebuffer> _preproc; ///< Contains the computed colored border.
std::unique_ptr<Framebuffer> _compo; ///< Contains the composited filled result at input resolution.
int _scale; ///< The downscaling factor.
};
| 36.46 | 141 | 0.740538 | kosua20 |
e3f10b43fdc0dce476b1427b56e9596d234c78db | 4,139 | cpp | C++ | src/task/search/bfs/BFSTaskRMAFetch.cpp | kilel/DGraphMark | e88418340b303434ccc75cd4079115e8d42fbeb5 | [
"Apache-2.0"
] | 1 | 2016-06-17T20:19:34.000Z | 2016-06-17T20:19:34.000Z | src/task/search/bfs/BFSTaskRMAFetch.cpp | kilel/DGraphMark | e88418340b303434ccc75cd4079115e8d42fbeb5 | [
"Apache-2.0"
] | null | null | null | src/task/search/bfs/BFSTaskRMAFetch.cpp | kilel/DGraphMark | e88418340b303434ccc75cd4079115e8d42fbeb5 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2014 Kislitsyn Ilya
*
* 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 <assert.h>
#include "BFSTaskRMAFetch.h"
#include "../../../mpi/RMAWindow.cpp" //to prevent link errors
namespace dgmark {
BFSTaskRMAFetch::BFSTaskRMAFetch(Intracomm *comm) : BFSdgmark(comm)
{
}
BFSTaskRMAFetch::BFSTaskRMAFetch(const BFSTaskRMAFetch& orig) : BFSdgmark(orig.comm)
{
}
BFSTaskRMAFetch::~BFSTaskRMAFetch()
{
}
void BFSTaskRMAFetch::open(Graph *newGraph)
{
SearchTask::open(newGraph);
qWin = new RMAWindow<Vertex>(comm, getQueueSize(), VERTEX_TYPE);
nextQWin = new RMAWindow<Vertex>(comm, getQueueSize(), VERTEX_TYPE);
pWin = new RMAWindow<Vertex>(comm, numLocalVertex, VERTEX_TYPE);
queue = qWin->getData();
nextQueue = nextQWin->getData();
parent = pWin->getData();
}
void BFSTaskRMAFetch::close()
{
qWin->clean();
nextQWin->clean();
pWin->clean();
delete qWin;
delete nextQWin;
delete pWin;
SearchTask::close();
}
string BFSTaskRMAFetch::getName()
{
return "dgmark_BFS_RMA_Fetch";
}
void BFSTaskRMAFetch::swapQueues()
{
//swap RMA windows
RMAWindow<Vertex> *temp = qWin;
qWin = nextQWin;
nextQWin = temp;
BFSdgmark::swapQueues();
}
void BFSTaskRMAFetch::performBFS()
{
for (int node = 0; node < size; ++node) {
if (rank == node) {
performBFSActualStep();
endSynch(BFS_SYNCH_TAG);
} else {
performBFSSynchRMA();
}
comm->Barrier();
}
}
void BFSTaskRMAFetch::performBFSSynchRMA()
{
while (true) {
if (waitSynch(BFS_SYNCH_TAG)) {
pWin->fenceOpen(MODE_NOPUT); //allow read parent
pWin->fenceClose(MODE_NOSTORE);
if (waitSynch(BFS_SYNCH_TAG)) {
pWin->fenceOpen(MODE_NOPUT); //allow to write to the parent
pWin->fenceClose(MODE_NOSTORE);
nextQWin->fenceOpen(MODE_NOPUT); //allow to read queue
nextQWin->fenceClose(MODE_NOSTORE);
nextQWin->fenceOpen(MODE_NOPUT); //allow to put to the queue
nextQWin->fenceClose(MODE_NOSTORE);
}
} else { //if fence is not neaded mode
break;
}
}
}
inline void BFSTaskRMAFetch::processGlobalChild(Vertex currVertex, Vertex child)
{
Vertex childLocal = graph->vertexToLocal(child);
const int childRank = graph->vertexRank(child);
Vertex parentOfChild;
//printf("%d: Getting parent of child\n", rank);
requestSynch(true, BFS_SYNCH_TAG); //fence is needed now
pWin->fenceOpen(MODE_NOPUT);
pWin->get(&parentOfChild, 1, childRank, childLocal);
pWin->fenceClose(0);
//printf("%d: Parent of child is %ld\n", rank, parentOfChild, numLocalVertex);
assert(0 <= parentOfChild && parentOfChild <= graph->numGlobalVertex);
bool isInnerFenceNeeded = (parentOfChild == graph->numGlobalVertex);
requestSynch(isInnerFenceNeeded, BFS_SYNCH_TAG); // call for inner fence if it is needed
if (isInnerFenceNeeded) {
//printf("%d: Putting child to the parent\n", rank);
pWin->fenceOpen(0);
pWin->put(&currVertex, 1, childRank, childLocal);
pWin->fenceClose(MODE_NOSTORE);
//Updating queue
Vertex queueLastIndex;
//printf("%d: Getting last queue index\n", rank);
nextQWin->fenceOpen(MODE_NOPUT);
nextQWin->get(&queueLastIndex, 1, childRank, 0); // get queue[0]
nextQWin->fenceClose(0);
//printf("%d: Last queue index is %ld\n", rank, queueLastIndex);
assert(0 <= queueLastIndex && queueLastIndex <= getQueueSize());
//printf("%d: Updating queue\n", rank);
nextQWin->fenceOpen(0);
nextQWin->put(&childLocal, 1, childRank, ++queueLastIndex);
nextQWin->put(&queueLastIndex, 1, childRank, 0);
nextQWin->fenceClose(MODE_NOSTORE);
}
}
}
| 27.593333 | 90 | 0.691955 | kilel |
e3f35bc6e91ca715d3671d61861844c681de74c2 | 2,109 | cxx | C++ | main/i18npool/source/transliteration/chartonum.cxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 679 | 2015-01-06T06:34:58.000Z | 2022-03-30T01:06:03.000Z | main/i18npool/source/transliteration/chartonum.cxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 102 | 2017-11-07T08:51:31.000Z | 2022-03-17T12:13:49.000Z | main/i18npool/source/transliteration/chartonum.cxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 331 | 2015-01-06T11:40:55.000Z | 2022-03-14T04:07:51.000Z | /**************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_i18npool.hxx"
#define TRANSLITERATION_ALL
#include <chartonum.hxx>
#include <data/numberchar.h>
#include <rtl/ustrbuf.hxx>
using namespace com::sun::star::uno;
using namespace rtl;
namespace com { namespace sun { namespace star { namespace i18n {
#define TRANSLITERATION_CHARTONUM( name ) \
CharToNum##name::CharToNum##name() \
{ \
nNativeNumberMode = 0; \
tableSize = 0; \
implementationName = "com.sun.star.i18n.Transliteration.CharToNum"#name; \
}
TRANSLITERATION_CHARTONUM( Fullwidth)
TRANSLITERATION_CHARTONUM( Lower_zh_CN)
TRANSLITERATION_CHARTONUM( Lower_zh_TW)
TRANSLITERATION_CHARTONUM( Upper_zh_CN)
TRANSLITERATION_CHARTONUM( Upper_zh_TW)
TRANSLITERATION_CHARTONUM( KanjiShort_ja_JP)
TRANSLITERATION_CHARTONUM( KanjiTraditional_ja_JP)
TRANSLITERATION_CHARTONUM( Lower_ko)
TRANSLITERATION_CHARTONUM( Upper_ko)
TRANSLITERATION_CHARTONUM( Hangul_ko)
TRANSLITERATION_CHARTONUM( Indic_ar)
TRANSLITERATION_CHARTONUM( EastIndic_ar)
TRANSLITERATION_CHARTONUM( Indic_hi)
TRANSLITERATION_CHARTONUM( _th)
#undef TRANSLITERATION_CHARTONUM
} } } }
| 34.57377 | 82 | 0.734471 | Grosskopf |
e3fb06bd2f5686d0a607795eb0aebd6a461cff00 | 12,341 | cpp | C++ | Src/MainLib/ExtensionFunctionWrapper.cpp | vinjn/glintercept | f82166d3a774bfb02459f6b3ae2a03d4c9eaf64f | [
"MIT"
] | 468 | 2015-04-13T19:03:57.000Z | 2022-03-23T00:11:24.000Z | Src/MainLib/ExtensionFunctionWrapper.cpp | vinjn/glintercept | f82166d3a774bfb02459f6b3ae2a03d4c9eaf64f | [
"MIT"
] | 12 | 2015-05-25T11:15:21.000Z | 2020-10-26T02:46:50.000Z | Src/MainLib/ExtensionFunctionWrapper.cpp | vinjn/glintercept | f82166d3a774bfb02459f6b3ae2a03d4c9eaf64f | [
"MIT"
] | 67 | 2015-04-22T13:22:48.000Z | 2022-03-05T01:11:02.000Z | /*=============================================================================
GLIntercept - OpenGL intercept/debugging tool
Copyright (C) 2011 Damian Trebilco
Licensed under the MIT license - See Docs\license.txt for details.
=============================================================================*/
#include "ExtensionFunctionWrapper.h"
#include "GLDriver.h"
#include "GLWindows.h"
#include "FunctionParamStore.h"
#include <stdarg.h>
//The driver to log calls by
extern GLDriver glDriver;
USING_ERRORLOG
// Pre-definition of manual override functions
GLfloat GLAPIENTRY glGetPathLengthNV(GLuint path,GLsizei startSegment, GLsizei numSegments);
GLuint64 GLAPIENTRY glGetTextureHandleNV(GLuint texture);
GLuint64 GLAPIENTRY glGetTextureSamplerHandleNV(GLuint texture, GLuint sampler);
GLuint64 GLAPIENTRY glGetImageHandleNV(GLuint texture, GLint level, GLboolean layered, GLint layer, GLenum format);
GLuint64 GLAPIENTRY glGetTextureHandleARB(GLuint texture);
GLuint64 GLAPIENTRY glGetTextureSamplerHandleARB(GLuint texture, GLuint sampler);
GLuint64 GLAPIENTRY glGetImageHandleARB(GLuint texture, GLint level, GLboolean layered, GLint layer, GLenum format);
HGLRC WGLAPIENTRY wglCreateContextAttribsARB(HDC hDC, HGLRC hShareContext, const int *attribList);
// Enum of manual extension wrapped functions
enum ExtensionWrapperFunctions
{
// Manual wrap for glGetPathLengthNV as it returns a float
EWF_GL_GET_PATH_LENGTH_NV = 0,
// Functions that have uint64 return values
EWF_GL_GET_TEXTURE_HANDLE_NV,
EWF_GL_GET_TEXTURE_SAMPLER_HANDLE_NV,
EWF_GL_GET_IMAGE_HANDLE_NV,
EWF_GL_GET_TEXTURE_HANDLE_ARB,
EWF_GL_GET_TEXTURE_SAMPLER_HANDLE_ARB,
EWF_GL_GET_IMAGE_HANDLE_ARB,
EWF_WGL_CREATECONTEXTATTRIBS_ARB,
EWF_MAX
};
// Struct of manual extension points
struct GLExtensions
{
GLfloat (GLAPIENTRY *glGetPathLengthNV) (GLuint path,GLsizei startSegment, GLsizei numSegments);
GLuint64 (GLAPIENTRY *glGetTextureHandleNV) (GLuint texture);
GLuint64 (GLAPIENTRY *glGetTextureSamplerHandleNV) (GLuint texture, GLuint sampler);
GLuint64 (GLAPIENTRY *glGetImageHandleNV) (GLuint texture, GLint level, GLboolean layered, GLint layer, GLenum format);
GLuint64 (GLAPIENTRY *glGetTextureHandleARB) (GLuint texture);
GLuint64 (GLAPIENTRY *glGetTextureSamplerHandleARB) (GLuint texture, GLuint sampler);
GLuint64 (GLAPIENTRY *glGetImageHandleARB) (GLuint texture, GLint level, GLboolean layered, GLint layer, GLenum format);
HGLRC (WGLAPIENTRY *wglCreateContextAttribsARB) (HDC hDC, HGLRC hShareContext, const int *attribList);
};
GLExtensions GLEXT =
{
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
};
// Helper class to manage manual overrides
struct ManualExtension
{
ManualExtension(const char * a_name, void * a_wrapPtr, void ** a_extFunction)
: m_index(0)
, m_name(a_name)
, m_wrapPtr(a_wrapPtr)
, m_extFunction(a_extFunction)
{
}
uint m_index; //!< The registered function index
const char * m_name; //!< The name of the function
void * m_wrapPtr; //!< The manual function extension wrapper
void ** m_extFunction; //!< Pointer to where the extension called function is stored
};
static ManualExtension s_manualExtensions[EWF_MAX] =
{
ManualExtension("glGetPathLengthNV", (void*)glGetPathLengthNV, (void**)&GLEXT.glGetPathLengthNV),
ManualExtension("glGetTextureHandleNV", (void*)glGetTextureHandleNV, (void**)&GLEXT.glGetTextureHandleNV),
ManualExtension("glGetTextureSamplerHandleNV", (void*)glGetTextureSamplerHandleNV, (void**)&GLEXT.glGetTextureSamplerHandleNV),
ManualExtension("glGetImageHandleNV", (void*)glGetImageHandleNV, (void**)&GLEXT.glGetImageHandleNV),
ManualExtension("glGetTextureHandleARB", (void*)glGetTextureHandleARB, (void**)&GLEXT.glGetTextureHandleARB),
ManualExtension("glGetTextureSamplerHandleARB", (void*)glGetTextureSamplerHandleARB, (void**)&GLEXT.glGetTextureSamplerHandleARB),
ManualExtension("glGetImageHandleARB", (void*)glGetImageHandleARB, (void**)&GLEXT.glGetImageHandleARB),
ManualExtension("wglCreateContextAttribsARB", (void*)wglCreateContextAttribsARB, (void**)&GLEXT.wglCreateContextAttribsARB),
};
///////////////////////////////////////////////////////////////////////////////
//
GLfloat GLAPIENTRY glGetPathLengthNV(GLuint path,GLsizei startSegment, GLsizei numSegments)
{
uint funcIndex = s_manualExtensions[EWF_GL_GET_PATH_LENGTH_NV].m_index;
#ifdef OS_ARCH_x86
glDriver.LogFunctionPre (funcIndex,FunctionArgs((char*)&path));
#elif defined(OS_ARCH_x64)
FunctionParamStore localParamStore = FunctionParamStore(path, startSegment, numSegments);
glDriver.LogFunctionPre (funcIndex, FunctionArgs((char *)&localParamStore.m_paramStore[0]));
#else
#error Unknown platform
#endif
// Call the real method
GLfloat retValue = GLEXT.glGetPathLengthNV(path, startSegment, numSegments);
glDriver.LogFunctionPost(funcIndex,FunctionRetValue((void*)0,retValue));
return retValue;
}
///////////////////////////////////////////////////////////////////////////////
//
GLuint64 GLAPIENTRY glGetTextureHandleNV(GLuint texture)
{
uint funcIndex = s_manualExtensions[EWF_GL_GET_TEXTURE_HANDLE_NV].m_index;
#ifdef OS_ARCH_x86
glDriver.LogFunctionPre (funcIndex,FunctionArgs((char*)&texture));
#elif defined(OS_ARCH_x64)
FunctionParamStore localParamStore = FunctionParamStore(texture);
glDriver.LogFunctionPre (funcIndex, FunctionArgs((char *)&localParamStore.m_paramStore[0]));
#else
#error Unknown platform
#endif
// Call the real method
GLuint64 retValue = GLEXT.glGetTextureHandleNV(texture);
glDriver.LogFunctionPost(funcIndex,FunctionRetValue(retValue));
return retValue;
}
///////////////////////////////////////////////////////////////////////////////
//
GLuint64 GLAPIENTRY glGetTextureSamplerHandleNV(GLuint texture, GLuint sampler)
{
uint funcIndex = s_manualExtensions[EWF_GL_GET_TEXTURE_SAMPLER_HANDLE_NV].m_index;
#ifdef OS_ARCH_x86
glDriver.LogFunctionPre (funcIndex,FunctionArgs((char*)&texture));
#elif defined(OS_ARCH_x64)
FunctionParamStore localParamStore = FunctionParamStore(texture, sampler);
glDriver.LogFunctionPre (funcIndex, FunctionArgs((char *)&localParamStore.m_paramStore[0]));
#else
#error Unknown platform
#endif
// Call the real method
GLuint64 retValue = GLEXT.glGetTextureSamplerHandleNV(texture, sampler);
glDriver.LogFunctionPost(funcIndex,FunctionRetValue(retValue));
return retValue;
}
///////////////////////////////////////////////////////////////////////////////
//
GLuint64 GLAPIENTRY glGetImageHandleNV(GLuint texture, GLint level, GLboolean layered, GLint layer, GLenum format)
{
uint funcIndex = s_manualExtensions[EWF_GL_GET_IMAGE_HANDLE_NV].m_index;
#ifdef OS_ARCH_x86
glDriver.LogFunctionPre (funcIndex,FunctionArgs((char*)&texture));
#elif defined(OS_ARCH_x64)
FunctionParamStore localParamStore = FunctionParamStore(texture, level, layered, layer, format);
glDriver.LogFunctionPre (funcIndex, FunctionArgs((char *)&localParamStore.m_paramStore[0]));
#else
#error Unknown platform
#endif
// Call the real method
GLuint64 retValue = GLEXT.glGetImageHandleNV(texture, level, layered, layer, format);
glDriver.LogFunctionPost(funcIndex,FunctionRetValue(retValue));
return retValue;
}
///////////////////////////////////////////////////////////////////////////////
//
GLuint64 GLAPIENTRY glGetTextureHandleARB(GLuint texture)
{
uint funcIndex = s_manualExtensions[EWF_GL_GET_TEXTURE_HANDLE_ARB].m_index;
#ifdef OS_ARCH_x86
glDriver.LogFunctionPre (funcIndex,FunctionArgs((char*)&texture));
#elif defined(OS_ARCH_x64)
FunctionParamStore localParamStore = FunctionParamStore(texture);
glDriver.LogFunctionPre (funcIndex, FunctionArgs((char *)&localParamStore.m_paramStore[0]));
#else
#error Unknown platform
#endif
// Call the real method
GLuint64 retValue = GLEXT.glGetTextureHandleARB(texture);
glDriver.LogFunctionPost(funcIndex,FunctionRetValue(retValue));
return retValue;
}
///////////////////////////////////////////////////////////////////////////////
//
GLuint64 GLAPIENTRY glGetTextureSamplerHandleARB(GLuint texture, GLuint sampler)
{
uint funcIndex = s_manualExtensions[EWF_GL_GET_TEXTURE_SAMPLER_HANDLE_ARB].m_index;
#ifdef OS_ARCH_x86
glDriver.LogFunctionPre (funcIndex,FunctionArgs((char*)&texture));
#elif defined(OS_ARCH_x64)
FunctionParamStore localParamStore = FunctionParamStore(texture, sampler);
glDriver.LogFunctionPre (funcIndex, FunctionArgs((char *)&localParamStore.m_paramStore[0]));
#else
#error Unknown platform
#endif
// Call the real method
GLuint64 retValue = GLEXT.glGetTextureSamplerHandleARB(texture, sampler);
glDriver.LogFunctionPost(funcIndex,FunctionRetValue(retValue));
return retValue;
}
///////////////////////////////////////////////////////////////////////////////
//
GLuint64 GLAPIENTRY glGetImageHandleARB(GLuint texture, GLint level, GLboolean layered, GLint layer, GLenum format)
{
uint funcIndex = s_manualExtensions[EWF_GL_GET_IMAGE_HANDLE_ARB].m_index;
#ifdef OS_ARCH_x86
glDriver.LogFunctionPre (funcIndex,FunctionArgs((char*)&texture));
#elif defined(OS_ARCH_x64)
FunctionParamStore localParamStore = FunctionParamStore(texture, level, layered, layer, format);
glDriver.LogFunctionPre (funcIndex, FunctionArgs((char *)&localParamStore.m_paramStore[0]));
#else
#error Unknown platform
#endif
// Call the real method
GLuint64 retValue = GLEXT.glGetImageHandleARB(texture, level, layered, layer, format);
glDriver.LogFunctionPost(funcIndex,FunctionRetValue(retValue));
return retValue;
}
///////////////////////////////////////////////////////////////////////////////
//
HGLRC WGLAPIENTRY wglCreateContextAttribsARB(HDC hDC, HGLRC hShareContext, const int *attribList)
{
uint funcIndex = s_manualExtensions[EWF_WGL_CREATECONTEXTATTRIBS_ARB].m_index;
#ifdef OS_ARCH_x86
glDriver.LogFunctionPre (funcIndex,FunctionArgs((char*)&hDC));
#elif defined(OS_ARCH_x64)
FunctionParamStore localParamStore = FunctionParamStore(hDC, hShareContext, attribList);
glDriver.LogFunctionPre (funcIndex, FunctionArgs((char *)&localParamStore.m_paramStore[0]));
#else
#error Unknown platform
#endif
// Call the real method
HGLRC retValue = GLEXT.wglCreateContextAttribsARB(hDC, hShareContext, attribList);
glDriver.LogFunctionPost(funcIndex,FunctionRetValue(retValue));
//Create our driver context
if(retValue != NULL && glDriver.GetFunctionCallDepth() == 0)
{
glDriver.CreateOpenGLContext(retValue);
}
return retValue;
}
///////////////////////////////////////////////////////////////////////////////
//
ExtensionFunctionWrapper::ExtensionFunctionWrapper(FunctionTable * functionTable):
functionTable(functionTable)
{
}
///////////////////////////////////////////////////////////////////////////////
//
ExtensionFunctionWrapper::~ExtensionFunctionWrapper()
{
}
///////////////////////////////////////////////////////////////////////////////
//
bool ExtensionFunctionWrapper::IsManualWrapFunction(const string & funcName)
{
// Loop for all registered functions
for(uint i = 0; i < EWF_MAX; i++)
{
// If matching, return true
if(funcName == s_manualExtensions[i].m_name)
{
return true;
}
}
return false;
}
///////////////////////////////////////////////////////////////////////////////
//
void * ExtensionFunctionWrapper::AddFunctionWrap(const string & funcName,void * functionPtr)
{
// Find the index of the function
for(uint i = 0; i < EWF_MAX; i++)
{
// If matching, return true
if(funcName == s_manualExtensions[i].m_name)
{
// Get the return pointer
void * retPtr = s_manualExtensions[i].m_wrapPtr;
// Get the pointer to the place where the internal call is stored (so it can be overwritten if necessary)
void ** wrapDataFunc = s_manualExtensions[i].m_extFunction;
// Store the function pointer
*wrapDataFunc = functionPtr;
//Add the data to the table and get the index
int funcIndex = functionTable->AddFunction(funcName, retPtr, functionPtr, wrapDataFunc, false);
// Assign the new function index
s_manualExtensions[i].m_index = funcIndex;
return retPtr;
}
}
return NULL;
}
| 32.734748 | 132 | 0.704481 | vinjn |
e3feed3e7e64309efcf1cac87b03a060c0ee7d56 | 2,004 | hpp | C++ | core/base/log.hpp | bartbalaz/gentroller | b40c4fb5661619e9540f0d4b88f6f22aafb9156c | [
"BSD-3-Clause"
] | null | null | null | core/base/log.hpp | bartbalaz/gentroller | b40c4fb5661619e9540f0d4b88f6f22aafb9156c | [
"BSD-3-Clause"
] | null | null | null | core/base/log.hpp | bartbalaz/gentroller | b40c4fb5661619e9540f0d4b88f6f22aafb9156c | [
"BSD-3-Clause"
] | null | null | null | #ifndef BX_LOG_HPP
#define BX_LOG_HPP
#include <string>
#include <vector>
#include <fstream>
#include <error.h>
#include "parameters.hpp"
#include "exception.hpp"
namespace Bx {
namespace Base {
class Log {
public:
typedef enum {
ftl = 0,
err = 1,
wrn = 2,
inf = 3,
dbg = 4
} logLevel_t;
static void level(const char* logLevel);
static void level(std::string& logLevel);
static void level(logLevel_t logLevel);
inline static logLevel_t level() { return _logInstance._logLevel; };
static void file(std::string& name);
static void file(const char* name);
static void log(logLevel_t logLevel, int error, const char* pFileName,
const int lineNum, const char* pFormat, ...);
static std::string& logLevelHelp();
static std::string& defaultLogLevel();
private:
enum {
core_msg_size = 100
};
Log();
~Log();
static Log _logInstance;
static std::vector<std::string> _levelVec;
static std::string _logLevelHelp;
static std::string _defaultLogLevel;
std::ofstream _logFile;
logLevel_t _logLevel;
};
}
}
#define LOG_DBG Bx::Base::Log::dbg
#define LOG_INF Bx::Base::Log::inf
#define LOG_WRN Bx::Base::Log::wrn
#define LOG_ERR Bx::Base::Log::err
#define LOG_FTL Bx::Base::Log::ftl
#define BX_LOG(LVL, ARGS...) \
if (LVL <= Bx::Base::Log::level()) { Bx::Base::Log::log(LVL, \
-1, __FILE__, __LINE__, ARGS); }
#define BX_LOG_E(LVL, ARGS...) \
if (LVL <= Bx::Base::Log::level()) { Bx::Base::Log::log(LVL, \
errno, __FILE__, __LINE__, ARGS); }
#define BX_LOG_EX(EXCEPTION) \
Bx::Base::Log::log(LOG_FTL, -1, __FILE__, __LINE__, \
EXCEPTION.what());
#define BX_LOG_E_EX(EXCEPTION) \
Bx::Base::Log::log(LOG_FTL, errno, __FILE__, __LINE__, \
EXCEPTION.what());
#endif /* BX_LOG_HPP */
| 21.319149 | 78 | 0.590319 | bartbalaz |
54067ea9bf250b02ae2deff7bb0ec787e23771cd | 1,512 | cpp | C++ | cpp/day7/day7.cpp | calewis/advent-of-code21 | a4efc4c551122c1a48f334c7ead237919586de35 | [
"MIT"
] | null | null | null | cpp/day7/day7.cpp | calewis/advent-of-code21 | a4efc4c551122c1a48f334c7ead237919586de35 | [
"MIT"
] | null | null | null | cpp/day7/day7.cpp | calewis/advent-of-code21 | a4efc4c551122c1a48f334c7ead237919586de35 | [
"MIT"
] | null | null | null | #include <fmt/core.h>
#include <fmt/ranges.h>
#include <algorithm>
#include <array>
#include <fstream>
#include <iostream>
#include <numeric>
#include <sstream>
#include <string>
#include <vector>
auto parseFile(char const *file_name) {
auto file = std::ifstream(file_name);
std::string line;
std::getline(file, line);
std::transform(line.begin(), line.end(), line.begin(),
[](char &c) { return c == ',' ? ' ' : c; });
std::stringstream ss(line);
std::vector<std::uint16_t> out;
int num = 0;
while (ss >> num) {
out.push_back(num);
}
return out;
}
int main(int _, char **argv) {
auto crabs = parseFile(argv[1]);
fmt::print("Input: {}\n", fmt::join(crabs, ", "));
// Is this the bounds?
auto [min_it, max_it] = std::minmax_element(crabs.begin(), crabs.end());
auto best = std::numeric_limits<std::size_t>::max();
for(auto i = *min_it; i <= *max_it; ++i){
auto score = 0UL;
for(auto c : crabs){
if(c > i){
score += c - i;
} else {
score += i - c;
}
}
best = std::min(best, score);
}
fmt::print("Part 1 best fuel usage: {}\n", best);
best = std::numeric_limits<std::size_t>::max();
for(auto i = *min_it; i <= *max_it; ++i){
auto score = 0UL;
for(auto c : crabs){
auto dist = (c > i) ? c - i : i - c;
// Sum of consecutive numbers is n(n+1)/2
score += dist*(dist+1)/2;
}
best = std::min(best, score);
}
fmt::print("Part 2 best fuel usage: {}\n", best);
}
| 22.909091 | 74 | 0.559524 | calewis |
540e937786d34e7246402afeef5e7c46e8c65296 | 2,046 | cpp | C++ | tests/pizza_tests.cpp | Harmos274/Plazza | ade41711f9d945f944276732a9df96442b2b4af8 | [
"MIT"
] | null | null | null | tests/pizza_tests.cpp | Harmos274/Plazza | ade41711f9d945f944276732a9df96442b2b4af8 | [
"MIT"
] | null | null | null | tests/pizza_tests.cpp | Harmos274/Plazza | ade41711f9d945f944276732a9df96442b2b4af8 | [
"MIT"
] | null | null | null | /*
** EPITECH PROJECT, 2020
** plazza
** File description:
** unit test for pizzas
*/
#include "include/catch2.hpp"
#include "pizzas/Ingredient.hpp"
#include "pizzas/Pizza.hpp"
#include "Marmiton.hpp"
#include <chrono>
#include <sstream>
#include <string>
TEST_CASE("Ingredient enum", "operators")
{
using plazza::pizzas::ingredient;
SECTION("| operator")
{
ingredient ing = ingredient::DOE;
CHECK(static_cast<int>((ing | ingredient::TOMATO)) == 3);
REQUIRE(static_cast<int>((ing | ingredient::TOMATO | ingredient::GRUYERE |
ingredient::HAM)) == 15);
}
SECTION("<< operator")
{
std::stringstream sstream;
ingredient bitst = ingredient::DOE | ingredient::TOMATO |
ingredient::GRUYERE | ingredient::HAM;
sstream << bitst;
REQUIRE(sstream.str() == "🦌💀🍅🧀🐷💀");
}
}
TEST_CASE("Pizzas", "Pizza class")
{
using namespace std::literals::chrono_literals;
using namespace plazza;
using namespace plazza::pizzas;
using plazza::pizzas::ingredient;
auto ptest = Pizza("test", ingredient::DOE | ingredient::GRUYERE | ingredient::HAM, 1s, size::XL);
SECTION("Baking time")
{
REQUIRE(ptest.getBakingTime() == 1s);
}
SECTION("Name")
{
REQUIRE(ptest.getName() == "test");
}
SECTION("Serializing")
{
REQUIRE(ptest.pack() == "test XL : 🦌💀🧀🐷💀");
}
}
TEST_CASE("Recipe", "Using the recipes")
{
using namespace plazza;
using namespace plazza::pizzas;
SECTION("Using string to access a recipe")
{
auto const& recipe = "americana" >> marmiton;
REQUIRE(recipe.getName() == "americana");
}
SECTION("Using invalid string to access a recipe")
{
CHECK_THROWS("Americanus" >> marmiton);
}
SECTION("Create a pizza from a recipe")
{
auto const& recipe = "margarita" >> marmiton;
auto pizza = recipe(size::XL);
REQUIRE(pizza.pack() == "margarita XL : 🦌💀🍅🧀");
}
}
| 22.483516 | 102 | 0.591398 | Harmos274 |
5411fb6f49e5e29620b3644cd482e5d4f1e07abb | 1,059 | cpp | C++ | Exercicios-Simples/ex05.cpp | raphaelcarmo/Praticando-C | ba2c926d2eeb4a00f24fef73281de1f937c90769 | [
"MIT"
] | null | null | null | Exercicios-Simples/ex05.cpp | raphaelcarmo/Praticando-C | ba2c926d2eeb4a00f24fef73281de1f937c90769 | [
"MIT"
] | null | null | null | Exercicios-Simples/ex05.cpp | raphaelcarmo/Praticando-C | ba2c926d2eeb4a00f24fef73281de1f937c90769 | [
"MIT"
] | null | null | null | #include <iomanip> /*A biblioteca <iomanip> fornece recursos para manipular a formatação de saída, como a base usada ao formatar inteiros e a precisão dos valores de ponto flutuante .*/
#include <iostream> /*Cabeçalho que define os objetos de fluxo de entrada / saída padrão*/
using namespace std;
/* Exercicio de Média 2.
Neste exercicio é pra calcular a média, ler a media, multiplica pelo peso. neste aqui temos 3 médias, para calcular, mas o processo é o mesmo.
O "cout.precision(1)" vai imprimir apenas 1 casas após a virgula.
desta vez eu declarei todas as variáveis como double para ter um precisão melhor.
*/
int main() {
double nota1,nota2,nota3,Media,peso1,peso2,peso3,total1,total2,total3,total4;
cin>>nota1;
cin>>nota2;
cin>>nota3;
peso1 = 2;
peso2 = 3;
peso3 = 5;
total1 = nota1 * peso1;
total2 = nota2 * peso2;
total3 = nota3 * peso3;
total4 = total1 + total2 + total3;
Media = total4 / 10;
cout << fixed << showpoint;
cout << setprecision(1);
cout << "MEDIA = " << Media << endl;
return 0;
} | 29.416667 | 185 | 0.694995 | raphaelcarmo |
5414ced84d682975ff6aaa1dff8bd48cf592384a | 12,463 | cpp | C++ | test/song_reader_test.cpp | joao18araujo/ly_parser | 4daff56b5e86fb6616d6f71977a5e218edc88174 | [
"MIT"
] | 2 | 2019-03-18T12:25:17.000Z | 2020-12-06T19:53:18.000Z | test/song_reader_test.cpp | joao18araujo/pierluigi | 4daff56b5e86fb6616d6f71977a5e218edc88174 | [
"MIT"
] | null | null | null | test/song_reader_test.cpp | joao18araujo/pierluigi | 4daff56b5e86fb6616d6f71977a5e218edc88174 | [
"MIT"
] | null | null | null | #include "catch.hpp"
#include "song_reader.h"
#include "note.h"
TEST_CASE("Song Reader can receive a string in lilypond format and return a note", "[single-file]"){
SECTION("when notes are without accidental"){
Note note = SongReader::string_to_note(Note(), "c'4");
REQUIRE(note.midi_number == 60);
REQUIRE(note.note_number == 35);
REQUIRE(note.octave == 4);
note = SongReader::string_to_note(Note(), "d'4");
REQUIRE(note.midi_number == 62);
REQUIRE(note.note_number == 36);
REQUIRE(note.octave == 4);
note = SongReader::string_to_note(Note(), "e'4");
REQUIRE(note.midi_number == 64);
REQUIRE(note.note_number == 37);
REQUIRE(note.octave == 4);
note = SongReader::string_to_note(Note(), "f'4");
REQUIRE(note.midi_number == 65);
REQUIRE(note.note_number == 38);
REQUIRE(note.octave == 4);
note = SongReader::string_to_note(Note(), "g'4");
REQUIRE(note.midi_number == 67);
REQUIRE(note.note_number == 39);
REQUIRE(note.octave == 4);
note = SongReader::string_to_note(Note(), "a'4");
REQUIRE(note.midi_number == 69);
REQUIRE(note.note_number == 40);
REQUIRE(note.octave == 4);
note = SongReader::string_to_note(Note(), "b'4");
REQUIRE(note.midi_number == 71);
REQUIRE(note.note_number == 41);
REQUIRE(note.octave == 4);
note = SongReader::string_to_note(Note(), "c''4");
REQUIRE(note.midi_number == 72);
REQUIRE(note.note_number == 42);
REQUIRE(note.octave == 5);
note = SongReader::string_to_note(Note(), "c4");
REQUIRE(note.midi_number == 48);
REQUIRE(note.note_number == 28);
REQUIRE(note.octave == 3);
note = SongReader::string_to_note(Note(), "c,4");
REQUIRE(note.midi_number == 36);
REQUIRE(note.note_number == 21);
REQUIRE(note.octave == 2);
note = SongReader::string_to_note(Note(), "c,,4");
REQUIRE(note.midi_number == 24);
REQUIRE(note.note_number == 14);
REQUIRE(note.octave == 1);
}
SECTION("when notes are with accidental"){
Note note = SongReader::string_to_note(Note(), "cis'4");
REQUIRE(note.midi_number == 61);
REQUIRE(note.note_number == 35);
REQUIRE(note.octave == 4);
note = SongReader::string_to_note(Note(), "ces'4");
REQUIRE(note.midi_number == 59);
REQUIRE(note.note_number == 35);
REQUIRE(note.octave == 4);
note = SongReader::string_to_note(Note(), "cisis'4");
REQUIRE(note.midi_number == 62);
REQUIRE(note.note_number == 35);
REQUIRE(note.octave == 4);
note = SongReader::string_to_note(Note(), "ceses'4");
REQUIRE(note.midi_number == 58);
REQUIRE(note.note_number == 35);
REQUIRE(note.octave == 4);
note = SongReader::string_to_note(Note(), "des'4");
REQUIRE(note.midi_number == 61);
REQUIRE(note.note_number == 36);
REQUIRE(note.octave == 4);
note = SongReader::string_to_note(Note(), "eis'4");
REQUIRE(note.midi_number == 65);
REQUIRE(note.note_number == 37);
REQUIRE(note.octave == 4);
note = SongReader::string_to_note(Note(), "fes'4");
REQUIRE(note.midi_number == 64);
REQUIRE(note.note_number == 38);
REQUIRE(note.octave == 4);
note = SongReader::string_to_note(Note(), "gis'4");
REQUIRE(note.midi_number == 68);
REQUIRE(note.note_number == 39);
REQUIRE(note.octave == 4);
note = SongReader::string_to_note(Note(), "ais'4");
REQUIRE(note.midi_number == 70);
REQUIRE(note.note_number == 40);
REQUIRE(note.octave == 4);
note = SongReader::string_to_note(Note(), "bis'4");
REQUIRE(note.midi_number == 72);
REQUIRE(note.note_number == 41);
REQUIRE(note.octave == 4);
note = SongReader::string_to_note(Note(), "c''4");
REQUIRE(note.midi_number == 72);
REQUIRE(note.note_number == 42);
REQUIRE(note.octave == 5);
}
SECTION("when notes have duration"){
Note note = SongReader::string_to_note(Note(), "c'1");
REQUIRE(note.duration == 32);
note = SongReader::string_to_note(Note(), "c'2");
REQUIRE(note.duration == 16);
note = SongReader::string_to_note(Note(), "c'4");
REQUIRE(note.duration == 8);
note = SongReader::string_to_note(Note(), "c'8");
REQUIRE(note.duration == 4);
note = SongReader::string_to_note(Note(), "c'16");
REQUIRE(note.duration == 2);
note = SongReader::string_to_note(Note(), "c'32");
REQUIRE(note.duration == 1);
}
SECTION("when notes are dotted"){
Note note = SongReader::string_to_note(Note(), "c'2.");
REQUIRE(note.duration == 24);
note = SongReader::string_to_note(Note(), "c'2..");
REQUIRE(note.duration == 28);
note = SongReader::string_to_note(Note(), "c'4.");
REQUIRE(note.duration == 12);
note = SongReader::string_to_note(Note(), "c'4..");
REQUIRE(note.duration == 14);
}
SECTION("when notes have duration from previous note"){
Note note = SongReader::string_to_note(Note(), "c'2");
Note note_2 = SongReader::string_to_note(note, "c");
REQUIRE(note.duration == note_2.duration);
note = SongReader::string_to_note(Note(), "c'4");
note_2 = SongReader::string_to_note(note, "c");
REQUIRE(note.duration == note_2.duration);
}
SECTION("when is a rest"){
Note note = SongReader::string_to_note(Note(), "r4");
REQUIRE(note.note == "r");
REQUIRE(note.rest() == true);
REQUIRE(note.midi_number == 0);
REQUIRE(note.note_number == 0);
REQUIRE(note.octave == 0);
}
}
TEST_CASE("Song Reader can receive a note and return a string", "[single-file]"){
SECTION("when notes are without accidental"){
Note note = Note("c", "", 3, 8);
string s = SongReader::note_to_string(note);
REQUIRE(s == "c4");
note = Note("c", "", 4, 8);
s = SongReader::note_to_string(note);
REQUIRE(s == "c'4");
note = Note("d", "", 4, 8);
s = SongReader::note_to_string(note);
REQUIRE(s == "d'4");
note = Note("e", "", 4, 8);
s = SongReader::note_to_string(note);
REQUIRE(s == "e'4");
note = Note("f", "", 4, 8);
s = SongReader::note_to_string(note);
REQUIRE(s == "f'4");
note = Note("g", "", 4, 8);
s = SongReader::note_to_string(note);
REQUIRE(s == "g'4");
note = Note("a", "", 4, 8);
s = SongReader::note_to_string(note);
REQUIRE(s == "a'4");
note = Note("b", "", 4, 8);
s = SongReader::note_to_string(note);
REQUIRE(s == "b'4");
note = Note("c", "", 5, 8);
s = SongReader::note_to_string(note);
REQUIRE(s == "c''4");
}
SECTION("when notes are with accidental"){
Note note = Note("c", "#", 4, 8);
string s = SongReader::note_to_string(note);
REQUIRE(s == "cis'4");
note = Note("c", "\u266D", 4, 8);
s = SongReader::note_to_string(note);
REQUIRE(s == "ces'4");
note = Note("d", "##", 4, 8);
s = SongReader::note_to_string(note);
REQUIRE(s == "disis'4");
note = Note("e", "\u266D\u266D", 4, 8);
s = SongReader::note_to_string(note);
REQUIRE(s == "eeses'4");
note = Note("f", "#", 4, 2);
s = SongReader::note_to_string(note);
REQUIRE(s == "fis'16");
note = Note("g", "##", 4, 32);
s = SongReader::note_to_string(note);
REQUIRE(s == "gisis'1");
note = Note("a", "\u266D\u266D", 4, 8);
s = SongReader::note_to_string(note);
REQUIRE(s == "aeses'4");
note = Note("b", "#", 4, 16);
s = SongReader::note_to_string(note);
REQUIRE(s == "bis'2");
note = Note("c", "#", 5, 4);
s = SongReader::note_to_string(note);
REQUIRE(s == "cis''8");
}
SECTION("when notes are dotted"){
Note note = Note("c", "", 3, 24);
string s = SongReader::note_to_string(note);
REQUIRE(s == "c2.");
note = Note("c", "", 3, 28);
s = SongReader::note_to_string(note);
REQUIRE(s == "c2..");
note = Note("c", "", 3, 12);
s = SongReader::note_to_string(note);
REQUIRE(s == "c4.");
note = Note("c", "", 3, 14);
s = SongReader::note_to_string(note);
REQUIRE(s == "c4..");
}
}
TEST_CASE("Song Reader can receive a string and return a scale", "[single-file]"){
Scale scale;
scale = SongReader::string_to_scale("\\key c \\major");
REQUIRE(scale.is_valid_note(Note("c")) == true);
REQUIRE(scale.is_valid_note(Note("c#")) == false);
REQUIRE(scale.is_valid_note(Note("d")) == true);
REQUIRE(scale.is_valid_note(Note("d#")) == false);
REQUIRE(scale.is_valid_note(Note("e")) == true);
REQUIRE(scale.is_valid_note(Note("f")) == true);
REQUIRE(scale.is_valid_note(Note("f#")) == false);
REQUIRE(scale.is_valid_note(Note("g")) == true);
REQUIRE(scale.is_valid_note(Note("g#")) == false);
REQUIRE(scale.is_valid_note(Note("a")) == true);
REQUIRE(scale.is_valid_note(Note("a#")) == false);
REQUIRE(scale.is_valid_note(Note("b")) == true);
scale = SongReader::string_to_scale("\\key a \\minor");
REQUIRE(scale.is_valid_note(Note("c")) == true);
REQUIRE(scale.is_valid_note(Note("c#")) == false);
REQUIRE(scale.is_valid_note(Note("d")) == true);
REQUIRE(scale.is_valid_note(Note("d#")) == false);
REQUIRE(scale.is_valid_note(Note("e")) == true);
REQUIRE(scale.is_valid_note(Note("f")) == true);
REQUIRE(scale.is_valid_note(Note("f#")) == false);
REQUIRE(scale.is_valid_note(Note("g")) == true);
REQUIRE(scale.is_valid_note(Note("g#")) == false);
REQUIRE(scale.is_valid_note(Note("a")) == true);
REQUIRE(scale.is_valid_note(Note("a#")) == false);
REQUIRE(scale.is_valid_note(Note("b")) == true);
scale = SongReader::string_to_scale("\\key f \\major");
REQUIRE(scale.is_valid_note(Note("f")) == true);
REQUIRE(scale.is_valid_note(Note("g")) == true);
REQUIRE(scale.is_valid_note(Note("g#")) == false);
REQUIRE(scale.is_valid_note(Note("a")) == true);
REQUIRE(scale.is_valid_note(Note("a#")) == false);
REQUIRE(scale.is_valid_note(Note("b\u266D")) == true);
REQUIRE(scale.is_valid_note(Note("b")) == false);
REQUIRE(scale.is_valid_note(Note("c")) == true);
REQUIRE(scale.is_valid_note(Note("c#")) == false);
REQUIRE(scale.is_valid_note(Note("d")) == true);
REQUIRE(scale.is_valid_note(Note("d#")) == false);
REQUIRE(scale.is_valid_note(Note("e")) == true);
REQUIRE(scale.is_valid_note(Note("e#")) == false);
scale = SongReader::string_to_scale("\\key g \\major");
REQUIRE(scale.is_valid_note(Note("g")) == true);
REQUIRE(scale.is_valid_note(Note("a")) == true);
REQUIRE(scale.is_valid_note(Note("a#")) == false);
REQUIRE(scale.is_valid_note(Note("b")) == true);
REQUIRE(scale.is_valid_note(Note("b#")) == false);
REQUIRE(scale.is_valid_note(Note("c")) == true);
REQUIRE(scale.is_valid_note(Note("c#")) == false);
REQUIRE(scale.is_valid_note(Note("d")) == true);
REQUIRE(scale.is_valid_note(Note("d#")) == false);
REQUIRE(scale.is_valid_note(Note("e")) == true);
REQUIRE(scale.is_valid_note(Note("f")) == false);
REQUIRE(scale.is_valid_note(Note("f#")) == true);
}
TEST_CASE("Song Reader can receive a string and return a compass time", "[single-file]"){
CompassTime compass_time;
compass_time = SongReader::string_to_compass_time("\\time 4/4");
REQUIRE(compass_time.times == 4);
REQUIRE(compass_time.base_note == 4);
REQUIRE(compass_time.base_note_duration() == 8);
REQUIRE(compass_time.compass_duration() == 32);
compass_time = SongReader::string_to_compass_time("\\time 3/4");
REQUIRE(compass_time.times == 3);
REQUIRE(compass_time.base_note == 4);
REQUIRE(compass_time.base_note_duration() == 8);
REQUIRE(compass_time.compass_duration() == 24);
compass_time = SongReader::string_to_compass_time("\\time 2/4");
REQUIRE(compass_time.times == 2);
REQUIRE(compass_time.base_note == 4);
REQUIRE(compass_time.base_note_duration() == 8);
REQUIRE(compass_time.compass_duration() == 16);
compass_time = SongReader::string_to_compass_time("\\time 2/2");
REQUIRE(compass_time.times == 2);
REQUIRE(compass_time.base_note == 2);
REQUIRE(compass_time.base_note_duration() == 16);
REQUIRE(compass_time.compass_duration() == 32);
compass_time = SongReader::string_to_compass_time("\\time 5/4");
REQUIRE(compass_time.times == 5);
REQUIRE(compass_time.base_note == 4);
REQUIRE(compass_time.base_note_duration() == 8);
REQUIRE(compass_time.compass_duration() == 40);
compass_time = SongReader::string_to_compass_time("\\time 9/8");
REQUIRE(compass_time.times == 9);
REQUIRE(compass_time.base_note == 8);
REQUIRE(compass_time.base_note_duration() == 4);
REQUIRE(compass_time.compass_duration() == 36);
}
| 33.502688 | 100 | 0.631389 | joao18araujo |
5414d22f87d16d2e0af57cec858db609321fdbb0 | 996 | hpp | C++ | rsa_utils/include/wrapping_iterator.hpp | j-dax/functional-rsa | 4e0a62fb7fd4b44b0ac925bfd9b2e757c58a45de | [
"MIT"
] | null | null | null | rsa_utils/include/wrapping_iterator.hpp | j-dax/functional-rsa | 4e0a62fb7fd4b44b0ac925bfd9b2e757c58a45de | [
"MIT"
] | null | null | null | rsa_utils/include/wrapping_iterator.hpp | j-dax/functional-rsa | 4e0a62fb7fd4b44b0ac925bfd9b2e757c58a45de | [
"MIT"
] | null | null | null | #pragma once
#include <iterator>
namespace rsa {
template <typename T>
class WrappingIterator : std::forward_iterator<T> {
private:
T *begin_it, *end_it;
size_t index;
public:
// WrappingIterator(); // don't allow default
WrappingIterator(T container) {
begin_it = std::begin(container);
end_it = std::end(container);
index = 0;
}
WrappingIterator(T container, size_t start_index) {
begin_it = std::begin(container);
end_it = std::end(container);
index = start_index;
}
~WrappingIterator() {
delete begin_it;
delete end_it;
}
T* begin() {
return begin_it;
}
T* end() {
return end_it;
}
T* operator++() {
index++;
index %= (end_it - begin_it);
return (begin_it + index);
}
};
}; | 22.636364 | 59 | 0.480924 | j-dax |
541b0ad6007d332bbfced8b4e5bd7d42a967b30c | 6,467 | cpp | C++ | Source/OpenWorldTutorial/Private/Section.cpp | TonyChoiMS/OpenWorldTutorial | 550f179e71e7f5af2c78ab8e6419c8efccd00cec | [
"MIT"
] | 1 | 2021-07-01T13:29:45.000Z | 2021-07-01T13:29:45.000Z | Source/OpenWorldTutorial/Private/Section.cpp | TonyChoiMS/OpenWorldTutorial | 550f179e71e7f5af2c78ab8e6419c8efccd00cec | [
"MIT"
] | null | null | null | Source/OpenWorldTutorial/Private/Section.cpp | TonyChoiMS/OpenWorldTutorial | 550f179e71e7f5af2c78ab8e6419c8efccd00cec | [
"MIT"
] | null | null | null | // Fill out your copyright notice in the Description page of Project Settings.
#include "Section.h"
#include "MyCharacter.h"
#include "ABItemBox.h"
#include "MyPlayerController.h"
#include "OpenWorldGameMode.h"
// Sets default values
ASection::ASection()
{
PrimaryActorTick.bCanEverTick = false;
Mesh = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("MESH"));
RootComponent = Mesh;
FString AssetPath = TEXT("/Game/Environment/SM_SQUARE.SM_SQUARE");
static ConstructorHelpers::FObjectFinder<UStaticMesh> SM_SQUARE(*AssetPath);
if (SM_SQUARE.Succeeded())
{
Mesh->SetStaticMesh(SM_SQUARE.Object);
}
else
{
ABLOG(Error, TEXT("Failed to load staticmesh asset. : %s"), *AssetPath);
}
Trigger = CreateDefaultSubobject<UBoxComponent>(TEXT("TRIGGER"));
Trigger->SetBoxExtent(FVector(775.0f, 775.0f, 300.0f));
Trigger->SetupAttachment(RootComponent);
Trigger->SetRelativeLocation(FVector(0.0f, 0.0f, 250.0f));
Trigger->SetCollisionProfileName(TEXT("OWTTrigger"));
Trigger->OnComponentBeginOverlap.AddDynamic(this, &ASection::OnTriggerBeginOverlap);
FString GateAssetPath = TEXT("/Game/Environment/SM_GATE.SM_GATE");
static ConstructorHelpers::FObjectFinder<UStaticMesh> SM_GATE(*GateAssetPath);
if (!SM_GATE.Succeeded())
{
ABLOG(Error, TEXT("Failed to load staticmesh asset. : %s"), *GateAssetPath);
}
static FName GateSockets[] = { { TEXT("+XGate") }, { TEXT("-XGate") }, { TEXT("+YGate") }, { TEXT("-YGate") } };
for (FName GateSocket : GateSockets)
{
ABCHECK(Mesh->DoesSocketExist(GateSocket));
UStaticMeshComponent* NewGate = CreateDefaultSubobject<UStaticMeshComponent>(*GateSocket.ToString());
NewGate->SetStaticMesh(SM_GATE.Object);
NewGate->SetupAttachment(RootComponent, GateSocket);
NewGate->SetRelativeLocation(FVector(0.0f, -80.5f, 0.0f));
GateMeshes.Add(NewGate);
UBoxComponent* NewGateTrigger = CreateDefaultSubobject<UBoxComponent>(*GateSocket.ToString().Append(TEXT("Trigger")));
NewGateTrigger->SetBoxExtent(FVector(100.0f, 100.0f, 300.0f));
NewGateTrigger->SetupAttachment(RootComponent, GateSocket);
NewGateTrigger->SetRelativeLocation(FVector(70.0f, 0.0f, 250.0f));
NewGateTrigger->SetCollisionProfileName(TEXT("OWTTrigger"));
GateTriggers.Add(NewGateTrigger);
NewGateTrigger->OnComponentBeginOverlap.AddDynamic(this, &ASection::OnGateTriggerBeginOverlap);
NewGateTrigger->ComponentTags.Add(GateSocket);
}
bNoBattle = false;
EnemySpawnTime = 2.0f;
ItemBoxSpawnTime = 5.0f;
}
// Called when the game starts or when spawned
void ASection::BeginPlay()
{
Super::BeginPlay();
SetState(bNoBattle ? ESectionState::COMPLETE : ESectionState::READY);
}
void ASection::SetState(ESectionState NewState)
{
switch (NewState)
{
case ESectionState::READY:
Trigger->SetCollisionProfileName(TEXT("OWTTrigger"));
for (UBoxComponent* GateTrigger : GateTriggers)
{
GateTrigger->SetCollisionProfileName(TEXT("NoCollision"));
}
OperateGates(true);
break;
case ESectionState::BATTLE:
Trigger->SetCollisionProfileName(TEXT("NoCollision"));
for (UBoxComponent* GateTrigger : GateTriggers)
{
GateTrigger->SetCollisionProfileName(TEXT("NoCollision"));
}
OperateGates(false);
GetWorld()->GetTimerManager().SetTimer(SpawnNPCTimerHandle,
FTimerDelegate::CreateUObject(this, &ASection::OnNPCSpawn), EnemySpawnTime, false);
GetWorld()->GetTimerManager().SetTimer(SpawnItemBoxTimerHandle,
FTimerDelegate::CreateLambda([this]() -> void
{
FVector2D RandXY = FMath::RandPointInCircle(600.0f);
GetWorld()->SpawnActor<AABItemBox>(GetActorLocation() + FVector(RandXY, 30.0f), FRotator::ZeroRotator);
}), ItemBoxSpawnTime, false);
break;
case ESectionState::COMPLETE:
Trigger->SetCollisionProfileName(TEXT("NoCollision"));
for (UBoxComponent* GateTrigger : GateTriggers)
{
GateTrigger->SetCollisionProfileName(TEXT("OWTTrigger"));
}
OperateGates(true);
break;
}
CurrentState = NewState;
}
void ASection::OperateGates(bool bOpen)
{
for (UStaticMeshComponent* Gate : GateMeshes)
{
Gate->SetRelativeRotation(bOpen ? FRotator(0.0f, -90.0f, 0.0f) : FRotator::ZeroRotator);
}
}
void ASection::OnTriggerBeginOverlap(UPrimitiveComponent * OverlappedComponent, AActor * OtherActor, UPrimitiveComponent * OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult & SweepResult)
{
if (CurrentState == ESectionState::READY)
{
SetState(ESectionState::BATTLE);
}
}
void ASection::OnGateTriggerBeginOverlap(UPrimitiveComponent * OverlappedComponent, AActor * OtherActor, UPrimitiveComponent * OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult & SweepResult)
{
ABCHECK(OverlappedComponent->ComponentTags.Num() == 1);
FName ComponentTag = OverlappedComponent->ComponentTags[0];
FName SocketName = FName(*ComponentTag.ToString().Left(2));
if (!Mesh->DoesSocketExist(SocketName))
return;
FVector NewLocation = Mesh->GetSocketLocation(SocketName);
TArray<FOverlapResult> OverlapResults;
FCollisionQueryParams CollisionQueryParam(NAME_None, false, this);
FCollisionObjectQueryParams ObjectQueryParam(FCollisionObjectQueryParams::InitType::AllObjects);
bool bResult = GetWorld()->OverlapMultiByObjectType(
OverlapResults,
NewLocation,
FQuat::Identity,
ObjectQueryParam,
FCollisionShape::MakeSphere(775.0f),
CollisionQueryParam
);
if (!bResult)
{
auto NewSection = GetWorld()->SpawnActor<ASection>(NewLocation, FRotator::ZeroRotator);
}
else
{
ABLOG(Warning, TEXT("New section Area is not empty"));
}
}
void ASection::OnNPCSpawn()
{
GetWorld()->GetTimerManager().ClearTimer(SpawnNPCTimerHandle);
auto KeyNPC = GetWorld()->SpawnActor<AMyCharacter>(GetActorLocation() + FVector::UpVector * 88.0f, FRotator::ZeroRotator);
if (nullptr != KeyNPC)
{
KeyNPC->OnDestroyed.AddDynamic(this, &ASection::OnKeyNPCDestroyed);
}
}
void ASection::OnKeyNPCDestroyed(AActor * DestroyedActor)
{
auto MyCharacter = Cast<AMyCharacter>(DestroyedActor);
ABCHECK(nullptr != MyCharacter);
auto MyPlayerController = Cast<AMyPlayerController>(MyCharacter->LastHitBy);
ABCHECK(nullptr != MyPlayerController);
auto OpenWorldGameMode = Cast<AOpenWorldGameMode>(GetWorld()->GetAuthGameMode());
ABCHECK(nullptr != OpenWorldGameMode);
OpenWorldGameMode->AddScore(MyPlayerController);
SetState(ESectionState::COMPLETE);
}
void ASection::OnConstruction(const FTransform& Transform)
{
Super::OnConstruction(Transform);
SetState(bNoBattle ? ESectionState::COMPLETE : ESectionState::READY);
} | 32.014851 | 208 | 0.761559 | TonyChoiMS |
541cc344174e53a72fb73bf72c9cf51c30c9d973 | 765 | cpp | C++ | Codeforces/545A Toy Cars.cpp | sreejonK19/online-judge-solutions | da65d635cc488c8f305e48b49727ad62649f5671 | [
"MIT"
] | null | null | null | Codeforces/545A Toy Cars.cpp | sreejonK19/online-judge-solutions | da65d635cc488c8f305e48b49727ad62649f5671 | [
"MIT"
] | null | null | null | Codeforces/545A Toy Cars.cpp | sreejonK19/online-judge-solutions | da65d635cc488c8f305e48b49727ad62649f5671 | [
"MIT"
] | 2 | 2018-11-06T19:37:56.000Z | 2018-11-09T19:05:46.000Z | #include <bits/stdc++.h>
using namespace std;
const int MAXN = 100;
int A[MAXN+2][MAXN+2];
vector < int > index;
int main( int argc, char ** argv ) {
// freopen( "input.txt", "r", stdin );
int n;
cin >> n;
for( int i = 1 ; i <= n ; ++i ) {
for( int j = 1 ; j <= n ; ++j ) {
cin >> A[i][j];
}
}
for( int i = 1 ; i <= n ; ++i ) {
bool flag = true;
for( int j = 1 ; j <= n ; ++j )
if( A[i][j] == 1 || A[i][j] == 3 ) flag = false;
if( flag ) index.push_back( i );
}
cout << index.size() << endl;
if( index.size() ) {
for( int i = 0 ; i < index.size() ; ++i ) {
cout << index[i] << " ";
}
cout << endl;
}
return 0;
} | 19.615385 | 60 | 0.393464 | sreejonK19 |
541cd13da1421a0e21f92485651c4b9eb0ccf9b2 | 1,419 | cpp | C++ | android-31/android/net/TelephonyNetworkSpecifier.cpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 12 | 2020-03-26T02:38:56.000Z | 2022-03-14T08:17:26.000Z | android-31/android/net/TelephonyNetworkSpecifier.cpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 1 | 2021-01-27T06:07:45.000Z | 2021-11-13T19:19:43.000Z | android-30/android/net/TelephonyNetworkSpecifier.cpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 3 | 2021-02-02T12:34:55.000Z | 2022-03-08T07:45:57.000Z | #include "../os/Parcel.hpp"
#include "../../JObject.hpp"
#include "../../JString.hpp"
#include "./TelephonyNetworkSpecifier.hpp"
namespace android::net
{
// Fields
JObject TelephonyNetworkSpecifier::CREATOR()
{
return getStaticObjectField(
"android.net.TelephonyNetworkSpecifier",
"CREATOR",
"Landroid/os/Parcelable$Creator;"
);
}
// QJniObject forward
TelephonyNetworkSpecifier::TelephonyNetworkSpecifier(QJniObject obj) : android::net::NetworkSpecifier(obj) {}
// Constructors
// Methods
jint TelephonyNetworkSpecifier::describeContents() const
{
return callMethod<jint>(
"describeContents",
"()I"
);
}
jboolean TelephonyNetworkSpecifier::equals(JObject arg0) const
{
return callMethod<jboolean>(
"equals",
"(Ljava/lang/Object;)Z",
arg0.object<jobject>()
);
}
jint TelephonyNetworkSpecifier::getSubscriptionId() const
{
return callMethod<jint>(
"getSubscriptionId",
"()I"
);
}
jint TelephonyNetworkSpecifier::hashCode() const
{
return callMethod<jint>(
"hashCode",
"()I"
);
}
JString TelephonyNetworkSpecifier::toString() const
{
return callObjectMethod(
"toString",
"()Ljava/lang/String;"
);
}
void TelephonyNetworkSpecifier::writeToParcel(android::os::Parcel arg0, jint arg1) const
{
callMethod<void>(
"writeToParcel",
"(Landroid/os/Parcel;I)V",
arg0.object(),
arg1
);
}
} // namespace android::net
| 19.985915 | 110 | 0.691332 | YJBeetle |
541ddb032cf6b50125093b4bdd76f49fc615081e | 2,328 | cpp | C++ | tests/vklayertests_best_practices.cpp | h3r2tic/Vulkan-ValidationLayers | 4fde9b75099271ded2de6d1a5903cb57a0e93931 | [
"Apache-2.0"
] | 1 | 2021-07-15T23:36:20.000Z | 2021-07-15T23:36:20.000Z | tests/vklayertests_best_practices.cpp | h3r2tic/Vulkan-ValidationLayers | 4fde9b75099271ded2de6d1a5903cb57a0e93931 | [
"Apache-2.0"
] | null | null | null | tests/vklayertests_best_practices.cpp | h3r2tic/Vulkan-ValidationLayers | 4fde9b75099271ded2de6d1a5903cb57a0e93931 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2015-2019 The Khronos Group Inc.
* Copyright (c) 2015-2019 Valve Corporation
* Copyright (c) 2015-2019 LunarG, Inc.
* Copyright (c) 2015-2019 Google, 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
*
* Author: Camden Stocker <camden@lunarg.com>
*/
#include "cast_utils.h"
#include "layer_validation_tests.h"
void VkBestPracticesLayerTest::InitBestPracticesFramework() {
VkValidationFeatureEnableEXT enables[] = {VK_VALIDATION_FEATURE_ENABLE_BEST_PRACTICES_EXT};
VkValidationFeaturesEXT features = {};
features.sType = VK_STRUCTURE_TYPE_VALIDATION_FEATURES_EXT;
features.enabledValidationFeatureCount = 1;
features.pEnabledValidationFeatures = enables;
InitFramework(myDbgFunc, m_errorMonitor, &features);
}
TEST_F(VkBestPracticesLayerTest, CmdClearAttachmentTest) {
TEST_DESCRIPTION("Test for validating usage of vkCmdClearAttachments");
InitBestPracticesFramework();
InitState();
ASSERT_NO_FATAL_FAILURE(InitRenderTarget());
m_commandBuffer->begin();
m_commandBuffer->BeginRenderPass(m_renderPassBeginInfo);
// Main thing we care about for this test is that the VkImage obj we're
// clearing matches Color Attachment of FB
// Also pass down other dummy params to keep driver and paramchecker happy
VkClearAttachment color_attachment;
color_attachment.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
color_attachment.clearValue.color.float32[0] = 1.0;
color_attachment.clearValue.color.float32[1] = 1.0;
color_attachment.clearValue.color.float32[2] = 1.0;
color_attachment.clearValue.color.float32[3] = 1.0;
color_attachment.colorAttachment = 0;
VkClearRect clear_rect = {{{0, 0}, {(uint32_t)m_width, (uint32_t)m_height}}, 0, 1};
// Call for full-sized FB Color attachment prior to issuing a Draw
m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT,
"UNASSIGNED-CoreValidation-DrawState-ClearCmdBeforeDraw");
vk::CmdClearAttachments(m_commandBuffer->handle(), 1, &color_attachment, 1, &clear_rect);
m_errorMonitor->VerifyFound();
}
| 40.842105 | 99 | 0.743557 | h3r2tic |
541e705ab721be349fd37bd00818face09224a09 | 1,055 | cpp | C++ | src/pWolfEncrypt/WolfEncryptMain.cpp | scottsideleau/moos-ivp-umassd | fb7f533d907208b438e5489e98f92615a6bb3246 | [
"Apache-2.0"
] | 6 | 2017-01-02T16:40:04.000Z | 2019-01-22T04:55:22.000Z | src/pWolfEncrypt/WolfEncryptMain.cpp | scottsideleau/moos-ivp-umassd | fb7f533d907208b438e5489e98f92615a6bb3246 | [
"Apache-2.0"
] | null | null | null | src/pWolfEncrypt/WolfEncryptMain.cpp | scottsideleau/moos-ivp-umassd | fb7f533d907208b438e5489e98f92615a6bb3246 | [
"Apache-2.0"
] | 2 | 2017-06-02T18:31:07.000Z | 2021-12-15T10:09:40.000Z | /****************************************************************************/
/* WolfEncryptMain.cpp */
/****************************************************************************/
// WolfEncrypt Includes
#include "WolfEncrypt.h"
/*************************************************************************//**
* The main function, which is responsible for starting the WolfEncrypt
* MOOS Application and properly handing it the .moos file.
*
* @return the number of errors
*/
int main(int argc , char *argv[])
{
// Set a default, blank mission file
const char *sMissionFile = "pWolfEncrypt.moos";
// Set a default process name
const char *sMOOSName = "pWolfEncrypt";
// Handle command line arguments
switch(argc)
{
case 3:
sMOOSName = argv[2]; // alternate process name provided
case 2:
sMissionFile = argv[1]; // alternate mission file provided
}
// Iniitialize and start the extended MOOSApp class
CMOOSWolfEncrypt MOOSWolfEncrypt;
MOOSWolfEncrypt.Run(sMOOSName, sMissionFile);
return 0;
}
| 27.051282 | 78 | 0.543128 | scottsideleau |
5429d2a80df1fa829e7a8fb21af9d4631e27ffc5 | 12,514 | cpp | C++ | nfc/NfcCxSample/windows-drivertemplate-nfc/Device.cpp | galeksandrp/Windows-driver-samples | 94de67aabfbc2a4e338d4d4eca838c918749fa7f | [
"MS-PL"
] | 3,084 | 2015-03-18T04:40:32.000Z | 2019-05-06T17:14:33.000Z | nfc/NfcCxSample/windows-drivertemplate-nfc/Device.cpp | galeksandrp/Windows-driver-samples | 94de67aabfbc2a4e338d4d4eca838c918749fa7f | [
"MS-PL"
] | 275 | 2015-03-19T18:44:41.000Z | 2019-05-06T14:13:26.000Z | nfc/NfcCxSample/windows-drivertemplate-nfc/Device.cpp | galeksandrp/Windows-driver-samples | 94de67aabfbc2a4e338d4d4eca838c918749fa7f | [
"MS-PL"
] | 3,091 | 2015-03-19T00:08:54.000Z | 2019-05-06T16:42:01.000Z | #include <new>
#include "Device.h"
// [Required]
// Called when the device is provisioned during system boot or when a new device is plugged-in while the
// system is running.
//
// https://docs.microsoft.com/windows-hardware/drivers/ddi/content/wdfdriver/nc-wdfdriver-evt_wdf_driver_device_add
NTSTATUS DeviceContext::AddDevice(
_In_ WDFDRIVER Driver,
_Inout_ PWDFDEVICE_INIT DeviceInit)
{
(void)Driver;
NTSTATUS status;
// Configure the NFC Class Extension.
// Note: The NFC_CX_TRANSPORT_TYPE is only used for telemetry purposes. It does not affect the behavior of
// the driver.
NFC_CX_CLIENT_CONFIG nfcCxConfig;
NFC_CX_CLIENT_CONFIG_INIT(&nfcCxConfig, NFC_CX_TRANSPORT_CUSTOM);
#ifdef ENABLE_IF_IMPLEMENTING_CUSTOM_IOCTLS
nfcCxConfig.EvtNfcCxDeviceIoControl = IoControl;
#endif
// Provide the NCI Write callback, which is called by the NFC CX when it has an NCI packet that needs to
// be sent to the NFC Controller.
nfcCxConfig.EvtNfcCxWriteNciPacket = WriteNciPacket;
// Instruct the NFC CX to read the existing NCI configuration values and only update them if necessary.
nfcCxConfig.DriverFlags = NFC_CX_DRIVER_ENABLE_EEPROM_WRITE_PROTECTION;
status = NfcCxDeviceInitConfig(DeviceInit, &nfcCxConfig);
if (!NT_SUCCESS(status))
{
return status;
}
// Create the PnP power callbacks configuration.
WDF_PNPPOWER_EVENT_CALLBACKS pnpCallbacks;
WDF_PNPPOWER_EVENT_CALLBACKS_INIT(&pnpCallbacks);
pnpCallbacks.EvtDevicePrepareHardware = PrepareHardware;
pnpCallbacks.EvtDeviceReleaseHardware = ReleaseHardware;
pnpCallbacks.EvtDeviceD0Entry = D0Entry;
pnpCallbacks.EvtDeviceD0Exit = D0Exit;
// Set the PnP power callbacks.
WdfDeviceInitSetPnpPowerEventCallbacks(DeviceInit, &pnpCallbacks);
// Create WDF object attributes for the device.
WDF_OBJECT_ATTRIBUTES deviceAttributes;
WDF_OBJECT_ATTRIBUTES_INIT_CONTEXT_TYPE(&deviceAttributes, DeviceContext);
deviceAttributes.EvtDestroyCallback = Destroy;
// Create the device.
WDFDEVICE device;
status = WdfDeviceCreate(&DeviceInit, &deviceAttributes, &device);
if (!NT_SUCCESS(status))
{
return status;
}
// Get a pointer to the raw memory that WDF allocated for the Device class.
DeviceContext* context = DeviceGetContext(device);
// Initialize the raw memory using C++'s placement new operator.
// https://en.cppreference.com/w/cpp/language/new
new (context) DeviceContext(device);
// Let the NFC Class Extension initialize the device.
status = NfcCxDeviceInitialize(device);
if (!NT_SUCCESS(status))
{
return status;
}
// Create the RF config. (Enable everything.)
NFC_CX_RF_DISCOVERY_CONFIG discoveryConfig;
NFC_CX_RF_DISCOVERY_CONFIG_INIT(&discoveryConfig);
discoveryConfig.PollConfig = NFC_CX_POLL_NFC_A | NFC_CX_POLL_NFC_B | NFC_CX_POLL_NFC_F_212 | NFC_CX_POLL_NFC_F_424 | NFC_CX_POLL_NFC_15693 | NFC_CX_POLL_NFC_ACTIVE | NFC_CX_POLL_NFC_A_KOVIO;
discoveryConfig.NfcIPMode = NFC_CX_NFCIP_NFC_A | NFC_CX_NFCIP_NFC_F_212 | NFC_CX_NFCIP_NFC_F_424 | NFC_CX_NFCIP_NFC_ACTIVE | NFC_CX_NFCIP_NFC_ACTIVE_A | NFC_CX_NFCIP_NFC_ACTIVE_F_212 | NFC_CX_NFCIP_NFC_ACTIVE_F_424;
discoveryConfig.NfcIPTgtMode = NFC_CX_NFCIP_TGT_NFC_A | NFC_CX_NFCIP_TGT_NFC_F | NFC_CX_NFCIP_TGT_NFC_ACTIVE_A | NFC_CX_NFCIP_TGT_NFC_ACTIVE_F;
discoveryConfig.NfcCEMode = NFC_CX_CE_NFC_A | NFC_CX_CE_NFC_B | NFC_CX_CE_NFC_F;
// Set the RF config.
status = NfcCxSetRfDiscoveryConfig(device, &discoveryConfig);
if (!NT_SUCCESS(status))
{
return status;
}
#ifdef ENABLE_IF_USING_SEQUENCE_HANDLER_CALLBACKS
// Set the NFC Class Extension sequence handlers.
for (int sequenceType = 0; sequenceType != SequenceMaximum; ++sequenceType)
{
status = NfcCxRegisterSequenceHandler(device, NFC_CX_SEQUENCE(sequenceType), SequenceHandler);
if (!NT_SUCCESS(status))
{
return status;
}
}
#endif
return STATUS_SUCCESS;
}
DeviceContext::DeviceContext(_In_ WDFDEVICE Device) :
_Device(Device)
{
}
// [Required]
// Called when the memory for the class is about to be freed by WDF.
//
// https://docs.microsoft.com/windows-hardware/drivers/ddi/content/wdfobject/nc-wdfobject-evt_wdf_object_context_destroy
void DeviceContext::Destroy(
_In_ WDFOBJECT Object)
{
// Manually call the destructor for the class.
// This mirrors the use of the placement new operator in `DeviceContext::AddDevice`.
DeviceContext* context = DeviceGetContext(Object);
context->~DeviceContext();
}
// [Likely required]
// Called when the device's hardware resources are ready to be initialized.
//
// https://docs.microsoft.com/windows-hardware/drivers/ddi/content/wdfdevice/nc-wdfdevice-evt_wdf_device_prepare_hardware
NTSTATUS DeviceContext::PrepareHardware(
_In_ WDFDEVICE Device,
_In_ WDFCMRESLIST ResourcesRaw,
_In_ WDFCMRESLIST ResourcesTranslated)
{
(void)Device;
(void)ResourcesRaw;
(void)ResourcesTranslated;
// FIX ME:
// Initialize the hardware so that it is ready to accept NCI packets.
return STATUS_SUCCESS;
}
// [Likely required]
// Called when the device's hardware resources are no longer accessible.
//
// https://docs.microsoft.com/windows-hardware/drivers/ddi/content/wdfdevice/nc-wdfdevice-evt_wdf_device_release_hardware
NTSTATUS DeviceContext::ReleaseHardware(
_In_ WDFDEVICE Device,
_In_ WDFCMRESLIST ResourcesTranslated)
{
(void)Device;
(void)ResourcesTranslated;
// FIX ME:
// If neccessary, free any resources created by PrepareHardware.
return STATUS_SUCCESS;
}
// [Likely required]
// Called when the NFC Controller is entering the fully powered-on state.
//
// https://docs.microsoft.com/windows-hardware/drivers/ddi/content/wdfdevice/nc-wdfdevice-evt_wdf_device_d0_entry
NTSTATUS DeviceContext::D0Entry(
_In_ WDFDEVICE Device,
_In_ WDF_POWER_DEVICE_STATE PreviousState)
{
(void)PreviousState;
NTSTATUS status;
// Invoke the HostActionStart event, so that the NFC Class Extension initializes the NFC Controller (by
// sending the relevant NCI packets).
NFC_CX_HARDWARE_EVENT eventArgs = {};
eventArgs.HostAction = HostActionStart;
status = NfcCxHardwareEvent(Device, &eventArgs);
if (!NT_SUCCESS(status))
{
return status;
}
return STATUS_SUCCESS;
}
// [Likely required]
// Called when the NFC Controller is entering a low power state.
//
// By default, the NFC Class Extension will prevent this callback from being invoked if there is an client
// process that may be using the NFC Controller. So it is okay for the NFC Controller to be fully
// uninitialized here.
//
// https://docs.microsoft.com/windows-hardware/drivers/ddi/content/wdfdevice/nc-wdfdevice-evt_wdf_device_d0_exit
NTSTATUS DeviceContext::D0Exit(
_In_ WDFDEVICE Device,
_In_ WDF_POWER_DEVICE_STATE TargetState)
{
(void)TargetState;
NTSTATUS status;
// Invoke the HostActionStop event, so that the NFC Class Extension uninitializes the NFC Controller (by sending
// the relevant NCI packets).
NFC_CX_HARDWARE_EVENT eventArgs = {};
eventArgs.HostAction = HostActionStop;
status = NfcCxHardwareEvent(Device, &eventArgs);
if (!NT_SUCCESS(status))
{
return status;
}
return STATUS_SUCCESS;
}
// [Optional]
// Called when certain state transitions occur within the NFC Class Extension state machine. This can be used to send
// custom commands to the NFC Controller if neccessary.
//
// https://docs.microsoft.com/windows-hardware/drivers/nfc/sequence-handling
void DeviceContext::SequenceHandler(
_In_ WDFDEVICE Device,
_In_ NFC_CX_SEQUENCE Sequence,
_In_ PFN_NFC_CX_SEQUENCE_COMPLETION_ROUTINE CompletionRoutine,
_In_opt_ WDFCONTEXT CompletionContext)
{
(void)Sequence;
// Nothing to do. So complete the sequence handler immediately.
// Note: CompletionRoutine may be called asynchronously.
CompletionRoutine(Device, STATUS_SUCCESS, 0, CompletionContext);
}
// [Optional]
// Can be used to implement custom IOCTLs.
//
// The NFC Class Extension registers for the default I/O queue and so it gets the first crack at handling all I/O requests.
// If this callback is enabled, any IOCTL the NFC Class Extension doesn't recognize will be forwarded here.
//
// https://docs.microsoft.com/windows-hardware/drivers/ddi/content/nfccx/nc-nfccx-evt_nfc_cx_device_io_control
void DeviceContext::IoControl(
_In_ WDFDEVICE Device,
_In_ WDFREQUEST Request,
_In_ size_t OutputBufferLength,
_In_ size_t InputBufferLength,
_In_ ULONG IoControlCode)
{
(void)Device;
(void)OutputBufferLength;
(void)InputBufferLength;
(void)IoControlCode;
// No custom IOCTLs are currently supported. So complete all I/O requests with a standard error.
WdfRequestComplete(Request, STATUS_INVALID_DEVICE_STATE);
}
// [Required]
// Called by the NFC Class Extension when an NCI packet must be sent to the NFC Controller.
//
// https://docs.microsoft.com/windows-hardware/drivers/ddi/content/nfccx/nc-nfccx-evt_nfc_cx_write_nci_packet
void DeviceContext::WriteNciPacket(
_In_ WDFDEVICE Device,
_In_ WDFREQUEST Request)
{
(void)Device;
NTSTATUS status;
// Get the NCI packet.
void* nciPacket;
size_t nciPacketLength;
status = WdfRequestRetrieveInputBuffer(Request, 0, &nciPacket, &nciPacketLength);
if (!NT_SUCCESS(status))
{
WdfRequestComplete(Request, status);
return;
}
// FIX ME:
// Send NCI packet to NFC Controller hardware using the relevant bus API.
// For example,
// - I2C or SPI: https://docs.microsoft.com/windows-hardware/drivers/spb/spb-peripheral-device-drivers
// - USB: https://docs.microsoft.com/windows-hardware/drivers/usbcon/usb-driver-development-guide
// FIX ME:
// Complete I/O request with STATUS_SUCCESS if NCI packet is succesfully sent to the NFC Controller.
WdfRequestComplete(Request, STATUS_NOT_IMPLEMENTED);
}
// FIX ME:
// Ensure NfcCxNciReadNotification is called when the NFC Controller needs to send an NCI packet to the driver.
// This is usually done in response to a hardware notification. For example,
// - GPIO interrupt (I2C or SPI): https://docs.microsoft.com/windows-hardware/drivers/gpio/gpio-interrupts
// - USB continuous reader: https://docs.microsoft.com/windows-hardware/drivers/usbcon/how-to-use-the-continous-reader-for-getting-data-from-a-usb-endpoint--umdf-/
//
// https://docs.microsoft.com/windows-hardware/drivers/ddi/content/nfccx/nf-nfccx-nfccxncireadnotification
// A helper function that forwards NCI packets from the NFC Controller to the NFC Class Extension driver.
//
// NOTE: If the NCI packet is already packaged within an existing WDFMEMORY, then the NfcCxNciReadNotification
// function can be called directly.
NTSTATUS DeviceContext::ReadNciPacket(
_In_reads_bytes_(nciPacketLength) void* nciPacket,
_In_ size_t nciPacketLength)
{
NTSTATUS status;
if (!_NciReadMemory)
{
// Create the WDFMEMORY object that will be used for all NCI reads.
WDF_OBJECT_ATTRIBUTES memoryAttributes;
WDF_OBJECT_ATTRIBUTES_INIT(&memoryAttributes);
memoryAttributes.ParentObject = _Device;
status = WdfMemoryCreatePreallocated(&memoryAttributes, nciPacket, nciPacketLength, &_NciReadMemory);
if (!NT_SUCCESS(status))
{
return status;
}
}
else
{
// Re-assign the WDFMEMORY to point to the new NCI packet.
status = WdfMemoryAssignBuffer(_NciReadMemory, nciPacket, nciPacketLength);
if (!NT_SUCCESS(status))
{
return status;
}
}
// Note: NfcCxNciReadNotification does not store a reference to the WDFMEMORY object passed to it. So it
// is safe to free the NCI packet's memory after the call has completed.
status = NfcCxNciReadNotification(_Device, _NciReadMemory);
if (!NT_SUCCESS(status))
{
return status;
}
return STATUS_SUCCESS;
}
| 36.377907 | 220 | 0.719754 | galeksandrp |
542b037a3a3ecbb79e02b2580f03fde45c53b18a | 1,685 | cpp | C++ | other_contest/yuruhuwa_onsite_3/d.cpp | zaurus-yusya/atcoder | 5fc345b3da50222fa1366d1ce52ae58799488cef | [
"MIT"
] | 3 | 2020-05-27T16:27:12.000Z | 2021-01-27T12:47:12.000Z | other_contest/yuruhuwa_onsite_3/d.cpp | zaurus-yusya/Competitive-Programming | c72e13a11f76f463510bd4a476b86631d9d1b13a | [
"MIT"
] | null | null | null | other_contest/yuruhuwa_onsite_3/d.cpp | zaurus-yusya/Competitive-Programming | c72e13a11f76f463510bd4a476b86631d9d1b13a | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
typedef long long ll;
#define rep(i,n) for(ll i=0;i<(n);i++)
#define repr(i,n) for(ll i=(n-1);i>=0;i--)
#define pb push_back
#define mp make_pair
#define all(x) x.begin(),x.end()
#define br cout << endl;
using namespace std;
const int INF = 1e9;
const int MOD = 1e9+7;
using Graph = vector<vector<ll>>;
template<class T> inline bool chmin(T &a, T b) { if(a > b){ a = b; return true;} return false;}
template<class T> inline bool chmax(T &a, T b) { if(a < b){ a = b; return true;} return false;}
int main() {
ll h, w;
cin >> h >> w;
vector<vector<ll>> vec(2*h, vector<ll>(w));
rep(i,h){
rep(j,w){
cin >> vec.at(i).at(j);
vec.at(i+h).at(j) = vec.at(i).at(j);
}
}
/*
rep(i,2*h){
rep(j,w){
cout << vec.at(i).at(j);
}
cout << "" << endl;
}
*/
//cout << "------" << endl;
vector<ll> first(h);
rep(i,h){
first.at(i) = vec.at(i).at(0);
}
vector<ll> ans(w);
ans.at(0) = 1;
for(ll j = 1; j < w; j++){
for(ll i = 0; i < h; i++){
ll flag = 0;
for(ll k = 0; k < h; k++){
//cout << first.at(i) << " " << vec.at(i+k).at(j) << endl;
if(first.at(k) != vec.at(i+k).at(j)){
flag = 1;
}
}
if(flag == 0){
ans.at(j) = 1;
}
}
}
ll ans_flag = 0;
rep(i,w){
if(ans.at(i) == 0){
ans_flag = 1;
cout << "No" << endl;
break;
}
}
if(ans_flag == 0){
cout << "Yes" << endl;
}
} | 21.883117 | 95 | 0.409496 | zaurus-yusya |
542ba87482e729829ee49a56bf852a3f823cd7bc | 914 | hpp | C++ | include/cppurses/widget/widgets/vertical_scrollbar.hpp | jktjkt/CPPurses | 652d702258db8fab55ae945f7bb38e0b7c29521b | [
"MIT"
] | null | null | null | include/cppurses/widget/widgets/vertical_scrollbar.hpp | jktjkt/CPPurses | 652d702258db8fab55ae945f7bb38e0b7c29521b | [
"MIT"
] | null | null | null | include/cppurses/widget/widgets/vertical_scrollbar.hpp | jktjkt/CPPurses | 652d702258db8fab55ae945f7bb38e0b7c29521b | [
"MIT"
] | null | null | null | #ifndef CPPURSES_WIDGET_WIDGETS_VERTICAL_SCROLLBAR_HPP
#define CPPURSES_WIDGET_WIDGETS_VERTICAL_SCROLLBAR_HPP
#include <signals/signal.hpp>
#include <cppurses/widget/layouts/vertical_layout.hpp>
#include <cppurses/widget/widget.hpp>
#include <cppurses/widget/widgets/push_button.hpp>
#include <cppurses/widget/widgets/textbox_base.hpp>
namespace cppurses {
class Vertical_scrollbar : public Vertical_layout {
public:
Vertical_scrollbar();
Vertical_scrollbar(Textbox_base& tb);
Push_button& up_button = this->make_child<Push_button>("▴");
Widget& middle = this->make_child<Widget>();
Push_button& down_button = this->make_child<Push_button>("▾");
// Signals
sig::Signal<void()>& up = up_button.clicked;
sig::Signal<void()>& down = down_button.clicked;
private:
void initialize();
};
} // namespace cppurses
#endif // CPPURSES_WIDGET_WIDGETS_VERTICAL_SCROLLBAR_HPP
| 29.483871 | 66 | 0.756018 | jktjkt |
542d4dbc420be1dc6e8d3ec946d4e96be49c98fa | 3,412 | cc | C++ | fluxml/FluxMLPool.cc | csachs/FluxML | 6a46492833a4f0660fc3f2fecd6c166e7de1d167 | [
"MIT"
] | 9 | 2019-05-27T18:01:09.000Z | 2022-01-07T11:26:52.000Z | fluxml/FluxMLPool.cc | csachs/FluxML | 6a46492833a4f0660fc3f2fecd6c166e7de1d167 | [
"MIT"
] | 17 | 2019-07-08T16:53:32.000Z | 2022-02-23T07:20:45.000Z | fluxml/FluxMLPool.cc | csachs/FluxML | 6a46492833a4f0660fc3f2fecd6c166e7de1d167 | [
"MIT"
] | 6 | 2019-07-12T10:26:22.000Z | 2022-02-11T09:46:44.000Z | #include <cstdlib>
#include <cerrno>
#include <cstdio>
#include <xercesc/dom/DOM.hpp>
#include "Error.h"
#include "cstringtools.h"
#include "Notation.h"
#include "Pool.h"
#include "SimLimits.h"
#include "UnicodeTools.h"
#include "XMLElement.h"
#include "FluxMLUnicodeConstants.h"
#include "FluxMLPool.h"
#include "fRegEx.h"
// Xerces C++ Namespace einbinden
XERCES_CPP_NAMESPACE_USE
namespace flux {
namespace xml {
void FluxMLPool::parsePool(DOMNode * node)
{
DOMAttr * attrNode;
DOMNamedNodeMap * nnm;
std::string name;
std::string cfg;
int natoms;
double poolsize = 1.;
if (pool_)
fTHROW(XMLException,"FluxMLPool object already initialized!");
if (not XMLElement::match(node,fml_pool,fml_xmlns_uri))
fTHROW(XMLException,node,"element node (pool) expected.");
// eine Liste der Attribute abfragen
nnm = node->getAttributes();
// das id-Attribut ist erforderlich (#REQUIRED)
attrNode = static_cast< DOMAttr* >(nnm->getNamedItem(fml_id));
if (attrNode == 0)
fTHROW(XMLException,node,"pool lacks the required unique id");
U2A utf_name(attrNode->getValue());
if (not data::Notation::is_varname(utf_name))
fTHROW(XMLException,node,"invalid pool name [%s]",
(char const *)utf_name);
name = utf_name;
// das atoms-Attribut ist optional (default: 0)
attrNode = static_cast< DOMAttr* >(
nnm->getNamedItem(fml_atoms));
if (attrNode != 0)
{
if (not XMLElement::parseInt(attrNode->getValue(),natoms))
{
U2A utf_natoms(attrNode->getValue());
fTHROW(XMLException,"error parsing atoms atrribute: %s",
(char const*)utf_natoms);
}
if (natoms < 0 or natoms > LIMIT_MAX_ATOMS)
fTHROW(XMLException,node,
"specified number of atoms (%i) out of range [0,%i].",
natoms, LIMIT_MAX_ATOMS);
}
else natoms = 0;
// das size-Attribut ist optional (default: 1.0)
attrNode = static_cast< DOMAttr* >(nnm->getNamedItem(fml_size));
if (attrNode != 0)
{
if (not XMLElement::parseDouble(attrNode->getValue(),poolsize))
{
U2A utf_size(attrNode->getValue());
fTHROW(XMLException,node,"error parsing pool size value: %s\n",
(char const*)utf_size);
}
if (poolsize < 0.)
{
U2A utf_size(attrNode->getValue());
fTHROW(XMLException,node,"negative pool size values are not allowed: %s\n",
(char const*)utf_size);
}
}
// das cfg-Attribut ist erforderlich für multi-isotopic Tracer MFA (#OPTIONAL)
attrNode = static_cast< DOMAttr* >(nnm->getNamedItem(fml_cfg));
if (attrNode != 0)
{
U2A utf_cfg(attrNode->getValue());
lib::RegEx rx_cfg("(([a-zA-Z]{2,})|([^CNOPH0-9][0-9]+))");
if(rx_cfg.matches((char const*)utf_cfg))
{
fTHROW(XMLException,node,"error parsing pool attribute [cfg= %s]. \nOnly the following isotopes are supported: C, N."
"\nA valid configuration can be speicified as follow: \"C1H2O3N4\" denotes "
"that one carbon, two hydrogen, three oxygen and four nitrogen are used by ILE.",
(char const *)utf_cfg);
}
cfg = utf_cfg;
}
// Unterhalb des pool-Elements können annotation-Elemente auftauchen.
// Der FluxML-Parser wertet die Informationen dieser Elemente nicht
// aus.
// das Pool-Objekt erzeugen:
pool_ = doc_->createPool(name, natoms, poolsize, cfg);
}
} // namespace flux::xml
} // namespace flux
| 29.669565 | 136 | 0.661782 | csachs |
542dca45b8b1dccfd04973871657bcadc3ffd782 | 304 | hpp | C++ | compat/cqit/qitype/anyfunction.hpp | arntanguy/libqi | 7f3e1394cb26126b26fa7ff54d2de1371a1c9f96 | [
"BSD-3-Clause"
] | 61 | 2015-01-08T08:05:28.000Z | 2022-01-07T16:47:47.000Z | compat/cqit/qitype/anyfunction.hpp | arntanguy/libqi | 7f3e1394cb26126b26fa7ff54d2de1371a1c9f96 | [
"BSD-3-Clause"
] | 30 | 2015-04-06T21:41:18.000Z | 2021-08-18T13:24:51.000Z | compat/cqit/qitype/anyfunction.hpp | arntanguy/libqi | 7f3e1394cb26126b26fa7ff54d2de1371a1c9f96 | [
"BSD-3-Clause"
] | 64 | 2015-02-23T20:01:11.000Z | 2022-03-14T13:31:20.000Z | /*
** Author(s):
** - Cedric GESTES <gestes@aldebaran-robotics.com>
**
** Copyright (C) 2014 Aldebaran
*/
#ifndef _QITYPE_ANYFUNCTION_HPP_
# define _QITYPE_ANYFUNCTION_HPP_
#include <qi/anyfunction.hpp>
#include <qi/macro.hpp>
QI_DEPRECATED_HEADER("Please use qi/anyfunction.hpp instead");
#endif
| 16.888889 | 62 | 0.740132 | arntanguy |
542ede783f441df6159ce024b3ce24ab47e43e44 | 315 | cpp | C++ | test/doublelinkedlist_test.cpp | thm-mni-ii/sea | 3d3f63c3d17ab91f0aaada3c4315ba98367a3460 | [
"MIT"
] | 17 | 2019-01-03T11:17:31.000Z | 2021-10-31T19:19:41.000Z | test/doublelinkedlist_test.cpp | thm-mni-ii/sea | 3d3f63c3d17ab91f0aaada3c4315ba98367a3460 | [
"MIT"
] | 106 | 2018-03-03T16:37:17.000Z | 2020-08-31T09:24:52.000Z | test/doublelinkedlist_test.cpp | thm-mni-ii/sea | 3d3f63c3d17ab91f0aaada3c4315ba98367a3460 | [
"MIT"
] | 4 | 2018-05-21T13:30:01.000Z | 2019-06-12T07:43:43.000Z | #include <gtest/gtest.h>
#include "../src/collection/largedoublelinkedlist.h"
using namespace Sealib; // NOLINT
TEST(DoubleLinkedListTest, basic) {
LargeDoubleLinkedList l(10);
EXPECT_FALSE(l.isEmpty());
EXPECT_EQ(l.get(), 0);
EXPECT_EQ(l.get(), 1);
l.remove(2);
EXPECT_EQ(l.get(), 3);
}
| 22.5 | 52 | 0.663492 | thm-mni-ii |
54302d4e90422ee1f7b40d37518066f34bc68508 | 1,436 | cc | C++ | heyp/alg/rate-limits.cc | uluyol/heyp-agents | 7e45bb636aa6a108e0e9d81a0e9f6e8c744798c6 | [
"MIT"
] | 5 | 2022-01-09T05:55:22.000Z | 2022-03-28T00:21:23.000Z | heyp/alg/rate-limits.cc | uluyol/heyp-agents | 7e45bb636aa6a108e0e9d81a0e9f6e8c744798c6 | [
"MIT"
] | 21 | 2021-08-30T03:22:20.000Z | 2022-01-28T03:22:12.000Z | heyp/alg/rate-limits.cc | uluyol/heyp-agents | 7e45bb636aa6a108e0e9d81a0e9f6e8c744798c6 | [
"MIT"
] | null | null | null | #include "heyp/alg/rate-limits.h"
namespace heyp {
std::ostream& operator<<(std::ostream& os, const RateLimits& limits) {
return os << "(" << limits.hipri_limit_bps << ", " << limits.lopri_limit_bps << ")";
}
double BweBurstinessFactor(const proto::AggInfo& info) {
double parent_demand_bps = info.parent().predicted_demand_bps();
double sum_child_demand_bps = 0;
for (const proto::FlowInfo& c : info.children()) {
sum_child_demand_bps += c.predicted_demand_bps();
}
if (parent_demand_bps == 0 || sum_child_demand_bps == 0) {
return 1;
}
if (sum_child_demand_bps < parent_demand_bps) {
// Due to the fact that we have multiple ways of measuring usage (one-shot average
// over a window, EWMA based on multiple fine-grained values), it's possible that the
// parent has higher demand that the sum of all children.
//
// Rather than try and change usage measurement and demand estimation to make this
// impossible, just handle it here.
return 1.0;
}
return sum_child_demand_bps / parent_demand_bps;
}
int64_t EvenlyDistributeExtra(int64_t admission, const std::vector<int64_t>& demands,
int64_t waterlevel) {
if (demands.empty()) {
return admission;
}
for (int64_t d : demands) {
admission -= std::min(d, waterlevel);
}
admission = std::max<int64_t>(0, admission);
return admission / demands.size();
}
} // namespace heyp
| 31.217391 | 89 | 0.680362 | uluyol |
f9ab184ece87f41cb9093a570a91f750ca128625 | 3,136 | cpp | C++ | test/plugins/condition/test_is_stuck.cpp | Adlink-ROS/nav2_behavior_tree | df7b3bf71eba930efa149d99ab4505d5595c1430 | [
"Apache-2.0"
] | null | null | null | test/plugins/condition/test_is_stuck.cpp | Adlink-ROS/nav2_behavior_tree | df7b3bf71eba930efa149d99ab4505d5595c1430 | [
"Apache-2.0"
] | null | null | null | test/plugins/condition/test_is_stuck.cpp | Adlink-ROS/nav2_behavior_tree | df7b3bf71eba930efa149d99ab4505d5595c1430 | [
"Apache-2.0"
] | null | null | null | // Copyright (c) 2018 Intel Corporation
// Copyright (c) 2020 Sarthak Mittal
//
// 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 <gtest/gtest.h>
#include <chrono>
#include <memory>
#include <set>
#include "rclcpp/rclcpp.hpp"
#include "geometry_msgs/msg/pose_stamped.hpp"
#include "nav2_util/robot_utils.hpp"
#include "../../test_behavior_tree_fixture.hpp"
#include "nav2_behavior_tree/plugins/condition/is_stuck_condition.hpp"
using namespace std::chrono; // NOLINT
using namespace std::chrono_literals; // NOLINT
class IsStuckTestFixture : public nav2_behavior_tree::BehaviorTreeTestFixture
{
public:
void SetUp()
{
bt_node_ = std::make_shared<nav2_behavior_tree::IsStuckCondition>("is_stuck", *config_);
}
void TearDown()
{
bt_node_.reset();
}
protected:
static std::shared_ptr<nav2_behavior_tree::IsStuckCondition> bt_node_;
};
std::shared_ptr<nav2_behavior_tree::IsStuckCondition>
IsStuckTestFixture::bt_node_ = nullptr;
TEST_F(IsStuckTestFixture, test_behavior)
{
auto odom_pub = node_->create_publisher<nav_msgs::msg::Odometry>("odom", 1);
nav_msgs::msg::Odometry odom_msg;
// fill up odometry history with zero velocity
auto time = node_->now();
odom_msg.header.stamp = time;
odom_msg.twist.twist.linear.x = 0.0;
odom_pub->publish(odom_msg);
std::this_thread::sleep_for(500ms);
odom_pub->publish(odom_msg);
std::this_thread::sleep_for(500ms);
EXPECT_EQ(bt_node_->executeTick(), BT::NodeStatus::FAILURE);
// huge negative velocity to simulate sudden brake
odom_msg.header.stamp = time + rclcpp::Duration::from_seconds(0.1);
odom_msg.twist.twist.linear.x = -1.5;
odom_pub->publish(odom_msg);
std::this_thread::sleep_for(500ms);
EXPECT_EQ(bt_node_->executeTick(), BT::NodeStatus::SUCCESS);
// huge positive velocity means robot is not stuck anymore
odom_msg.header.stamp = time + rclcpp::Duration::from_seconds(0.2);
odom_msg.twist.twist.linear.x = 1.0;
odom_pub->publish(odom_msg);
std::this_thread::sleep_for(500ms);
EXPECT_EQ(bt_node_->executeTick(), BT::NodeStatus::FAILURE);
// stuck again due to negative velocity change is smaller time period
odom_msg.header.stamp = time + rclcpp::Duration::from_seconds(0.25);
odom_msg.twist.twist.linear.x = 0.0;
odom_pub->publish(odom_msg);
std::this_thread::sleep_for(500ms);
EXPECT_EQ(bt_node_->executeTick(), BT::NodeStatus::SUCCESS);
}
int main(int argc, char ** argv)
{
::testing::InitGoogleTest(&argc, argv);
// initialize ROS
rclcpp::init(argc, argv);
bool all_successful = RUN_ALL_TESTS();
// shutdown ROS
rclcpp::shutdown();
return all_successful;
}
| 30.745098 | 92 | 0.738839 | Adlink-ROS |
f9ab887a9818e9fa3a2d15da97b21762827202fe | 1,808 | hpp | C++ | level_editor/export/cpp.hpp | xiroV/game-tools | 01b7d4f0269cfdcb70901ed07705d1467ed66f37 | [
"MIT"
] | 1 | 2021-11-05T10:06:16.000Z | 2021-11-05T10:06:16.000Z | level_editor/export/cpp.hpp | xiroV/game-tools | 01b7d4f0269cfdcb70901ed07705d1467ed66f37 | [
"MIT"
] | 24 | 2021-10-03T15:33:16.000Z | 2021-11-29T22:24:57.000Z | level_editor/export/cpp.hpp | xiroV/game-tools | 01b7d4f0269cfdcb70901ed07705d1467ed66f37 | [
"MIT"
] | null | null | null | #ifndef __EXPORT_CPP__
#define __EXPORT_CPP__
#include "exporter.hpp"
#include <sstream>
struct CppExporter : Exporter {
CppExporter() {
setName("C++");
setExtension("hpp");
}
std::string generate(Editor* editor) {
stringstream output;
output << "//version " << editor->version << endl;
output << endl;
output << "#include <string>" << endl;
output << "#include <vector>" << endl;
output << "#include \"level_data.hpp\"" << endl;
output << endl;
output << "struct " << editor->levelName << " : LevelData {"<< endl
<< " std::vector<LevelObject> objects;" << endl;
output << " void init() override {" << endl;
output << " objects = {" << endl;
for (Object const& obj : editor->objects) {
output << " {"
<< obj.x << ", "
<< obj.y << ", "
<< obj.width << ", "
<< obj.height << ", "
<< obj.rotation << ", "
<< "\"" << editor->objectTypes[obj.type].name << "\","
<< "{";
for (ObjectData const& keyValuePair : obj.data) {
output << "{\"" << keyValuePair.key << "\", \"" << keyValuePair.value << "\"},";
}
output << "}";
output << "}," << endl;
}
output << " };" << endl
<< " };" << endl << endl;
output << " std::vector<LevelObject> &getObjects() override {" << endl
<< " return objects;" << endl
<< " }" << endl
<< "};" << endl
<< endl;
return output.str();
}
};
#endif
| 30.133333 | 100 | 0.400442 | xiroV |
f9acf061a969b56be116e9f4506f5b48d03977a4 | 788 | hpp | C++ | include/canard/net/ofp/v13/detail/basic_queue_property.hpp | amedama41/bulb | 2e9fd8a8c35cfc2be2ecf5f747f83cf36ffbbdbb | [
"BSL-1.0"
] | null | null | null | include/canard/net/ofp/v13/detail/basic_queue_property.hpp | amedama41/bulb | 2e9fd8a8c35cfc2be2ecf5f747f83cf36ffbbdbb | [
"BSL-1.0"
] | 8 | 2016-07-21T11:29:13.000Z | 2016-12-03T05:16:42.000Z | include/canard/net/ofp/v13/detail/basic_queue_property.hpp | amedama41/bulb | 2e9fd8a8c35cfc2be2ecf5f747f83cf36ffbbdbb | [
"BSL-1.0"
] | null | null | null | #ifndef CANARD_NET_OFP_V13_QUEUE_PROPERTIES_BAISC_QUEUE_PROPERTY_HPP
#define CANARD_NET_OFP_V13_QUEUE_PROPERTIES_BAISC_QUEUE_PROPERTY_HPP
#include <canard/net/ofp/detail/basic_queue_property.hpp>
#include <canard/net/ofp/v13/openflow.hpp>
namespace canard {
namespace net {
namespace ofp {
namespace v13 {
namespace queue_properties {
namespace queue_property_detail {
template <class T>
using basic_queue_property = ofp::detail::basic_queue_property<
T
, ofp::v13::protocol::ofp_queue_prop_header
, ofp::v13::protocol::ofp_queue_properties
>;
} // namespace queue_property_detail
} // namespace queue_properties
} // namespace v13
} // namespace ofp
} // namespace net
} // namespace canard
#endif // CANARD_NET_OFP_V13_QUEUE_PROPERTIES_BAISC_QUEUE_PROPERTY_HPP
| 27.172414 | 70 | 0.796954 | amedama41 |
f9ae0c07f267178fe9e0d47a92d739f1423e4cf2 | 985 | hpp | C++ | include/saci/qt/radio_btn/radio_btn.hpp | ricardocosme/saci | 2a6a134f63b6e69fde452e0fe9bb5acfd149a6e4 | [
"BSL-1.0"
] | 1 | 2020-07-29T20:42:58.000Z | 2020-07-29T20:42:58.000Z | include/saci/qt/radio_btn/radio_btn.hpp | ricardocosme/saci | 2a6a134f63b6e69fde452e0fe9bb5acfd149a6e4 | [
"BSL-1.0"
] | null | null | null | include/saci/qt/radio_btn/radio_btn.hpp | ricardocosme/saci | 2a6a134f63b6e69fde452e0fe9bb5acfd149a6e4 | [
"BSL-1.0"
] | null | null | null |
// Copyright Ricardo Calheiros de Miranda Cosme 2018.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#pragma once
#include "saci/qt/base_widget.hpp"
#include "saci/qt/radio_btn/detail/view_to_model.hpp"
#include <QRadioButton>
namespace saci { namespace qt {
struct radio_btn
: base_widget<
QRadioButton,
bool,
detail::radio_btn_to_model
>
{
using base = base_widget<QRadioButton,
bool,
detail::radio_btn_to_model>;
radio_btn() = default;
template<typename ObservableObject>
radio_btn(ObservableObject& model, QRadioButton& widget)
: base(model,
widget,
SIGNAL(toggled(bool)),
SLOT(propagates(bool)),
[](QRadioButton& widget, bool v)
{ widget.setChecked(v); })
{}
};
}}
| 24.02439 | 61 | 0.598985 | ricardocosme |
f9b3f5b5a0ad2fea452a20a10754d26251db1b3a | 2,015 | cpp | C++ | C9_Histogram/Template/main.cpp | StarryThrone/OpenCV_Learning_Notes | b52151f443cdde38daf1962b7dc5429b0f050f13 | [
"MIT"
] | 2 | 2020-09-03T09:49:23.000Z | 2021-06-11T09:20:13.000Z | C9_Histogram/Template/main.cpp | StarryThrone/OpenCV_Learning_Notes | b52151f443cdde38daf1962b7dc5429b0f050f13 | [
"MIT"
] | null | null | null | C9_Histogram/Template/main.cpp | StarryThrone/OpenCV_Learning_Notes | b52151f443cdde38daf1962b7dc5429b0f050f13 | [
"MIT"
] | 1 | 2020-09-03T09:49:30.000Z | 2020-09-03T09:49:30.000Z | //
// main.cpp
// Template
//
// Created by chenjie on 2020/7/15.
// Copyright © 2020 chenjie. All rights reserved.
//
#include <iostream>
#include <opencv2/core.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/imgproc.hpp>
void help(const char * argv[]) {
std::cout << "\n"
<< "\nExample: using matchTemplate(). The call is:\n"
<< "\n"
<< argv [0] << " <template> <image_to_be_searched?\n"
<< "\nExample:\n" << argv[0] << "../BlueCup.jpg ../adrian.jpg"
<< "\n"
<< " This routine will search using all methods:\n"
<< " cv::TM_SQDIFF 0\n"
<< " cv::TM_SQDIFF_NORMED 1\n"
<< " cv::TM_CCORR 2\n"
<< " cv::TM_CCORR_NORMED 3\n"
<< " cv::TM_CCOEFF 4\n"
<< " cv::TM_CCOEFF_NORMED 5\n"
<< "\n" << std::endl;
}
int main(int argc, const char * argv[]) {
if (argc != 3) {
help(argv);
return -1;
}
// 读取匹配模版图像
cv::Mat templ = cv::imread(argv[1], 1);
if (templ.empty()) {
std::cout << "Error on reading template " << argv[1] << std::endl;
help(argv);
return -1;
}
// 读取待查找图像
cv::Mat src = cv::imread(argv[2], 1);
if (src.empty()) {
std::cout << "Error on reading src image " << argv[2] << std::endl;
help(argv);
return -1;
}
// 使用6种不同的方法执行模版匹配操作
cv::Mat ftmp[6];
for (int i = 0; i < 6; ++i) {
cv::matchTemplate( src, templ, ftmp[i], i);
cv::normalize(ftmp[i],ftmp[i],1,0,cv::NORM_MINMAX);
}
// 显示匹配结果
cv::imshow("Template", templ);
cv::imshow("Image", src);
cv::imshow("SQDIFF", ftmp[0]);
cv::imshow("SQDIFF_NORMED", ftmp[1]);
cv::imshow("CCORR", ftmp[2]);
cv::imshow("CCORR_NORMED", ftmp[3]);
cv::imshow("CCOEFF", ftmp[4]);
cv::imshow("CCOEFF_NORMED", ftmp[5]);
// 挂起程序等待用户输入事件
cv::waitKey(0);
return 0;
}
| 26.866667 | 78 | 0.490819 | StarryThrone |
f9b4a1508c4c5b829284aee2916c8ea773395087 | 455 | cpp | C++ | CSCI-104/hw7/hw7-test/tests/rotate_test/stress2.cpp | liyang990803/CSCI-103 | 6f84fbc242be90f7a9c3a58bdcc6f54352e4ae5a | [
"MIT"
] | null | null | null | CSCI-104/hw7/hw7-test/tests/rotate_test/stress2.cpp | liyang990803/CSCI-103 | 6f84fbc242be90f7a9c3a58bdcc6f54352e4ae5a | [
"MIT"
] | null | null | null | CSCI-104/hw7/hw7-test/tests/rotate_test/stress2.cpp | liyang990803/CSCI-103 | 6f84fbc242be90f7a9c3a58bdcc6f54352e4ae5a | [
"MIT"
] | 1 | 2018-03-23T04:19:24.000Z | 2018-03-23T04:19:24.000Z | #include "rotate_gtest_class.h"
TEST_F(RotateTest, Stress2_RightRotate)
{
InsertFull(mBST1, 14);
InsertFull(mBST2, 15);
InsertFull(mBST3, 16);
std::clock_t t1 = std::clock();
mBST1.exposedRightRotate(mBST1.getRoot());
std::clock_t t2 = std::clock();
mBST2.exposedRightRotate(mBST2.getRoot());
std::clock_t t3 = std::clock();
mBST3.exposedRightRotate(mBST3.getRoot());
std::clock_t t4 = std::clock();
CheckRuntime(t1, t2, t3, t4, 5, 2);
} | 21.666667 | 43 | 0.701099 | liyang990803 |
f9b621e1b5224710b65b5ac0ba9c61a63ac17024 | 8,348 | cpp | C++ | src/_i18n/charsets/Charset_ISO_8859_16_2001.inc.cpp | TheDoubleB/acpl | cae3169da73bbec9fcab261ba01b2170d3a22de2 | [
"BSD-3-Clause"
] | null | null | null | src/_i18n/charsets/Charset_ISO_8859_16_2001.inc.cpp | TheDoubleB/acpl | cae3169da73bbec9fcab261ba01b2170d3a22de2 | [
"BSD-3-Clause"
] | null | null | null | src/_i18n/charsets/Charset_ISO_8859_16_2001.inc.cpp | TheDoubleB/acpl | cae3169da73bbec9fcab261ba01b2170d3a22de2 | [
"BSD-3-Clause"
] | null | null | null | #ifndef ACPL_I18N_CHARSETS_CHARSET_ISO_8859_16_2001_INC_CPP
#define ACPL_I18N_CHARSETS_CHARSET_ISO_8859_16_2001_INC_CPP
// WARNING: Do not modify this file because it was generated using i18nproc
#include "../../Charsets.h"
#include "../../_cp/Memory.inc.cpp"
namespace acpl
{
namespace i18n
{
class Charset_ISO_8859_16_2001
{
public:
static inline bool IsCompatible(const char *nMimeName, acpl::Charsets::ByteOrderMask nBom, acpl::Charsets::Fpc &nFpc)
{
if (nMimeName != NULL &&
acpl::pi::_string_ascii_strcasecmp(nMimeName, "ISO-8859-16") != 0 &&
acpl::pi::_string_ascii_strcasecmp(nMimeName, "ISO_8859-16") != 0 &&
acpl::pi::_string_ascii_strcasecmp(nMimeName, "latin10") != 0 &&
acpl::pi::_string_ascii_strcasecmp(nMimeName, "l10") != 0 &&
acpl::pi::_string_ascii_strcasecmp(nMimeName, "iso-ir-226") != 0)
return false;
if (nBom != acpl::Charsets::bomNone)
return false;
nFpc.Set(
IsCompatible,
GetMimeName,
IsBomSuggested,
CreateBom,
MinSeqSize,
MaxSeqSize,
Decode,
Encode
);
return true;
}
static inline const char *GetMimeName()
{
return "ISO-8859-16";
}
static inline bool IsBomSuggested()
{
return false;
}
static inline acpl::SizeT CreateBom(acpl::UInt8 *, acpl::SizeT)
{
return 0;
}
static inline acpl::SizeT MinSeqSize()
{
return 1;
}
static inline acpl::SizeT MaxSeqSize()
{
return 1;
}
static inline acpl::SizeT Decode(const acpl::UInt8 *nBfr, acpl::SizeT nBfrSize, acpl::Unichar &nUnicodeChar)
{
if (nBfrSize >= 1)
{
acpl::UInt8 oChar = *nBfr;
// Mirror mappings
if (
oChar <= 0xA0 ||
oChar == 0xA7 ||
oChar == 0xA9 ||
oChar == 0xAB ||
oChar == 0xAD ||
(oChar >= 0xB0 && oChar <= 0xB1) ||
(oChar >= 0xB6 && oChar <= 0xB7) ||
oChar == 0xBB ||
(oChar >= 0xC0 && oChar <= 0xC2) ||
oChar == 0xC4 ||
(oChar >= 0xC6 && oChar <= 0xCF) ||
(oChar >= 0xD2 && oChar <= 0xD4) ||
oChar == 0xD6 ||
(oChar >= 0xD9 && oChar <= 0xDC) ||
(oChar >= 0xDF && oChar <= 0xE2) ||
oChar == 0xE4 ||
(oChar >= 0xE6 && oChar <= 0xEF) ||
(oChar >= 0xF2 && oChar <= 0xF4) ||
oChar == 0xF6 ||
(oChar >= 0xF9 && oChar <= 0xFC) ||
oChar == 0xFF
)
{
nUnicodeChar = static_cast<acpl::Unichar>(oChar);
return 1;
}
// Unique mappings
if (oChar == 0xA1) nUnicodeChar = 0x0104; else
if (oChar == 0xA2) nUnicodeChar = 0x0105; else
if (oChar == 0xA3) nUnicodeChar = 0x0141; else
if (oChar == 0xA4) nUnicodeChar = 0x20AC; else
if (oChar == 0xA5) nUnicodeChar = 0x201E; else
if (oChar == 0xA6) nUnicodeChar = 0x0160; else
if (oChar == 0xA8) nUnicodeChar = 0x0161; else
if (oChar == 0xAA) nUnicodeChar = 0x0218; else
if (oChar == 0xAC) nUnicodeChar = 0x0179; else
if (oChar == 0xAE) nUnicodeChar = 0x017A; else
if (oChar == 0xAF) nUnicodeChar = 0x017B; else
if (oChar == 0xB2) nUnicodeChar = 0x010C; else
if (oChar == 0xB3) nUnicodeChar = 0x0142; else
if (oChar == 0xB4) nUnicodeChar = 0x017D; else
if (oChar == 0xB5) nUnicodeChar = 0x201D; else
if (oChar == 0xB8) nUnicodeChar = 0x017E; else
if (oChar == 0xB9) nUnicodeChar = 0x010D; else
if (oChar == 0xBA) nUnicodeChar = 0x0219; else
if (oChar == 0xBC) nUnicodeChar = 0x0152; else
if (oChar == 0xBD) nUnicodeChar = 0x0153; else
if (oChar == 0xBE) nUnicodeChar = 0x0178; else
if (oChar == 0xBF) nUnicodeChar = 0x017C; else
if (oChar == 0xC3) nUnicodeChar = 0x0102; else
if (oChar == 0xC5) nUnicodeChar = 0x0106; else
if (oChar == 0xD0) nUnicodeChar = 0x0110; else
if (oChar == 0xD1) nUnicodeChar = 0x0143; else
if (oChar == 0xD5) nUnicodeChar = 0x0150; else
if (oChar == 0xD7) nUnicodeChar = 0x015A; else
if (oChar == 0xD8) nUnicodeChar = 0x0170; else
if (oChar == 0xDD) nUnicodeChar = 0x0118; else
if (oChar == 0xDE) nUnicodeChar = 0x021A; else
if (oChar == 0xE3) nUnicodeChar = 0x0103; else
if (oChar == 0xE5) nUnicodeChar = 0x0107; else
if (oChar == 0xF0) nUnicodeChar = 0x0111; else
if (oChar == 0xF1) nUnicodeChar = 0x0144; else
if (oChar == 0xF5) nUnicodeChar = 0x0151; else
if (oChar == 0xF7) nUnicodeChar = 0x015B; else
if (oChar == 0xF8) nUnicodeChar = 0x0171; else
if (oChar == 0xFD) nUnicodeChar = 0x0119; else
if (oChar == 0xFE) nUnicodeChar = 0x021B; else
return 0;
return 1;
}
return 0;
}
static inline acpl::SizeT Encode(acpl::Unichar nUnicodeChar, acpl::UInt8 *nBfr, acpl::SizeT nBfrSize)
{
if (nBfrSize >= 1)
{
// Mirror mappings
if (
nUnicodeChar <= 0xA0 ||
nUnicodeChar == 0xA7 ||
nUnicodeChar == 0xA9 ||
nUnicodeChar == 0xAB ||
nUnicodeChar == 0xAD ||
(nUnicodeChar >= 0xB0 && nUnicodeChar <= 0xB1) ||
(nUnicodeChar >= 0xB6 && nUnicodeChar <= 0xB7) ||
nUnicodeChar == 0xBB ||
(nUnicodeChar >= 0xC0 && nUnicodeChar <= 0xC2) ||
nUnicodeChar == 0xC4 ||
(nUnicodeChar >= 0xC6 && nUnicodeChar <= 0xCF) ||
(nUnicodeChar >= 0xD2 && nUnicodeChar <= 0xD4) ||
nUnicodeChar == 0xD6 ||
(nUnicodeChar >= 0xD9 && nUnicodeChar <= 0xDC) ||
(nUnicodeChar >= 0xDF && nUnicodeChar <= 0xE2) ||
nUnicodeChar == 0xE4 ||
(nUnicodeChar >= 0xE6 && nUnicodeChar <= 0xEF) ||
(nUnicodeChar >= 0xF2 && nUnicodeChar <= 0xF4) ||
nUnicodeChar == 0xF6 ||
(nUnicodeChar >= 0xF9 && nUnicodeChar <= 0xFC) ||
nUnicodeChar == 0xFF
)
{
*nBfr = static_cast<acpl::UInt8>(nUnicodeChar);
return 1;
}
// Unique mappings
if (nUnicodeChar == 0x0104) *nBfr = 0xA1; else
if (nUnicodeChar == 0x0105) *nBfr = 0xA2; else
if (nUnicodeChar == 0x0141) *nBfr = 0xA3; else
if (nUnicodeChar == 0x20AC) *nBfr = 0xA4; else
if (nUnicodeChar == 0x201E) *nBfr = 0xA5; else
if (nUnicodeChar == 0x0160) *nBfr = 0xA6; else
if (nUnicodeChar == 0x0161) *nBfr = 0xA8; else
if (nUnicodeChar == 0x0218) *nBfr = 0xAA; else
if (nUnicodeChar == 0x0179) *nBfr = 0xAC; else
if (nUnicodeChar == 0x017A) *nBfr = 0xAE; else
if (nUnicodeChar == 0x017B) *nBfr = 0xAF; else
if (nUnicodeChar == 0x010C) *nBfr = 0xB2; else
if (nUnicodeChar == 0x0142) *nBfr = 0xB3; else
if (nUnicodeChar == 0x017D) *nBfr = 0xB4; else
if (nUnicodeChar == 0x201D) *nBfr = 0xB5; else
if (nUnicodeChar == 0x017E) *nBfr = 0xB8; else
if (nUnicodeChar == 0x010D) *nBfr = 0xB9; else
if (nUnicodeChar == 0x0219) *nBfr = 0xBA; else
if (nUnicodeChar == 0x0152) *nBfr = 0xBC; else
if (nUnicodeChar == 0x0153) *nBfr = 0xBD; else
if (nUnicodeChar == 0x0178) *nBfr = 0xBE; else
if (nUnicodeChar == 0x017C) *nBfr = 0xBF; else
if (nUnicodeChar == 0x0102) *nBfr = 0xC3; else
if (nUnicodeChar == 0x0106) *nBfr = 0xC5; else
if (nUnicodeChar == 0x0110) *nBfr = 0xD0; else
if (nUnicodeChar == 0x0143) *nBfr = 0xD1; else
if (nUnicodeChar == 0x0150) *nBfr = 0xD5; else
if (nUnicodeChar == 0x015A) *nBfr = 0xD7; else
if (nUnicodeChar == 0x0170) *nBfr = 0xD8; else
if (nUnicodeChar == 0x0118) *nBfr = 0xDD; else
if (nUnicodeChar == 0x021A) *nBfr = 0xDE; else
if (nUnicodeChar == 0x0103) *nBfr = 0xE3; else
if (nUnicodeChar == 0x0107) *nBfr = 0xE5; else
if (nUnicodeChar == 0x0111) *nBfr = 0xF0; else
if (nUnicodeChar == 0x0144) *nBfr = 0xF1; else
if (nUnicodeChar == 0x0151) *nBfr = 0xF5; else
if (nUnicodeChar == 0x015B) *nBfr = 0xF7; else
if (nUnicodeChar == 0x0171) *nBfr = 0xF8; else
if (nUnicodeChar == 0x0119) *nBfr = 0xFD; else
if (nUnicodeChar == 0x021B) *nBfr = 0xFE; else
return 0;
return 1;
}
return 0;
}
};
}
}
#endif // ACPL_I18N_CHARSETS_CHARSET_ISO_8859_16_2001_INC_CPP
| 35.07563 | 121 | 0.575827 | TheDoubleB |
f9b841c6213e9dde8c55f85a4a06483e99ba95d9 | 1,939 | cc | C++ | swapmc/modules_swap.cc | muhammadhasyim/montecarlo-swap | d99b316ae3e8b08a056ec5f639cbb78b0d5848b3 | [
"BSD-3-Clause"
] | null | null | null | swapmc/modules_swap.cc | muhammadhasyim/montecarlo-swap | d99b316ae3e8b08a056ec5f639cbb78b0d5848b3 | [
"BSD-3-Clause"
] | null | null | null | swapmc/modules_swap.cc | muhammadhasyim/montecarlo-swap | d99b316ae3e8b08a056ec5f639cbb78b0d5848b3 | [
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2009-2019 The Regents of the University of Michigan
// This file is part of the HOOMD-blue project, released under the BSD 3-Clause License.
// Include the defined classes that are to be exported to python
//#include <hoomd/hpmc/IntegratorHPMC.h>
//#include <hoomd/hpmc/IntegratorHPMCMono.h>
#include "PatchEnergyJITCustom.h"
#include "IntegratorHPMCPolydisperse.h"
#include "ShapePolydisperse.h"
#include "ShapeProxySwap.h"
#include "UpdaterBoxMCSwap.h"
/*
//#include <hoomd/hpmc/GPUTree.h>
#ifdef ENABLE_CUDA
#include "IntegratorHPMCMonoGPU.h"
#endif
*/
#include "modules_swap.h"
/*! \file module.cc
\brief Export classes to python
*/
using namespace hpmc;
using namespace std;
namespace py = pybind11;
namespace hpmc
{
//! HPMC implementation details
/*! The detail namespace contains classes and functions that are not part of the HPMC public interface. These are
subject to change without notice and are designed solely for internal use within HPMC.
*/
namespace detail
{
// could move the make_param functions back??
}; // end namespace detail
}; // end namespace hpmc
using namespace hpmc::detail;
//! Define the _hpmc python module exports
PYBIND11_MODULE(_swapmc, m)
{
export_IntegratorHPMCSwap(m);
//export_IntegratorHPMCTest(m);
export_UpdaterBoxMCSwap(m);
//export_external_fields(m);
export_sph_poly_params(m);
//export_shapetest_params(m);
export_PatchEnergyJITCustom(m);
//export_point(m);
export_sph_poly(m);
py::class_<sph_poly_params, std::shared_ptr<sph_poly_params> >(m, "sph_poly_params", py::module_local());
m.def("make_sph_poly_params", &make_sph_poly_params);
m.def("make_overlapreal3", &make_overlapreal3);
m.def("make_overlapreal4", &make_overlapreal4);
// export counters
//export_hpmc_implicit_counters(m); //<< check if this is part of mono or monoimplicit
//export_hpmc_clusters_counters(m);
}
| 26.930556 | 113 | 0.741104 | muhammadhasyim |
f9ba535a534d174b4e4fe63eaf45c5f8e6fc2f59 | 7,950 | cpp | C++ | playing/renderer/yas_playing_renderer.cpp | objective-audio/playing | b1bfe5f7e73d182717efafc6fd2e53257e92d8fd | [
"MIT"
] | null | null | null | playing/renderer/yas_playing_renderer.cpp | objective-audio/playing | b1bfe5f7e73d182717efafc6fd2e53257e92d8fd | [
"MIT"
] | null | null | null | playing/renderer/yas_playing_renderer.cpp | objective-audio/playing | b1bfe5f7e73d182717efafc6fd2e53257e92d8fd | [
"MIT"
] | null | null | null | //
// yas_playing_renderer.cpp
//
#include "yas_playing_renderer.h"
#include <audio/yas_audio_graph_io.h>
#include <audio/yas_audio_io.h>
#include <playing/yas_playing_types.h>
using namespace yas;
using namespace yas::playing;
renderer::renderer(audio::io_device_ptr const &device)
: graph(audio::graph::make_shared()),
_device(device),
_rendering_sample_rate(observing::value::holder<sample_rate_t>::make_shared(sample_rate_t{0})),
_rendering_pcm_format(observing::value::holder<audio::pcm_format>::make_shared(audio::pcm_format::other)),
_output_sample_rate(observing::value::holder<sample_rate_t>::make_shared(sample_rate_t{0})),
_output_pcm_format(observing::value::holder<audio::pcm_format>::make_shared(audio::pcm_format::other)),
_sample_rate(observing::value::holder<sample_rate_t>::make_shared(sample_rate_t{0})),
_pcm_format(observing::value::holder<audio::pcm_format>::make_shared(audio::pcm_format::other)),
_channel_count(observing::value::holder<std::size_t>::make_shared(std::size_t(0))),
_format(observing::value::holder<renderer_format>::make_shared(
{.sample_rate = 0, .pcm_format = audio::pcm_format::float32, .channel_count = 0})),
_io(this->graph->add_io(this->_device)),
_converter(audio::graph_avf_au::make_shared(kAudioUnitType_FormatConverter, kAudioUnitSubType_AUConverter)),
_tap(audio::graph_tap::make_shared()) {
this->_update_format();
this->_rendering_sample_rate->observe([this](auto const &) { this->_update_format(); }).end()->add_to(this->_pool);
this->_rendering_pcm_format->observe([this](auto const &) { this->_update_format(); }).end()->add_to(this->_pool);
this->_device->observe_io_device([this](auto const &) { this->_update_format(); }).end()->add_to(this->_pool);
auto set_config_handler = [this] {
this->_format->set_value(renderer_format{.sample_rate = this->_sample_rate->value(),
.pcm_format = this->_pcm_format->value(),
.channel_count = this->_channel_count->value()});
};
this->_sample_rate->observe([set_config_handler](auto const &) { set_config_handler(); })
.end()
->add_to(this->_pool);
this->_pcm_format->observe([set_config_handler](auto const &) { set_config_handler(); }).end()->add_to(this->_pool);
this->_channel_count->observe([set_config_handler](auto const &) { set_config_handler(); })
.sync()
->add_to(this->_pool);
this->_output_sample_rate->observe([this](auto const &) { this->_update_connection(); }).end()->add_to(this->_pool);
this->_output_pcm_format->observe([this](auto const &) { this->_update_connection(); }).end()->add_to(this->_pool);
this->_format->observe([this](auto const &) { this->_update_connection(); }).sync()->add_to(this->_pool);
this->_is_rendering
->observe([this](bool const &is_rendering) {
if (is_rendering) {
this->graph->start_render();
} else {
this->graph->stop();
}
})
.sync()
->add_to(this->_pool);
}
renderer_format const &renderer::format() const {
return this->_format->value();
}
observing::syncable renderer::observe_format(renderer_format_observing_handler_f &&handler) {
return this->_format->observe(std::move(handler));
}
void renderer::set_rendering_sample_rate(sample_rate_t const sample_rate) {
this->_rendering_sample_rate->set_value(sample_rate);
}
void renderer::set_rendering_pcm_format(audio::pcm_format const pcm_format) {
this->_rendering_pcm_format->set_value(pcm_format);
}
void renderer::set_rendering_handler(renderer_rendering_f &&handler) {
this->_tap->set_render_handler([handler = std::move(handler)](audio::node_render_args const &args) {
if (args.bus_idx != 0) {
return;
}
auto const &buffer = args.buffer;
if (buffer->format().is_interleaved()) {
return;
}
if (handler) {
handler(buffer);
}
});
}
void renderer::set_is_rendering(bool const is_rendering) {
this->_is_rendering->set_value(is_rendering);
}
void renderer::_update_format() {
if (auto const &output_format = this->_device->output_format()) {
this->_output_sample_rate->set_value(output_format->sample_rate());
if (auto const &rendering_pcm_format = this->_rendering_pcm_format->value();
rendering_pcm_format != audio::pcm_format::other) {
this->_output_pcm_format->set_value(rendering_pcm_format);
} else {
this->_output_pcm_format->set_value(output_format->pcm_format());
}
this->_sample_rate->set_value(this->_rendering_sample_rate->value() ?: output_format->sample_rate());
this->_channel_count->set_value(output_format->channel_count());
this->_pcm_format->set_value(output_format->pcm_format());
} else {
this->_output_sample_rate->set_value(0);
this->_output_pcm_format->set_value(audio::pcm_format::other);
this->_sample_rate->set_value(0);
this->_channel_count->set_value(0);
this->_pcm_format->set_value(audio::pcm_format::other);
}
}
void renderer::_update_connection() {
if (this->_connection) {
this->graph->disconnect(*this->_connection);
this->_connection = std::nullopt;
}
if (this->_converter_connection) {
this->graph->disconnect(*this->_converter_connection);
this->_converter_connection = std::nullopt;
}
auto const &output_format = this->_device->output_format();
auto const output_sample_rate = output_format.has_value() ? output_format.value().sample_rate() : 0;
auto const output_pcm_format =
output_format.has_value() ? output_format.value().pcm_format() : audio::pcm_format::other;
sample_rate_t const &config_sample_rate = this->_sample_rate->value();
audio::pcm_format const &config_pcm_format = this->_pcm_format->value();
std::size_t const ch_count = this->_channel_count->value();
audio::pcm_format const pcm_format = this->_pcm_format->value();
if (output_sample_rate > 0 && config_sample_rate > 0 && ch_count > 0 && pcm_format != audio::pcm_format::other &&
config_pcm_format != audio::pcm_format::other) {
if (output_sample_rate != config_sample_rate || output_pcm_format != config_pcm_format) {
audio::format const input_format{{.sample_rate = static_cast<double>(config_sample_rate),
.channel_count = static_cast<uint32_t>(ch_count),
.pcm_format = config_pcm_format}};
audio::format const output_format{{.sample_rate = static_cast<double>(output_sample_rate),
.channel_count = static_cast<uint32_t>(ch_count),
.pcm_format = pcm_format}};
this->_converter->raw_au->set_input_format(input_format, 0);
this->_converter->raw_au->set_output_format(output_format, 0);
this->_converter_connection = this->graph->connect(this->_tap->node, this->_converter->node, input_format);
this->_connection = this->graph->connect(this->_converter->node, this->_io->output_node, output_format);
} else {
audio::format const format{{.sample_rate = static_cast<double>(config_sample_rate),
.channel_count = static_cast<uint32_t>(ch_count),
.pcm_format = pcm_format}};
this->_connection = this->graph->connect(this->_tap->node, this->_io->output_node, format);
}
}
}
renderer_ptr renderer::make_shared(audio::io_device_ptr const &device) {
return renderer_ptr(new renderer{device});
}
| 46.491228 | 120 | 0.653962 | objective-audio |
f9c0500254198312e8e26665062d2cba531b2a30 | 1,290 | cpp | C++ | Engine/C_BoxCollider.cpp | SOLID-TEAM/SOLID_ENGINE | 7fa9eccc28217d49a937fcf1dcfc052716825d30 | [
"MIT"
] | 2 | 2019-11-22T23:34:36.000Z | 2019-11-27T10:27:35.000Z | Engine/C_BoxCollider.cpp | SOLID-TEAM/SOLID_ENGINE | 7fa9eccc28217d49a937fcf1dcfc052716825d30 | [
"MIT"
] | null | null | null | Engine/C_BoxCollider.cpp | SOLID-TEAM/SOLID_ENGINE | 7fa9eccc28217d49a937fcf1dcfc052716825d30 | [
"MIT"
] | null | null | null | #include "C_BoxCollider.h"
#include "C_Mesh.h"
#include "GameObject.h"
C_BoxCollider::C_BoxCollider(GameObject* go) : C_Collider(go)
{
name.assign("Box Collider");
type = ComponentType::BOX_COLLIDER;
size = float3::one;
}
void C_BoxCollider::CreateShape(C_Mesh* mesh)
{
if (is_loaded == false)
{
size = (mesh != nullptr) ? mesh->mesh_aabb.Size() : size = float3::one;
center = (mesh != nullptr) ? mesh->mesh_aabb.CenterPoint() : float3::zero;
}
float3 shape_size = float3::one * 0.5f;
shape = new btBoxShape(btVector3(shape_size.x, shape_size.y, shape_size.z));
}
void C_BoxCollider::AdjustShape()
{
scaled_center = center;
float3 scaled_size = size.Mul(linked_go->transform->scale.Abs());
scaled_size = CheckInvalidCollider(scaled_size);
shape->setLocalScaling(btVector3(scaled_size.x, scaled_size.y, scaled_size.z));
}
void C_BoxCollider::SaveCollider(Config& config)
{
config.AddFloatArray("size", (float*)&size, 3);
}
void C_BoxCollider::LoadCollider(Config& config)
{
size = config.GetFloat3("size", { 1.f ,1.f, 1.f });
}
float3 C_BoxCollider::CheckInvalidCollider(float3 size)
{
return size.Max(float3(0.01, 0.01, 0.01));
}
void C_BoxCollider::DrawInfoCollider()
{
ImGui::Title("Size", 1); ImGui::DragFloat3("##size", size.ptr(), 0.1f, 0.01f, FLT_MAX);
}
| 24.807692 | 88 | 0.710853 | SOLID-TEAM |
f9c0d26e22b18d634103e0f8cf7d527f96ac0048 | 56,128 | cpp | C++ | examples/MyFS/myfs.cpp | baz1/SimpleFuse | f047fb327d36f99fde7e05145903eb5630c18679 | [
"0BSD"
] | 2 | 2015-07-02T17:31:10.000Z | 2015-11-09T22:00:40.000Z | examples/MyFS/myfs.cpp | baz1/SimpleFuse | f047fb327d36f99fde7e05145903eb5630c18679 | [
"0BSD"
] | null | null | null | examples/MyFS/myfs.cpp | baz1/SimpleFuse | f047fb327d36f99fde7e05145903eb5630c18679 | [
"0BSD"
] | null | null | null | #include "myfs.h"
#include <string.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <stdio.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <time.h>
#include <QByteArray>
#define READONLY_FS 0
#define DIR_BLOCK_SIZE 0x400
#define REG_BLOCK_SIZE 0x1000
#define MAX_OPEN_FILES 1000
#if DIR_BLOCK_SIZE < REG_BLOCK_SIZE
#define MIN_BLOCK_SIZE DIR_BLOCK_SIZE
#else
#define MIN_BLOCK_SIZE REG_BLOCK_SIZE
#endif
#define SEEK_ERROR ((off_t) (-1))
static char str_buffer[0x100];
/* We will make it single-threaded to avoid any further concurrency issues */
MyFS::MyFS(QString mountPoint, QString filename) : QSimpleFuse(mountPoint, true), filename(convStr(filename)), fd(-1)
{
}
MyFS::~MyFS()
{
delete[] filename;
}
void MyFS::createNewFilesystem(QString filename)
{
char *cFilename = convStr(filename);
int fd = creat(cFilename, 0666);
delete[] cFilename;
if (fd < 0)
{
perror("creat");
return;
}
if (ftruncate(fd, 0x100000) < 0) /* 1MB as a starting size */
{
perror("ftruncate");
close(fd);
return;
}
quint32 addr;
quint16 mshort;
addr = htonl(8);
if (write(fd, &addr, 4) != 4) goto abort;
addr = htonl(DIR_BLOCK_SIZE + 8);
if (write(fd, &addr, 4) != 4) goto abort;
addr = htonl(DIR_BLOCK_SIZE);
if (write(fd, &addr, 4) != 4) goto abort;
addr = 0;
if (write(fd, &addr, 4) != 4) goto abort;
addr = htonl(time(0));
if (write(fd, &addr, 4) != 4) goto abort;
mshort = htons(2);
if (write(fd, &mshort, 2) != 2) goto abort;
mshort = htons(SF_MODE_DIRECTORY | 0777);
if (write(fd, &mshort, 2) != 2) goto abort;
addr = htonl(8);
if (write(fd, &addr, 4) != 4) goto abort;
str_buffer[0] = 1;
if (write(fd, str_buffer, 1) != 1) goto abort;
str_buffer[1] = '.';
if (write(fd, str_buffer + 1, 1) != 1) goto abort;
/* /../ is the same as / (root directory) (overwritten by fuse, but let's do it the right way) */
if (write(fd, &addr, 4) != 4) goto abort;
str_buffer[0] = 2;
if (write(fd, str_buffer, 1) != 1) goto abort;
str_buffer[0] = '.';
if (write(fd, str_buffer, 2) != 2) goto abort;
addr = 0;
if (write(fd, &addr, 4) != 4) goto abort;
if (lseek(fd, DIR_BLOCK_SIZE + 8, SEEK_SET) != DIR_BLOCK_SIZE + 8) goto abort;
addr = htonl(0x100000 - DIR_BLOCK_SIZE - 8);
if (write(fd, &addr, 4) != 4) goto abort;
addr = 0;
if (write(fd, &addr, 4) != 4) goto abort;
close(fd);
return;
abort:
perror("read");
close(fd);
}
void MyFS::sInit()
{
fd = open(filename, O_RDWR);
if (fd < 0)
{
perror("open");
return;
}
if (read(fd, &root_address, 4) != 4)
goto read_error;
root_address = ntohl(root_address);
if (read(fd, &first_blank, 4) != 4)
goto read_error;
first_blank = ntohl(first_blank);
return;
read_error:
perror("read");
close(fd);
fd = -1;
}
void MyFS::sDestroy()
{
if (fd >= 0)
{
close(fd);
fd = -1;
}
}
int MyFS::sGetSize(quint64 &size, quint64 &free)
{
if (fd < 0) return -EIO;
/* Get total size */
off_t length = lseek(fd, 0, SEEK_END);
if (length == SEEK_ERROR)
return -EIO;
size = (quint64) length;
/* Get free size */
free = 0;
if (first_blank)
{
quint32 current = first_blank, to_add;
while (true)
{
if (lseek(fd, current, SEEK_SET) != current)
return -EIO;
if (read(fd, &to_add, 4) != 4)
return -EIO;
to_add = ntohl(to_add);
if (to_add > 8)
free += to_add - 8;
if (read(fd, ¤t, 4) != 4)
return -EIO;
if (!current)
break;
current = ntohl(current);
}
}
return 0;
}
int MyFS::sGetAttr(const lString &pathname, sAttr &attr)
{
if (fd < 0) return -EIO;
quint32 addr;
lString shallowCopy = pathname;
int ret_value = getAddress(shallowCopy, addr);
if (ret_value != 0)
return ret_value;
return myGetAttr(addr, attr);
}
int MyFS::sMkFile(const lString &pathname, quint16 mst_mode)
{
#if READONLY_FS
Q_UNUSED(pathname);
Q_UNUSED(mst_mode);
return -EROFS;
#else
if (fd < 0) return -EIO;
/* Create the file block */
quint32 file;
int ret_value = getBlock(mst_mode & SF_MODE_DIRECTORY ? DIR_BLOCK_SIZE : REG_BLOCK_SIZE, file);
if (ret_value != 0)
return ret_value;
quint32 addr = htonl(time(0));
if (write(fd, &addr, 4) != 4)
return -EIO;
quint16 mshort = htons((mst_mode & SF_MODE_DIRECTORY) ? 2 : 1);
if (write(fd, &mshort, 2) != 2)
return -EIO;
mshort = htons(mst_mode);
if (write(fd, &mshort, 2) != 2)
return -EIO;
if (mst_mode & SF_MODE_DIRECTORY)
{
addr = htonl(file);
if (write(fd, &addr, 4) != 4)
return -EIO;
str_buffer[0] = 1;
if (write(fd, str_buffer, 1) != 1)
return -EIO;
str_buffer[1] = '.';
if (write(fd, str_buffer + 1, 1) != 1)
return -EIO;
addr = 0; /* Temporary null address */
if (write(fd, &addr, 4) != 4)
return -EIO;
str_buffer[0] = 2;
if (write(fd, str_buffer, 1) != 1)
return -EIO;
str_buffer[0] = '.';
if (write(fd, str_buffer, 2) != 2)
return -EIO;
addr = 0;
if (write(fd, &addr, 4) != 4)
return -EIO;
/* Link to pathname */
ret_value = myLink(file, pathname, &addr);
if (ret_value != 0)
return ret_value;
/* Change reference to parent directory */
if (lseek(fd, file + 22, SEEK_SET) == SEEK_ERROR)
return -EIO;
addr = htonl(addr);
if (write(fd, &addr, 4) != 4)
return -EIO;
} else {
quint32 fsize = 0;
if (write(fd, &fsize, 4) != 4)
return -EIO;
/* Link to pathname */
return myLink(file, pathname);
}
return 0;
#endif /* READONLY_FS */
}
int MyFS::sRmFile(const lString &pathname, bool isDir)
{
#if READONLY_FS
Q_UNUSED(pathname);
Q_UNUSED(isDir);
return -EROFS;
#else
if (fd < 0) return -EIO;
return myUnlink(pathname, isDir);
#endif /* READONLY_FS */
}
int MyFS::sMvFile(const lString &pathBefore, const lString &pathAfter)
{
#if READONLY_FS
Q_UNUSED(pathBefore);
Q_UNUSED(pathAfter);
return -EROFS;
#else
if (fd < 0) return -EIO;
bool isDir;
quint32 file;
int ret_value = myUnlink(pathBefore, isDir, &file);
if (ret_value != 0)
return ret_value;
if (isDir)
{
quint32 parentAddr;
ret_value = myLink(file, pathAfter, &parentAddr);
if (ret_value != 0)
return ret_value;
/* Change reference to parent directory */
quint32 next_block;
if (lseek(fd, file + 4, SEEK_SET) == SEEK_ERROR)
return -EIO;
if (read(fd, &next_block, 4) != 4)
return -EIO;
if (lseek(fd, 8, SEEK_CUR) == SEEK_ERROR)
return -EIO;
while (true)
{
quint32 addr;
if (read(fd, &addr, 4) != 4)
return -EIO;
if (!addr)
{
if (!next_block)
return -EIO; /* Corrupted data */
next_block = ntohl(next_block) + 4;
if (lseek(fd, next_block, SEEK_SET) != next_block)
return -EIO;
if (read(fd, &next_block, 4) != 4)
return -EIO;
continue;
}
unsigned char nameLen;
if (read(fd, &nameLen, 1) != 1)
return -EIO;
if (read(fd, &str_buffer, nameLen) != nameLen)
return -EIO;
if ((nameLen == 2) && (memcmp("..", str_buffer, 2) == 0))
{
if (lseek(fd, -7, SEEK_CUR) == SEEK_ERROR)
return -EIO;
parentAddr = htonl(parentAddr);
if (write(fd, &parentAddr, 4) != 4)
return -EIO;
return 0;
}
}
} else {
return myLink(file, pathAfter);
}
#endif /* READONLY_FS */
}
int MyFS::sLink(const lString &pathFrom, const lString &pathTo)
{
#if READONLY_FS
Q_UNUSED(pathFrom);
Q_UNUSED(pathTo);
return -EROFS;
#else
if (fd < 0) return -EIO;
quint32 addrTo;
lString shallowCopy = pathTo;
int ret_value = getAddress(shallowCopy, addrTo);
if (ret_value != 0)
return ret_value;
if (lseek(this->fd, addrTo + 12, SEEK_SET) == SEEK_ERROR)
return -EIO;
quint16 nlink, mshort;
if (read(this->fd, &nlink, 2) != 2)
return -EIO;
nlink = ntohs(nlink);
if (nlink == 0xFFFF)
return -EMLINK;
if (read(this->fd, &mshort, 2) != 2)
return -EIO;
mshort = ntohs(mshort);
if (mshort & SF_MODE_DIRECTORY)
return -EPERM;
ret_value = myLink(addrTo, pathFrom);
if (ret_value != 0)
return ret_value;
if (lseek(this->fd, addrTo + 12, SEEK_SET) == SEEK_ERROR)
return -EIO;
nlink = htons(nlink + 1);
if (write(this->fd, &nlink, 2) != 2)
return -EIO;
return 0;
#endif /* READONLY_FS */
}
int MyFS::sChMod(const lString &pathname, quint16 mst_mode)
{
#if READONLY_FS
Q_UNUSED(pathname);
Q_UNUSED(mst_mode);
return -EROFS;
#else
if (fd < 0) return -EIO;
quint32 nodeAddr;
quint16 mshort;
lString shallowCopy = pathname;
int ret_value = getAddress(shallowCopy, nodeAddr);
if (ret_value != 0)
return ret_value;
nodeAddr += 14;
if (lseek(fd, nodeAddr, SEEK_SET) != nodeAddr)
return -EIO;
if (read(fd, &mshort, 2) != 2)
return -EIO;
mshort = ntohs(mshort);
mshort = (mshort & (~0x1FF)) | (mst_mode & 0x1FF);
if (lseek(fd, nodeAddr, SEEK_SET) != nodeAddr)
return -EIO;
mshort = htons(mshort);
if (write(fd, &mshort, 2) != 2)
return -EIO;
return 0;
#endif /* READONLY_FS */
}
int MyFS::sTruncate(const lString &pathname, quint64 newsize)
{
#if READONLY_FS
Q_UNUSED(pathname);
Q_UNUSED(newsize);
return -EROFS;
#else
if (fd < 0) return -EIO;
if (newsize > 0xFFFFFFFFL)
return -EINVAL;
quint32 nodeAddr;
quint16 mshort;
lString shallowCopy = pathname;
int ret_value = getAddress(shallowCopy, nodeAddr);
if (ret_value != 0)
return ret_value;
if (lseek(fd, nodeAddr + 14, SEEK_SET) == SEEK_ERROR)
return -EIO;
if (read(fd, &mshort, 2) != 2)
return -EIO;
mshort = ntohs(mshort);
if (mshort & SF_MODE_DIRECTORY)
return -EISDIR;
if (!(mshort & S_IWUSR))
return -EACCES;
return myTruncate(nodeAddr, (quint32) newsize);
#endif /* READONLY_FS */
}
int MyFS::sUTime(const lString &pathname, time_t mst_atime, time_t mst_mtime)
{
Q_UNUSED(mst_atime);
#if READONLY_FS
Q_UNUSED(pathname);
Q_UNUSED(mst_mtime);
return -EROFS;
#else
if (fd < 0) return -EIO;
quint32 nodeAddr;
quint32 mtime;
lString shallowCopy = pathname;
int ret_value = getAddress(shallowCopy, nodeAddr);
if (ret_value != 0)
return ret_value;
nodeAddr += 8;
if (lseek(fd, nodeAddr, SEEK_SET) != nodeAddr)
return -EIO;
mtime = htonl(mst_mtime);
if (write(fd, &mtime, 4) != 4)
return -EIO;
return 0;
#endif /* READONLY_FS */
}
int MyFS::sOpen(const lString &pathname, int flags, quint32 &fd)
{
if (this->fd < 0) return -EIO;
#if READONLY_FS
if (flags & (O_WRONLY | O_RDWR))
return -EROFS;
#endif /* READONLY_FS */
OpenFile myFile;
lString shallowCopy = pathname;
int ret_value = getAddress(shallowCopy, myFile.nodeAddr);
if (ret_value != 0)
return ret_value;
if (lseek(this->fd, myFile.nodeAddr, SEEK_SET) != myFile.nodeAddr)
return -EIO;
if (read(this->fd, &myFile.partLength, 4) != 4)
return -EIO;
if (read(this->fd, &myFile.nextAddr, 4) != 4)
return -EIO;
if (lseek(this->fd, 6, SEEK_CUR) == SEEK_ERROR)
return -EIO;
quint16 mshort;
if (read(this->fd, &mshort, 2) != 2)
return -EIO;
mshort = ntohs(mshort);
if (mshort & SF_MODE_DIRECTORY)
return -EISDIR;
myFile.flags = (flags & O_NOATIME) ? OPEN_FILE_FLAGS_NOATIME : 0;
if (!(flags & O_WRONLY))
{
myFile.flags |= OPEN_FILE_FLAGS_PREAD;
if (!(mshort & S_IRUSR))
return -EACCES;
}
if (flags & (O_WRONLY | O_RDWR))
{
myFile.flags |= OPEN_FILE_FLAGS_PWRITE;
if (!(mshort & S_IWUSR))
return -EACCES;
} else {
if (flags & O_TRUNC)
return -EACCES;
}
if (flags & O_TRUNC)
{
myFile.fileLength = 0;
if (write(this->fd, &myFile.fileLength, 4) != 4)
return -EIO;
} else {
if (read(this->fd, &myFile.fileLength, 4) != 4)
return -EIO;
myFile.fileLength = ntohl(myFile.fileLength);
}
fd = 0;
while ((fd < (quint32) openFiles.count()) && openFiles.at(fd).nodeAddr) ++fd;
myFile.partLength = ntohl(myFile.partLength);
myFile.nextAddr = ntohl(myFile.nextAddr);
myFile.partAddr = myFile.nodeAddr;
myFile.partOffset = 0;
myFile.isRegular = true;
if ((flags & O_APPEND) && !(flags & O_TRUNC))
{
quint32 available = myFile.partLength - 20;
while (available <= (myFile.fileLength - myFile.partOffset))
{
myFile.partOffset += available;
if (lseek(this->fd, myFile.nextAddr, SEEK_SET) != myFile.nextAddr)
return -EIO;
myFile.partAddr = myFile.nextAddr;
if (read(this->fd, &myFile.partLength, 4) != 4)
return -EIO;
if (read(this->fd, &myFile.nextAddr, 4) != 4)
return -EIO;
myFile.partLength = ntohl(myFile.partLength);
myFile.nextAddr = ntohl(myFile.nextAddr);
available = myFile.partLength - 8;
}
myFile.currentAddr = myFile.partAddr + (myFile.partOffset ? 8 : 20) + (myFile.fileLength - myFile.partOffset);
} else {
myFile.currentAddr = myFile.nodeAddr + 20;
}
if (fd == (quint32) openFiles.count())
{
if (fd > MAX_OPEN_FILES)
return -ENFILE;
openFiles.append(myFile);
} else {
openFiles[fd] = myFile;
}
return 0;
}
int MyFS::sRead(quint32 fd, void *buf, quint32 count, quint64 offset)
{
if ((fd >= (quint32) openFiles.count()) || (!openFiles.at(fd).nodeAddr) || (!openFiles.at(fd).isRegular))
return -EBADF;
if (this->fd < 0) return -EIO;
OpenFile &myFile = openFiles[fd];
if (!(myFile.flags & OPEN_FILE_FLAGS_PREAD))
return -EBADF;
if (offset > myFile.fileLength)
return -EOVERFLOW;
if (offset + count > myFile.fileLength)
count = myFile.fileLength - offset;
if (!setPosition(myFile, offset))
return -EIO;
quint32 toread = qMin((quint32) count, myFile.partLength - (myFile.currentAddr - myFile.partAddr));
if (read(this->fd, buf, toread) != toread)
return -EIO;
if (toread == (quint32) count)
{
myFile.currentAddr += count;
return count;
}
buf = (void*) (((quint8*) buf) + toread);
int original_count = count;
count -= toread;
quint32 available = myFile.partLength - (myFile.partOffset ? 8 : 20);
while (true)
{
myFile.partOffset += available;
if (lseek(this->fd, myFile.nextAddr, SEEK_SET) != myFile.nextAddr)
return -EIO;
myFile.partAddr = myFile.nextAddr;
if (read(this->fd, &myFile.partLength, 4) != 4)
return -EIO;
if (read(this->fd, &myFile.nextAddr, 4) != 4)
return -EIO;
myFile.partLength = ntohl(myFile.partLength);
myFile.nextAddr = ntohl(myFile.nextAddr);
available = myFile.partLength - 8;
toread = qMin((quint32) count, available);
if (read(this->fd, buf, toread) != toread)
return -EIO;
if (toread == (quint32) count)
{
myFile.currentAddr = myFile.partAddr + 8 + count;
return original_count;
}
buf = (void*) (((quint8*) buf) + toread);
count -= toread;
available = myFile.partLength - 8;
}
}
int MyFS::sWrite(quint32 fd, const void *buf, quint32 count, quint64 offset)
{
if ((fd >= (quint32) openFiles.count()) || (!openFiles.at(fd).nodeAddr) || (!openFiles.at(fd).isRegular))
return -EBADF;
if (this->fd < 0) return -EIO;
OpenFile &myFile = openFiles[fd];
if (!(myFile.flags & OPEN_FILE_FLAGS_PWRITE))
return -EBADF;
if (offset + count > myFile.fileLength)
{
if (offset + count > 0xFFFFFFFFL)
return -EFBIG;
int ret_value = myTruncate(myFile.nodeAddr, (quint32) (offset + count));
if (ret_value != 0)
return ret_value;
}
if (!setPosition(myFile, offset))
return -EIO;
quint32 towrite = qMin((quint32) count, myFile.partLength - (myFile.currentAddr - myFile.partAddr));
if (write(this->fd, buf, towrite) != towrite)
return -EIO;
myFile.flags |= OPEN_FILE_FLAGS_MODIFIED;
if (towrite == (quint32) count)
{
myFile.currentAddr += count;
return count;
}
quint8 *mbuf = (quint8*) buf;
mbuf += towrite;
int original_count = count;
count -= towrite;
quint32 available = myFile.partLength - (myFile.partOffset ? 8 : 20);
while (true)
{
myFile.partOffset += available;
if (lseek(this->fd, myFile.nextAddr, SEEK_SET) != myFile.nextAddr)
return -EIO;
myFile.partAddr = myFile.nextAddr;
if (read(this->fd, &myFile.partLength, 4) != 4)
return -EIO;
if (read(this->fd, &myFile.nextAddr, 4) != 4)
return -EIO;
myFile.partLength = ntohl(myFile.partLength);
myFile.nextAddr = ntohl(myFile.nextAddr);
available = myFile.partLength - 8;
towrite = qMin((quint32) count, available);
if (write(this->fd, mbuf, towrite) != towrite)
return -EIO;
if (towrite == (quint32) count)
{
myFile.currentAddr = myFile.partAddr + 8 + count;
return original_count;
}
mbuf += towrite;
count -= towrite;
available = myFile.partLength - 8;
}
}
int MyFS::sSync(quint32 fd)
{
if ((fd >= (quint32) openFiles.count()) || (!openFiles.at(fd).nodeAddr) || (!openFiles.at(fd).isRegular))
return -EBADF;
return 0;
}
int MyFS::sClose(quint32 fd)
{
if ((fd >= (quint32) openFiles.count()) || (!openFiles.at(fd).nodeAddr) || (!openFiles.at(fd).isRegular))
return -EBADF;
OpenFile *file = &openFiles[fd];
if (file->flags & OPEN_FILE_FLAGS_MODIFIED)
{
if (this->fd < 0) return -EIO;
if (lseek(this->fd, file->nodeAddr + 8, SEEK_SET) == SEEK_ERROR)
return -EIO;
quint32 mytime = htonl(time(0));
if (write(this->fd, &mytime, 4) != 4)
return -EIO;
}
file->nodeAddr = 0;
while ((!openFiles.isEmpty()) && (!openFiles.last().nodeAddr))
openFiles.removeLast();
return 0;
}
int MyFS::sOpenDir(const lString &pathname, quint32 &fd)
{
if (this->fd < 0) return -EIO;
OpenFile myDir;
lString shallowCopy = pathname;
int ret_value = getAddress(shallowCopy, myDir.nodeAddr);
if (ret_value != 0)
return ret_value;
if (lseek(this->fd, myDir.nodeAddr + 4, SEEK_SET) == SEEK_ERROR)
return -EIO;
if (read(this->fd, &myDir.nextAddr, 4) != 4)
return -EIO;
if (lseek(this->fd, 6, SEEK_CUR) == SEEK_ERROR)
return -EIO;
quint16 mshort;
if (read(this->fd, &mshort, 2) != 2)
return -EIO;
mshort = ntohs(mshort);
if (mshort & SF_MODE_REGULARFILE)
return -ENOTDIR;
if (!(mshort & S_IRUSR))
return -EACCES;
fd = 0;
while ((fd < (quint32) openFiles.count()) && openFiles.at(fd).nodeAddr) ++fd;
myDir.currentAddr = myDir.nodeAddr + 16;
myDir.nextAddr = ntohl(myDir.nextAddr);
myDir.isRegular = false;
if (fd == (quint32) openFiles.count())
{
if (fd > MAX_OPEN_FILES)
return -ENFILE;
openFiles.append(myDir);
} else {
openFiles[fd] = myDir;
}
return 0;
}
int MyFS::sReadDir(quint32 fd, char *&name)
{
if ((fd >= (quint32) openFiles.count()) || (!openFiles.at(fd).nodeAddr) || openFiles.at(fd).isRegular)
return -EBADF;
if (this->fd < 0) return -EIO;
OpenFile *file = &openFiles[fd];
if (lseek(this->fd, file->currentAddr, SEEK_SET) != file->currentAddr)
return -EIO;
quint32 addr;
while (true)
{
if (read(this->fd, &addr, 4) != 4)
return -EIO;
if (addr == 0)
{
if (!file->nextAddr)
{
name = NULL;
return 0;
}
file->nextAddr += 4;
if (lseek(this->fd, file->nextAddr, SEEK_SET) != file->nextAddr)
goto ioerror;
file->currentAddr = file->nextAddr + 4;
if (read(this->fd, &file->nextAddr, 4) != 4)
goto ioerror;
file->nextAddr = ntohl(file->nextAddr);
continue;
}
unsigned char sLen;
if (read(this->fd, &sLen, 1) != 1)
return -EIO;
if (read(this->fd, str_buffer, sLen) != sLen)
return -EIO;
file->currentAddr += 5;
file->currentAddr += sLen;
str_buffer[sLen] = 0;
name = str_buffer;
return 0;
}
ioerror:
file->nodeAddr = 0;
return -EIO;
}
int MyFS::sCloseDir(quint32 fd)
{
if ((fd >= (quint32) openFiles.count()) || (!openFiles.at(fd).nodeAddr) || openFiles.at(fd).isRegular)
return -EBADF;
OpenFile *file = &openFiles[fd];
file->nodeAddr = 0;
while ((!openFiles.isEmpty()) && (!openFiles.last().nodeAddr))
openFiles.removeLast();
return 0;
}
int MyFS::sAccess(const lString &pathname, quint8 mode)
{
if (fd < 0) return -EIO;
quint32 addr;
lString shallowCopy = pathname;
int ret_value = getAddress(shallowCopy, addr);
if (ret_value != 0)
return ret_value;
if (mode == F_OK)
return 0;
#if READONLY_FS
if (mode & W_OK)
return -EROFS;
#endif /* READONLY_FS */
if (lseek(fd, addr + 14, SEEK_SET) == SEEK_ERROR)
return -EIO;
quint16 mshort;
if (read(fd, &mshort, 2) != 2)
return -EIO;
mshort = ntohs(mshort);
if ((mode & R_OK) && (!(mshort & S_IRUSR)))
return -EACCES;
if ((mode & W_OK) && (!(mshort & S_IWUSR)))
return -EACCES;
if ((mode & X_OK) && (!(mshort & S_IXUSR)))
return -EACCES;
return 0;
}
int MyFS::sFTruncate(quint32 fd, quint64 newsize)
{
#if READONLY_FS
Q_UNUSED(fd);
Q_UNUSED(newsize);
return -EROFS;
#else
if ((fd >= (quint32) openFiles.count()) || (!openFiles.at(fd).nodeAddr) || (!openFiles.at(fd).isRegular))
return -EBADF;
if (this->fd < 0) return -EIO;
if (newsize > 0xFFFFFFFFL)
return -EINVAL;
OpenFile *file = &openFiles[fd];
file->fileLength = (quint32) newsize;
return myTruncate(file->nodeAddr, file->fileLength);
#endif /* READONLY_FS */
}
int MyFS::sFGetAttr(quint32 fd, sAttr &attr)
{
if ((fd >= (quint32) openFiles.count()) || (!openFiles.at(fd).nodeAddr))
return -EBADF;
if (this->fd < 0) return -EIO;
return myGetAttr(openFiles.at(fd).nodeAddr, attr);
}
/* Links the regular file pointed by file to pathname, WITHOUT updating the nlink field */
int MyFS::myLink(quint32 file, const lString &pathname, quint32 *parentAddr)
{
/* Get the last part of the path */
lString shallowCopy = pathname;
if (shallowCopy.str_len == 0)
return -ENOENT;
while ((shallowCopy.str_len > 0) && (shallowCopy.str_value[shallowCopy.str_len - 1] == '/'))
--shallowCopy.str_len;
if (shallowCopy.str_len == 0)
return -EEXIST;
int len = shallowCopy.str_len;
while (shallowCopy.str_value[shallowCopy.str_len - 1] != '/')
--shallowCopy.str_len;
len -= shallowCopy.str_len;
int start = shallowCopy.str_len;
if (len > 0xFF)
return -ENAMETOOLONG;
/* Get the address of the parent directory */
quint32 dirAddr;
int ret_value = getAddress(shallowCopy, dirAddr);
if (ret_value != 0)
return ret_value;
/* Check whether or not this is indeed a directory */
if (lseek(fd, dirAddr, SEEK_SET) != dirAddr)
return -EIO;
quint32 block_size;
if (read(fd, &block_size, 4) != 4)
return -EIO;
block_size = ntohl(block_size);
quint32 next_block;
if (read(fd, &next_block, 4) != 4)
return -EIO;
if (read(fd, str_buffer, 4) != 4)
return -EIO;
quint16 mshort, nlink;
if (read(fd, &nlink, 2) != 2)
return -EIO;
if (read(fd, &mshort, 2) != 2)
return -EIO;
mshort = ntohs(mshort);
if (mshort & SF_MODE_REGULARFILE)
return -ENOTDIR;
/* Check the permissions */
if (!(mshort & S_IWUSR))
return -EACCES;
/* Modify the last modification time */
if (lseek(fd, dirAddr + 8, SEEK_SET) == SEEK_ERROR)
return -EIO;
quint32 linkDate = htonl(time(0));
if (write(fd, &linkDate, 4) != 4)
return -EIO;
/* Add new entry */
quint32 currentPart = dirAddr;
quint32 addr;
if (parentAddr)
{
*parentAddr = dirAddr;
addr = dirAddr + 12;
if (lseek(fd, addr, SEEK_SET) != addr)
return -EIO;
if (nlink == 0xFFFF)
return -EMLINK;
nlink = htons(ntohs(nlink) + 1);
if (write(fd, &nlink, 2) != 2)
return -EIO;
if (read(fd, &mshort, 2) != 2)
return -EIO;
} else {
addr = dirAddr + 16;
if (lseek(fd, addr, SEEK_SET) != addr)
return -EIO;
}
while (true)
{
if (read(fd, &addr, 4) != 4)
return -EIO;
if (addr == 0)
{
off_t currentPos = lseek(fd, 0, SEEK_CUR);
if (currentPos == SEEK_ERROR)
return -EIO;
quint32 used = (quint32) currentPos;
used -= currentPart;
if (block_size - used >= (quint32) len + 5)
{
/* Add entry to the existing list */
currentPos -= 4;
if (lseek(fd, currentPos, SEEK_SET) != currentPos)
return -EIO;
file = htonl(file);
if (write(fd, &file, 4) != 4)
return -EIO;
unsigned char sLen = (unsigned char) len;
if (write(fd, &sLen, 1) != 1)
return -EIO;
if (write(fd, pathname.str_value + start, len) != len)
return -EIO;
if (write(fd, &addr, 4) != 4)
return -EIO;
} else if (next_block != 0)
{
/* Go to the next part */
next_block = ntohl(next_block);
if (lseek(fd, next_block, SEEK_SET) != next_block)
return -EIO;
currentPart = next_block;
if (read(fd, &block_size, 4) != 4)
return -EIO;
block_size = ntohl(block_size);
if (read(fd, &next_block, 4) != 4)
return -EIO;
continue;
} else {
/* Create a new part to add the entry */
ret_value = getBlock(DIR_BLOCK_SIZE, next_block);
if (ret_value != 0)
{
freeBlock(file);
return ret_value;
}
file = htonl(file);
if (write(fd, &file, 4) != 4)
return -EIO;
unsigned char sLen = (unsigned char) len;
if (write(fd, &sLen, 1) != 1)
return -EIO;
if (write(fd, pathname.str_value + start, len) != len)
return -EIO;
if (write(fd, &addr, 4) != 4)
return -EIO;
currentPart += 4;
if (lseek(fd, currentPart, SEEK_SET) != currentPart)
return -EIO;
next_block = htonl(next_block);
if (write(fd, &next_block, 4) != 4)
return -EIO;
}
return 0;
} else {
unsigned char sLen;
if (read(fd, &sLen, 1) != 1)
return -EIO;
if (read(fd, str_buffer, sLen) != sLen)
return -EIO;
if ((sLen == len) && (memcmp(str_buffer, pathname.str_value + start, len) == 0))
{
freeBlock(file);
return -EEXIST;
}
}
}
}
int MyFS::myUnlink(const lString &pathname, bool &isDir, quint32 *nodeAddr)
{
/* Get the last part of the path */
lString shallowCopy = pathname;
if (shallowCopy.str_len == 0)
return -ENOENT;
while ((shallowCopy.str_len > 0) && (shallowCopy.str_value[shallowCopy.str_len - 1] == '/'))
--shallowCopy.str_len;
if (shallowCopy.str_len == 0)
return -EEXIST;
int len = shallowCopy.str_len;
while (shallowCopy.str_value[shallowCopy.str_len - 1] != '/')
--shallowCopy.str_len;
len -= shallowCopy.str_len;
int start = shallowCopy.str_len;
/* Get the address of the parent directory */
quint32 dirAddr, beforeAddr = 0, currentAddr;
int ret_value = getAddress(shallowCopy, dirAddr);
if (ret_value != 0)
return ret_value;
/* Check whether or not this is indeed a directory */
currentAddr = dirAddr + 4;
if (lseek(fd, currentAddr, SEEK_SET) != currentAddr)
return -EIO;
quint32 next_block;
if (read(fd, &next_block, 4) != 4)
return -EIO;
if (read(fd, str_buffer, 4) != 4)
return -EIO;
quint16 mshort;
if (read(fd, &mshort, 2) != 2)
return -EIO;
quint16 nlink = ntohs(mshort);
if (read(fd, &mshort, 2) != 2)
return -EIO;
mshort = ntohs(mshort);
if (mshort & SF_MODE_REGULARFILE)
return -ENOTDIR;
/* Check the permissions */
if (!(mshort & S_IWUSR))
return -EACCES;
/* Look for the pathname entry */
while (true)
{
quint32 addr;
if (read(fd, &addr, 4) != 4)
return -EIO;
if (!addr)
{
if (!next_block)
return -ENOENT;
beforeAddr = currentAddr;
currentAddr = ntohl(next_block) + 4;
if (lseek(fd, currentAddr, SEEK_SET) != currentAddr)
return -EIO;
if (read(fd, &next_block, 4) != 4)
return -EIO;
continue;
}
unsigned char nameLen;
if (read(fd, &nameLen, 1) != 1)
return -EIO;
if (read(fd, &str_buffer, nameLen) != nameLen)
return -EIO;
if ((nameLen == len) && (memcmp(pathname.str_value + start, str_buffer, len) == 0))
{
/* Found it. */
addr = ntohl(addr);
off_t nextEntry = lseek(fd, 0, SEEK_CUR);
if (nextEntry == SEEK_ERROR)
return -EIO;
/* Check if the file is opened. */
for (int i = 0; i < openFiles.count(); ++i)
{
if (openFiles.at(i).nodeAddr == addr)
return -EBUSY;
}
/* Check if isDir has the right value. */
if (lseek(fd, addr + 14, SEEK_SET) != addr + 14)
return -EIO;
if (read(fd, &mshort, 2) != 2)
return -EIO;
mshort = ntohs(mshort);
if (nodeAddr)
{
isDir = (bool) (mshort & SF_MODE_DIRECTORY);
*nodeAddr = addr;
} else {
if (isDir ^ ((bool) (mshort & SF_MODE_DIRECTORY)))
return isDir ? -ENOTDIR : -EISDIR;
/* Remove addr (or just decrease the link counter) */
if (!isDir)
{
if (lseek(fd, addr + 12, SEEK_SET) == SEEK_ERROR)
return -EIO;
if (read(fd, &mshort, 2) != 2)
return -EIO;
mshort = ntohs(mshort) - 1;
if (mshort)
{
if (lseek(fd, -2, SEEK_CUR) == SEEK_ERROR)
return -EIO;
mshort = htons(mshort);
if (write(fd, &mshort, 2) != 2)
return -EIO;
} else {
ret_value = freeBlocks(addr);
if (ret_value != 0)
return ret_value;
}
} else {
/* If this is a directory, check if it is empty */
quint32 myfd;
char *entryName;
ret_value = sOpenDir(pathname, myfd);
if (ret_value != 0)
return ret_value;
while (true)
{
ret_value = sReadDir(myfd, entryName);
if (ret_value != 0)
return ret_value;
if (entryName == NULL)
break;
if (strcmp(entryName, ".") == 0)
continue;
if (strcmp(entryName, "..") == 0)
continue;
sCloseDir(myfd);
return -ENOTEMPTY;
}
sCloseDir(myfd);
/* Remove addr */
ret_value = freeBlocks(addr);
if (ret_value != 0)
return ret_value;
}
}
/* Remove the corresponding entry in the parent */
if (lseek(fd, nextEntry, SEEK_SET) != nextEntry)
return -EIO;
if (read(fd, &addr, 4) != 4)
return -EIO;
if ((!addr) && (((quint32) nextEntry) == currentAddr + 4))
{
/* Empty part to remove */
if (lseek(fd, beforeAddr, SEEK_SET) != beforeAddr)
return -EIO;
if (write(fd, &next_block, 4) != 4)
return -EIO;
ret_value = freeBlock(currentAddr - 4);
if (ret_value != 0)
return ret_value;
} else {
/* Move following entries */
len += 5;
if (lseek(fd, -(len + 4), SEEK_CUR) == SEEK_ERROR)
return -EIO;
if (write(fd, &addr, 4) != 4)
return -EIO;
while (addr)
{
if (lseek(fd, len, SEEK_CUR) == SEEK_ERROR)
return -EIO;
if (read(fd, &nameLen, 1) != 1)
return -EIO;
if (read(fd, &str_buffer, nameLen) != nameLen)
return -EIO;
if (read(fd, &addr, 4) != 4)
return -EIO;
if (lseek(fd, -(len + 5 + (int) nameLen), SEEK_CUR) == SEEK_ERROR)
return -EIO;
if (write(fd, &nameLen, 1) != 1)
return -EIO;
if (write(fd, &str_buffer, nameLen) != nameLen)
return -EIO;
if (write(fd, &addr, 4) != 4)
return -EIO;
}
}
/* Change the last modification time */
dirAddr += 8;
if (lseek(fd, dirAddr, SEEK_SET) != dirAddr)
return -EIO;
addr = htonl(time(0));
if (write(fd, &addr, 4) != 4)
return -EIO;
/* And the number of hard links if need be */
if (isDir)
{
nlink = htons(nlink - 1);
if (write(fd, &nlink, 2) != 2)
return -EIO;
}
return 0;
}
}
}
int MyFS::myGetAttr(quint32 addr, sAttr &attr)
{
addr += 8;
if (lseek(fd, addr, SEEK_SET) != addr)
return -EIO;
if (read(fd, &addr, 4) != 4)
return -EIO;
attr.mst_atime = (time_t) ntohl(addr);
attr.mst_mtime = attr.mst_atime;
quint16 mshort;
if (read(fd, &mshort, 2) != 2)
return -EIO;
attr.mst_nlink = (quint32) ntohs(mshort);
if (read(fd, &mshort, 2) != 2)
return -EIO;
attr.mst_mode = ntohs(mshort);
if (attr.mst_mode & SF_MODE_REGULARFILE)
{
if (read(fd, &addr, 4) != 4)
return -EIO;
attr.mst_size = (quint64) ntohl(addr);
}
return 0;
}
int MyFS::myTruncate(quint32 addr, quint32 newsize)
{
#if READONLY_FS
Q_UNUSED(addr);
Q_UNUSED(newsize);
return -EROFS;
#else
quint32 block_size, next_block, file_size, mytime;
quint32 modifNodeAddr = addr, modifNodeSize = (quint32) newsize, modifNodePart = 0;
if (lseek(fd, addr, SEEK_SET) != addr)
return -EIO;
if (read(fd, &block_size, 4) != 4)
return -EIO;
if (read(fd, &next_block, 4) != 4)
return -EIO;
mytime = htonl(time(0));
if (write(fd, &mytime, 4) != 4)
return -EIO;
if (lseek(fd, 4, SEEK_CUR) == SEEK_ERROR)
return -EIO;
if (read(fd, &file_size, 4) != 4)
return -EIO;
file_size = ntohl(file_size);
if (file_size == newsize)
return 0;
if (file_size < newsize)
{
/* We have to increase the size of the file, by appending zeros at the end */
if (lseek(fd, -4, SEEK_CUR) == SEEK_ERROR)
return -EIO;
quint32 mynewsize = (quint32) newsize;
mynewsize = htonl(mynewsize);
if (write(fd, &mynewsize, 4) != 4)
return -EIO;
bool isFistBlock = true;
block_size = ntohl(block_size) - 20;
while (block_size < file_size)
{
file_size -= block_size;
newsize -= block_size;
if (!next_block)
return -EIO; /* Corrupted data */
next_block = ntohl(next_block);
if (lseek(fd, next_block, SEEK_SET) != next_block)
return -EIO;
addr = next_block;
if (read(fd, &block_size, 4) != 4)
return -EIO;
isFistBlock = false;
block_size = ntohl(block_size) - 8;
if (read(fd, &next_block, 4) != 4)
return -EIO;
}
memset(str_buffer, 0, 0x100);
if (block_size > file_size)
{
if (lseek(fd, addr + (isFistBlock ? 20 : 8) + file_size, SEEK_SET) == SEEK_ERROR)
return -EIO;
if (!myWriteB(qMin(block_size - file_size, (quint32) (newsize - file_size))))
return -EIO;
}
while (newsize > block_size)
{
newsize -= block_size;
if (!next_block)
{
int ret_value = getBlock(newsize + 8, next_block);
if ((ret_value != 0) && (ret_value != -ENOSPC))
return ret_value;
if (ret_value == -ENOSPC)
{
if (next_block <= 8)
return -ENOSPC;
block_size = next_block - 8;
ret_value = getBlock(next_block, next_block);
if (ret_value != 0)
return ret_value;
} else {
block_size = newsize;
}
if (lseek(fd, addr + 4, SEEK_SET) == SEEK_ERROR)
return -EIO;
addr = next_block;
if (!modifNodePart)
modifNodePart = next_block;
next_block = htonl(next_block);
if (write(fd, &next_block, 4) != 4)
return -EIO;
next_block = 0;
if (lseek(fd, addr + 8, SEEK_SET) == SEEK_ERROR)
return -EIO;
} else {
addr = ntohl(next_block);
if (lseek(fd, addr, SEEK_SET) == SEEK_ERROR)
return -EIO;
if (read(fd, &block_size, 4) != 4)
return -EIO;
block_size = ntohl(block_size);
if (read(fd, &next_block, 4) != 4)
return -EIO;
}
if (!myWriteB(qMin(block_size, (quint32) newsize)))
return -EIO;
}
/* Update the file descriptors */
for (int i = 0; i < openFiles.count(); ++i)
{
if (openFiles.at(i).nodeAddr == modifNodeAddr)
{
if (modifNodePart && (!openFiles.at(i).nextAddr))
openFiles[i].nextAddr = modifNodePart;
openFiles[i].fileLength = modifNodeSize;
}
}
return 0;
} else {
/* We have to reduce the size of the file */
if (lseek(fd, -4, SEEK_CUR) == SEEK_ERROR)
return -EIO;
quint32 mynewsize = (quint32) newsize;
mynewsize = htonl(mynewsize);
if (write(fd, &mynewsize, 4) != 4)
return -EIO;
if (!next_block)
return 0;
next_block = ntohl(next_block);
newsize -= ntohl(block_size) - 20;
while (newsize > 0)
{
if (lseek(fd, next_block, SEEK_SET) != next_block)
return -EIO;
addr = next_block;
if (read(fd, &block_size, 4) != 4)
return -EIO;
if (read(fd, &next_block, 4) != 4)
return -EIO;
if (!next_block)
return 0;
next_block = ntohl(next_block);
newsize -= ntohl(block_size) - 8;
}
addr += 4;
if (lseek(fd, addr, SEEK_SET) != addr)
return -EIO;
addr = 0;
if (write(fd, &addr, 4) != 4)
return -EIO;
int ret_value = freeBlocks(next_block);
if (ret_value != 0)
return ret_value;
/* Update the file descriptors */
for (int i = 0; i < openFiles.count(); ++i)
{
if (openFiles.at(i).nodeAddr == modifNodeAddr)
{
if (openFiles.at(i).partOffset >= modifNodeSize)
{
openFiles[i].partAddr = openFiles[i].nodeAddr;
openFiles[i].currentAddr = openFiles[i].nodeAddr + 20;
if (lseek(fd, modifNodeAddr, SEEK_SET) != modifNodeAddr)
return -EIO;
quint32 &pLen = openFiles[i].partLength;
quint32 &pNext = openFiles[i].nextAddr;
if (read(fd, &pLen, 4) != 4)
return -EIO;
pLen = ntohl(pLen);
if (read(fd, &pNext, 4) != 4)
return -EIO;
pNext = ntohl(pNext);
openFiles[i].partOffset = 0;
} else if (openFiles.at(i).partOffset + openFiles.at(i).partLength >= modifNodeSize)
{
openFiles[i].nextAddr = 0;
}
openFiles[i].fileLength = modifNodeSize;
}
}
return 0;
}
#endif /* READONLY_FS */
}
bool MyFS::setPosition(OpenFile &file, quint32 offset)
{
if (offset < file.partOffset)
{
/* Scan the file from the beginning */
file.partAddr = file.nodeAddr;
if (lseek(fd, file.nodeAddr, SEEK_SET) != file.nodeAddr)
return false;
if (read(fd, &file.partLength, 4) != 4)
return false;
if (read(fd, &file.nextAddr, 4) != 4)
return false;
file.partLength = ntohl(file.partLength);
file.nextAddr = ntohl(file.nextAddr);
file.currentAddr = file.nodeAddr + 20;
file.partOffset = 0;
}
/* Scan the file until the right offset range */
quint32 available = file.partLength - (file.partOffset ? 8 : 20);
while (offset >= file.partOffset + available)
{
file.partOffset += available;
if (lseek(fd, file.nextAddr, SEEK_SET) != file.nextAddr)
return false;
file.partAddr = file.nextAddr;
if (read(fd, &file.partLength, 4) != 4)
return false;
if (read(fd, &file.nextAddr, 4) != 4)
return false;
file.partLength = ntohl(file.partLength);
file.nextAddr = ntohl(file.nextAddr);
available = file.partLength - 8;
}
file.currentAddr = file.partAddr + (file.partOffset ? 8 : 20) + (offset - file.partOffset);
if (lseek(fd, file.currentAddr, SEEK_SET) != file.currentAddr)
return -EIO;
return true;
}
bool MyFS::myWriteB(quint32 size)
{
while (size > 0x100)
{
if (write(fd, str_buffer, 0x100) != 0x100)
return false;
size -= 0x100;
}
return (write(fd, str_buffer, size) == size);
}
char *MyFS::convStr(const QString &str)
{
char *result = new char[str.length() + 1];
QByteArray strData = str.toLocal8Bit();
memcpy(result, strData.data(), str.length());
result[str.length()] = 0;
return result;
}
/* Allocates some blocks (linked together), puts the address of the first one into addr and returns 0 on success. */
int MyFS::getBlocks(quint32 size, quint32 &addr)
{
Q_ASSERT(size > 0);
int ret_value;
quint32 next_block = 0;
while (true)
{
ret_value = getBlock(size + 8, addr);
if ((ret_value != 0) && (ret_value != -ENOSPC))
return ret_value;
if (ret_value == 0)
{
if (next_block)
{
if (lseek(fd, -4, SEEK_CUR) != -SEEK_ERROR)
return -EIO;
if (write(fd, &next_block, 4) != 4)
return -EIO;
}
return 0;
}
if (addr <= 8)
{
if (next_block)
freeBlocks(next_block);
return -ENOSPC;
}
size -= addr - 8;
ret_value = getBlock(addr, addr);
if (ret_value != 0)
return ret_value;
if (next_block)
{
if (lseek(fd, -4, SEEK_CUR) != -SEEK_ERROR)
return -EIO;
if (write(fd, &next_block, 4) != 4)
return -EIO;
}
next_block = htonl(addr);
}
}
/* Allocates the block, writes its size in the first 4 bytes, 0 on the 4 next bytes, puts its address into addr and returns 0 on success.
In this case, fd will point to the 9-th byte of that block at the end of the call.
In the case it returns -ENOSPC, addr will contain the maximum free block size. */
int MyFS::getBlock(quint32 size, quint32 &addr)
{
#if READONLY_FS
Q_UNUSED(size);
Q_UNUSED(addr);
return -EROFS;
#else
Q_ASSERT(size > 0);
quint32 currentAddr = first_blank, refAddr = 4, bsize;
addr = 0;
while (true)
{
if (!currentAddr)
return -ENOSPC;
if (lseek(fd, currentAddr, SEEK_SET) != currentAddr)
return -EIO;
if (read(fd, &bsize, 4) != 4)
return -EIO;
bsize = ntohl(bsize);
if (bsize >= size)
{
if (bsize >= size + MIN_BLOCK_SIZE)
{
/* We split the space in two parts */
if (lseek(fd, currentAddr, SEEK_SET) != currentAddr)
return -EIO;
bsize -= size;
addr = currentAddr + bsize;
bsize = htonl(bsize);
if (write(fd, &bsize, 4) != 4)
return -EIO;
if (lseek(fd, addr, SEEK_SET) != addr)
return -EIO;
bsize = htonl(size);
if (write(fd, &bsize, 4) != 4)
return -EIO;
currentAddr = 0;
if (write(fd, ¤tAddr, 4) != 4)
return -EIO;
} else {
/* We use all the space */
addr = currentAddr;
if (read(fd, ¤tAddr, 4) != 4)
return -EIO;
if (lseek(fd, refAddr, SEEK_SET) != refAddr)
return -EIO;
if (write(fd, ¤tAddr, 4) != 4)
return -EIO;
if (lseek(fd, addr + 4, SEEK_SET) != addr + 4)
return -EIO;
bsize = 0;
if (write(fd, &bsize, 4) != 4)
return -EIO;
}
return 0;
} else {
if (bsize > addr)
addr = bsize;
}
refAddr = currentAddr + 4;
if (read(fd, ¤tAddr, 4) != 4)
return -EIO;
currentAddr = ntohl(currentAddr);
}
#endif /* READONLY_FS */
}
/* Frees the block at address addr and its following parts, and returns 0 on success. */
int MyFS::freeBlocks(quint32 addr)
{
int ret_value;
quint32 next_block;
while (true)
{
if (lseek(fd, addr + 4, SEEK_SET) == SEEK_ERROR)
return -EIO;
if (read(fd, &next_block, 4) != 4)
return -EIO;
ret_value = freeBlock(addr);
if (ret_value != 0)
return ret_value;
if (!next_block)
break;
addr = ntohl(next_block);
}
return 0;
}
/* Frees the block at address addr and returns 0 on success. */
int MyFS::freeBlock(quint32 addr)
{
#if READONLY_FS
Q_UNUSED(addr);
return -EROFS;
#else
/* Get the length of the block to free */
quint32 block_len;
if (lseek(fd, addr, SEEK_SET) != addr)
return -EIO;
if (read(fd, &block_len, 4) != 4)
return -EIO;
block_len = ntohl(block_len);
/* Search for the next free block */
quint32 refAddr = 0, currentAddr = first_blank, prev_len = 0;
while (currentAddr < addr)
{
refAddr = currentAddr;
if (lseek(fd, currentAddr, SEEK_SET) != currentAddr)
return -EIO;
if (read(fd, &prev_len, 4) != 4)
return -EIO;
prev_len = ntohl(prev_len);
if (read(fd, ¤tAddr, 4) != 4)
return -EIO;
if (!currentAddr)
break;
currentAddr = ntohl(currentAddr);
}
/* Check merging requirements */
if (refAddr + prev_len == addr)
{
if (addr + block_len == currentAddr)
{
/* Merge with the previous and the next free block */
quint32 currentLen, currentNext;
if (lseek(fd, currentAddr, SEEK_SET) != currentAddr)
return -EIO;
if (read(fd, ¤tLen, 4) != 4)
return -EIO;
currentLen = ntohl(currentLen);
if (read(fd, ¤tNext, 4) != 4)
return -EIO;
if (lseek(fd, refAddr, SEEK_SET) != refAddr)
return -EIO;
block_len += prev_len;
block_len += currentLen;
block_len = htonl(block_len);
if (write(fd, &block_len, 4) != 4)
return -EIO;
if (write(fd, ¤tNext, 4) != 4)
return -EIO;
} else {
/* Merge with the previous free block */
if (lseek(fd, refAddr, SEEK_SET) != refAddr)
return -EIO;
block_len += prev_len;
block_len = htonl(block_len);
if (write(fd, &block_len, 4) != 4)
return -EIO;
currentAddr = htonl(currentAddr);
if (write(fd, ¤tAddr, 4) != 4)
return -EIO;
}
} else {
/* Change the link of the previous block */
refAddr += 4;
if (lseek(fd, refAddr, SEEK_SET) != refAddr)
return -EIO;
refAddr = htonl(addr);
if (write(fd, &refAddr, 4) != 4)
return -EIO;
if (addr + block_len == currentAddr)
{
/* Merge with the next free block */
quint32 currentLen, currentNext;
if (lseek(fd, currentAddr, SEEK_SET) != currentAddr)
return -EIO;
if (read(fd, ¤tLen, 4) != 4)
return -EIO;
currentLen = ntohl(currentLen);
if (read(fd, ¤tNext, 4) != 4)
return -EIO;
if (lseek(fd, addr, SEEK_SET) != addr)
return -EIO;
block_len += currentLen;
block_len = htonl(block_len);
if (write(fd, &block_len, 4) != 4)
return -EIO;
if (write(fd, ¤tNext, 4) != 4)
return -EIO;
} else {
/* Do not merge with anything */
addr += 4;
if (lseek(fd, addr, SEEK_SET) != addr)
return -EIO;
currentAddr = htonl(currentAddr);
if (write(fd, ¤tAddr, 4) != 4)
return -EIO;
}
}
return 0;
#endif /* READONLY_FS */
}
int MyFS::getAddress(lString &pathname, quint32 &result)
{
if (pathname.str_value[0] != '/') return -ENOENT;
while ((pathname.str_value[pathname.str_len - 1] == '/') && (pathname.str_len > 0))
--pathname.str_len;
if (pathname.str_len == 0)
{
result = root_address;
return 0;
}
/* Checking whether or not the result is in the cache */
QString sValue = QString::fromLocal8Bit(pathname.str_value, pathname.str_len);
result = cache.value(sValue, 0);
if (result != 0)
return 0;
/* Get the last part of the path */
int len = pathname.str_len;
while (pathname.str_value[pathname.str_len - 1] != '/')
--pathname.str_len;
len -= pathname.str_len;
int start = pathname.str_len;
/* Run this function recursively on the beginning of the path */
int ret_value = getAddress(pathname, result);
if (ret_value != 0)
return ret_value;
/* Look for the last part of the pathname in the parent directory */
result += 4;
if (lseek(fd, result, SEEK_SET) != result)
return -EIO;
if (read(fd, &result, 4) != 4)
return -EIO;
if (read(fd, &str_buffer, 6) != 6)
return -EIO;
quint16 mshort;
if (read(fd, &mshort, 2) != 2)
return -EIO;
mshort = ntohs(mshort);
if (!(mshort & SF_MODE_DIRECTORY))
return -ENOTDIR;
if (!(mshort & S_IXUSR))
return -EACCES;
while (true)
{
quint32 addr;
if (read(fd, &addr, 4) != 4)
return -EIO;
if (!addr)
{
if (!result)
return -ENOENT;
result = ntohl(result) + 4;
if (lseek(fd, result, SEEK_SET) != result)
return -EIO;
if (read(fd, &result, 4) != 4)
return -EIO;
continue;
}
unsigned char nameLen;
if (read(fd, &nameLen, 1) != 1)
return -EIO;
if (read(fd, &str_buffer, nameLen) != nameLen)
return -EIO;
if ((nameLen == len) && (memcmp(pathname.str_value + start, str_buffer, len) == 0))
{
result = ntohl(addr);
/* Store the result in the cache (we won't care about limiting the cache size) */
cache[sValue] = result;
return 0;
}
}
}
| 32.146621 | 137 | 0.510173 | baz1 |
f9ca369eb57fcf984b3a7fd04161ad537301539a | 8,940 | cxx | C++ | Kinematics/StarKinematics.cxx | klendathu2k/StarGenerator | 7dd407c41d4eea059ca96ded80d30bda0bc014a4 | [
"MIT"
] | null | null | null | Kinematics/StarKinematics.cxx | klendathu2k/StarGenerator | 7dd407c41d4eea059ca96ded80d30bda0bc014a4 | [
"MIT"
] | null | null | null | Kinematics/StarKinematics.cxx | klendathu2k/StarGenerator | 7dd407c41d4eea059ca96ded80d30bda0bc014a4 | [
"MIT"
] | null | null | null | #include "StarKinematics.h"
#include "StarGenerator/EVENT/StarGenEvent.h"
#include "StarGenerator/EVENT/StarGenParticle.h"
#include "StarGenerator/UTIL/StarParticleData.h"
#include "StarGenerator/UTIL/StarRandom.h"
#include <boost/algorithm/string.hpp>
#include <vector>
#include <string>
#include <algorithm>
#include <random>
#define random myrandom
// ----------------------------------------------------------------------------
StarParticleData &data = StarParticleData::instance();
StarRandom &random = StarRandom::Instance();
static std::random_device _stl_rd;
static std::mt19937 _mt19937( _stl_rd() );
StarGenEvent *gEvent = 0;
StarGenEvent *gUser = 0;
// ----------------------------------------------------------------------------
StarKinematics::StarKinematics( const Char_t *name ) : StarGenerator(name)
{
mEvent = new StarGenEvent("kine"); gEvent = mEvent;
mUser = new StarGenEvent("user"); gUser = mUser;
}
// ----------------------------------------------------------------------------
Int_t StarKinematics::PreGenerate()
{
return kStOK;
}
// ----------------------------------------------------------------------------
Int_t StarKinematics::Generate()
{
// Copy user event into mEvent
for ( Int_t i=0;i<mUser->GetNumberOfParticles(); i++ )
{
mEvent -> AddParticle( (*mUser)[i] );
}
// And clear the user event
mUser->Clear();
return kStOK;
}
// ----------------------------------------------------------------------------
Int_t StarKinematics::PostGenerate()
{
return kStOK;
}
// ----------------------------------------------------------------------------
StarGenParticle *StarKinematics::AddParticle()
{
StarGenParticle *p = mUser->AddParticle();
p->SetStatus( StarGenParticle::kFinal );
return p;
}
// ----------------------------------------------------------------------------
StarGenParticle *StarKinematics::AddParticle( const Char_t *type )
{
TParticlePDG *pdg = data(type); assert(pdg);
Int_t id = pdg->PdgCode();
StarGenParticle *p = AddParticle();
p->SetStatus( StarGenParticle::kFinal );
p->SetMass( pdg->Mass() );
p->SetId( id );
return p;
}
// ----------------------------------------------------------------------------
void StarKinematics::Kine(Int_t ntrack, const Char_t *_type, Double_t ptlow, Double_t pthigh,
Double_t ylow, Double_t yhigh,
Double_t philow, Double_t phihigh )
{
std::string type = _type;
std::vector<std::string> types;
boost::split( types, type, [](char c){ return (c==' ' || c== ',');} );
for ( Int_t i=0;i<ntrack;i++ )
{
std::shuffle( types.begin(), types.end(), _mt19937 );
type = types[0];
StarGenParticle *p = AddParticle(type.c_str());
// Sample pt, eta, phi
if ( 0 == IAttr("energy") ) { // uniform in pT
double pt = random(ptlow, pthigh);
double y = random(ylow, yhigh );
double phi= random(philow, phihigh );
double m = p->GetMass();
double mt = pt;
if ( IAttr("rapidity" ) ) {
// switch from pseudorapidity to plain vanilla rapidity
mt = TMath::Sqrt( pt*pt + m*m );
}
double px = pt * TMath::Cos( phi );
double py = pt * TMath::Sin( phi );
double pz = mt * TMath::SinH( y );
double E = mt * TMath::CosH( y );
p->SetPx( px );
p->SetPy( py );
p->SetPz( pz );
p->SetEnergy( E );
p->SetVx( 0. ); // put vertex at 0,0,0,0
p->SetVy( 0. );
p->SetVz( 0. );
p->SetTof( 0. );
}
if ( IAttr("energy") ) { // uniform in energy.
assert( 0==IAttr("rapidity") ); // only flat in eta, not rapidity
double E = random(ptlow, pthigh);
double y = random(ylow, yhigh ); // y is eta here, not rapidity
double phi= random(philow, phihigh );
double m = p->GetMass();
double pmom = TMath::Sqrt(E*E - m*m);
double pt = 2.0 * pmom * TMath::Exp( -y ) / ( 1 + TMath::Exp( -2.0*y ) );
double mt = pt;
if ( IAttr("rapidity" ) ) {
// switch from pseudorapidity to plain vanilla rapidity
mt = TMath::Sqrt( pt*pt + m*m );
}
double px = pt * TMath::Cos( phi );
double py = pt * TMath::Sin( phi );
double pz = mt * TMath::SinH( y );
//double E = mt * TMath::CosH( y );
p->SetPx( px );
p->SetPy( py );
p->SetPz( pz );
p->SetEnergy( E );
p->SetVx( 1e-11); // put vertex at 0,0,0,0
p->SetVy( 1e-11);
p->SetVz( 1e-11);
p->SetTof( 0. );
}
}
}
// ----------------------------------------------------------------------------
void StarKinematics::Dist( Int_t ntrack, const Char_t *_type, TF1 *ptFunc, TF1 *etaFunc, TF1 *phiFunc )
{
std::string type = _type;
std::vector<std::string> types;
boost::split( types, type, [](char c){ return (c==' ' || c== ',');} );
for ( Int_t i=0; i<ntrack; i++ )
{
std::shuffle( types.begin(), types.end(), _mt19937 );
type = types[0];
StarGenParticle *p = AddParticle(type.c_str());
Double_t pt = ptFunc -> GetRandom();
Double_t y = etaFunc -> GetRandom();
Double_t phi = (phiFunc) ? phiFunc->GetRandom() : random( 0., TMath::TwoPi() );
Double_t m = p->GetMass();
double mt = pt;
if ( IAttr("rapidity" ) ) {
// switch from pseudorapidity to plain vanilla rapidity
mt = TMath::Sqrt( pt*pt + m*m );
}
double px = pt * TMath::Cos( phi );
double py = pt * TMath::Sin( phi );
double pz = mt * TMath::SinH( y );
double E = mt * TMath::CosH( y );
p->SetPx( px );
p->SetPy( py );
p->SetPz( pz );
p->SetEnergy( E );
p->SetVx( 0. ); // put vertex at 0,0,0,0
p->SetVy( 0. );
p->SetVz( 0. );
p->SetTof( 0. );
}
}
// ----------------------------------------------------------------------------
void StarKinematics::Dist( Int_t ntrack, const Char_t *_type, TH1 *ptFunc, TH1 *etaFunc, TH1 *phiFunc )
{
std::string type = _type;
std::vector<std::string> types;
boost::split( types, type, [](char c){ return (c==' ' || c== ',');} );
for ( Int_t i=0; i<ntrack; i++ )
{
std::shuffle( types.begin(), types.end(), _mt19937 );
type = types[0];
StarGenParticle *p = AddParticle(type.c_str());
Double_t pt = ptFunc -> GetRandom();
Double_t y = etaFunc -> GetRandom();
Double_t phi = (phiFunc) ? phiFunc->GetRandom() : random( 0., TMath::TwoPi() );
Double_t m = p->GetMass();
double mt = pt;
if ( IAttr("rapidity" ) ) {
// switch from pseudorapidity to plain vanilla rapidity
mt = TMath::Sqrt( pt*pt + m*m );
}
double px = pt * TMath::Cos( phi );
double py = pt * TMath::Sin( phi );
double pz = mt * TMath::SinH( y );
double E = mt * TMath::CosH( y );
p->SetPx( px );
p->SetPy( py );
p->SetPz( pz );
p->SetEnergy( E );
p->SetVx( 0. ); // put vertex at 0,0,0,0
p->SetVy( 0. );
p->SetVz( 0. );
p->SetTof( 0. );
}
}
// ----------------------------------------------------------------------------
const double deg2rad = TMath::DegToRad();
void StarKinematics::Cosmic( int ntrack, const char* _type, double plow, double phigh, double radius, double zmin, double zmax, double dphi )
{
std::string type = _type;
std::vector<std::string> types;
boost::split( types, type, [](char c){ return (c==' ' || c== ',');} );
for ( Int_t i=0; i<ntrack; i++ )
{
std::shuffle( types.begin(), types.end(), _mt19937 );
type = types[0];
StarGenParticle *p = AddParticle(type.c_str());
// Generate a random vertex
double zvertex = random( zmin, zmax );
double phi = random( 0.0, TMath::TwoPi() );
double xvertex = radius * TMath::Cos(phi);
double yvertex = radius * TMath::Sin(phi);
xvertex *= 10; // cm --> mm per HEPEVT standard
yvertex *= 10; // cm --> mm
zvertex *= 10; // cm --> mm
// Initialize vertex X,Y ... to get unit vector pointing to beam line
TVector3 vertex(xvertex,yvertex,0);
// Unit vector pointing away from beamline
TVector3 direct = vertex.Unit();
// Sample momentum distribution
double pmag = random(plow, phigh);
// Momentum vector pointing in towards the beamline
_momentum = -pmag * direct;
// Now, randomize phi and theta by +/- dphi degrees about the momentum axis
phi = _momentum.Phi() + deg2rad * random( -dphi, +dphi );
double theta = _momentum.Theta() + deg2rad * random( -dphi, +dphi );
_momentum.SetPhi(phi);
_momentum.SetTheta(theta);
Double_t m = p->GetMass();
Double_t E2 = _momentum.Mag2() + m*m;
Double_t E = sqrt(E2);
p->SetPx( _momentum.Px() );
p->SetPy( _momentum.Py() );
p->SetPz( _momentum.Pz() );
p->SetEnergy( E );
p->SetVx( xvertex );
p->SetVy( yvertex );
p->SetVz( zvertex );
p->SetTof( 0. );
}
}
// ----------------------------------------------------------------------------
| 28.745981 | 141 | 0.518345 | klendathu2k |
f9cb223eea17f8f91336b2955df8ccb3d904d3d2 | 1,899 | cpp | C++ | src/gpgmm/common/IndexedMemoryPool.cpp | intel/GPGMM | 75b953cb0fc6ffd265eb0a77fab36bdb6a401e4f | [
"Apache-2.0"
] | 1 | 2022-02-13T15:48:36.000Z | 2022-02-13T15:48:36.000Z | src/gpgmm/common/IndexedMemoryPool.cpp | intel/GPGMM | 75b953cb0fc6ffd265eb0a77fab36bdb6a401e4f | [
"Apache-2.0"
] | 16 | 2021-10-05T21:32:14.000Z | 2022-03-30T11:39:21.000Z | src/gpgmm/common/IndexedMemoryPool.cpp | intel/GPGMM | 75b953cb0fc6ffd265eb0a77fab36bdb6a401e4f | [
"Apache-2.0"
] | null | null | null | // Copyright 2021 The GPGMM Authors
//
// 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 "gpgmm/common/IndexedMemoryPool.h"
#include "gpgmm/common/Debug.h"
#include "gpgmm/common/MemoryAllocator.h"
namespace gpgmm {
IndexedMemoryPool::IndexedMemoryPool(uint64_t memorySize) : MemoryPool(memorySize) {
}
std::unique_ptr<MemoryAllocation> IndexedMemoryPool::AcquireFromPool(uint64_t memoryIndex) {
if (memoryIndex >= mPool.size()) {
mPool.resize(memoryIndex + 1);
}
return std::move(mPool[memoryIndex]);
}
void IndexedMemoryPool::ReturnToPool(std::unique_ptr<MemoryAllocation> allocation,
uint64_t memoryIndex) {
ASSERT(allocation != nullptr);
ASSERT(memoryIndex < mPool.size());
mPool[memoryIndex] = std::move(allocation);
}
void IndexedMemoryPool::ReleasePool() {
for (auto& allocation : mPool) {
if (allocation != nullptr) {
allocation->GetAllocator()->DeallocateMemory(std::move(allocation));
}
}
mPool.clear();
}
uint64_t IndexedMemoryPool::GetPoolSize() const {
uint64_t count = 0;
for (auto& allocation : mPool) {
if (allocation != nullptr) {
count++;
}
}
return count;
}
} // namespace gpgmm
| 32.186441 | 96 | 0.63981 | intel |
f9cc8435642f0ff0ef400e2d894893d08f80124c | 2,102 | cc | C++ | chrome/browser/extensions/api/safe_browsing_private/safe_browsing_private_event_router_factory.cc | zipated/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 2,151 | 2020-04-18T07:31:17.000Z | 2022-03-31T08:39:18.000Z | chrome/browser/extensions/api/safe_browsing_private/safe_browsing_private_event_router_factory.cc | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 395 | 2020-04-18T08:22:18.000Z | 2021-12-08T13:04:49.000Z | chrome/browser/extensions/api/safe_browsing_private/safe_browsing_private_event_router_factory.cc | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 338 | 2020-04-18T08:03:10.000Z | 2022-03-29T12:33:22.000Z | // Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/extensions/api/safe_browsing_private/safe_browsing_private_event_router_factory.h"
#include "chrome/browser/extensions/api/safe_browsing_private/safe_browsing_private_event_router.h"
#include "components/keyed_service/content/browser_context_dependency_manager.h"
#include "content/public/browser/browser_context.h"
#include "extensions/browser/extension_system_provider.h"
#include "extensions/browser/extensions_browser_client.h"
namespace extensions {
// static
SafeBrowsingPrivateEventRouter*
SafeBrowsingPrivateEventRouterFactory::GetForProfile(
content::BrowserContext* context) {
return static_cast<SafeBrowsingPrivateEventRouter*>(
GetInstance()->GetServiceForBrowserContext(context, true));
}
// static
SafeBrowsingPrivateEventRouterFactory*
SafeBrowsingPrivateEventRouterFactory::GetInstance() {
return base::Singleton<SafeBrowsingPrivateEventRouterFactory>::get();
}
SafeBrowsingPrivateEventRouterFactory::SafeBrowsingPrivateEventRouterFactory()
: BrowserContextKeyedServiceFactory(
"SafeBrowsingPrivateEventRouter",
BrowserContextDependencyManager::GetInstance()) {
DependsOn(ExtensionsBrowserClient::Get()->GetExtensionSystemFactory());
}
SafeBrowsingPrivateEventRouterFactory::
~SafeBrowsingPrivateEventRouterFactory() {}
KeyedService* SafeBrowsingPrivateEventRouterFactory::BuildServiceInstanceFor(
content::BrowserContext* context) const {
return new SafeBrowsingPrivateEventRouter(context);
}
content::BrowserContext*
SafeBrowsingPrivateEventRouterFactory::GetBrowserContextToUse(
content::BrowserContext* context) const {
return ExtensionsBrowserClient::Get()->GetOriginalContext(context);
}
bool SafeBrowsingPrivateEventRouterFactory::ServiceIsCreatedWithBrowserContext()
const {
return true;
}
bool SafeBrowsingPrivateEventRouterFactory::ServiceIsNULLWhileTesting() const {
return true;
}
} // namespace extensions
| 35.033333 | 107 | 0.82255 | zipated |
f9ccb4d6ac0df11719166b96edbe8a9ee1467a72 | 1,462 | cpp | C++ | wumpus_expressions/autogenerated/src/Plans/SingleAgent/Behaviours/InitASPModel.cpp | dasys-lab/cnc-wumpus | da5c3b56f9dd6ef852c7fe5195ec6455d50d6142 | [
"MIT"
] | null | null | null | wumpus_expressions/autogenerated/src/Plans/SingleAgent/Behaviours/InitASPModel.cpp | dasys-lab/cnc-wumpus | da5c3b56f9dd6ef852c7fe5195ec6455d50d6142 | [
"MIT"
] | null | null | null | wumpus_expressions/autogenerated/src/Plans/SingleAgent/Behaviours/InitASPModel.cpp | dasys-lab/cnc-wumpus | da5c3b56f9dd6ef852c7fe5195ec6455d50d6142 | [
"MIT"
] | null | null | null | using namespace std;
#include "Plans/SingleAgent/Behaviours/InitASPModel.h"
/*PROTECTED REGION ID(inccpp1536061745720) ENABLED START*/ //Add additional includes here
#include <engine/AlicaEngine.h>
/*PROTECTED REGION END*/
namespace alica
{
/*PROTECTED REGION ID(staticVars1536061745720) ENABLED START*/ //initialise static variables here
/*PROTECTED REGION END*/
InitASPModel::InitASPModel() :
DomainBehaviour("InitASPModel")
{
/*PROTECTED REGION ID(con1536061745720) ENABLED START*/ //Add additional options here
this->query = make_shared<alica::Query>();
/*PROTECTED REGION END*/
}
InitASPModel::~InitASPModel()
{
/*PROTECTED REGION ID(dcon1536061745720) ENABLED START*/ //Add additional options here
/*PROTECTED REGION END*/
}
void InitASPModel::run(void* msg)
{
/*PROTECTED REGION ID(run1536061745720) ENABLED START*/ //Add additional options here
/*PROTECTED REGION END*/
}
void InitASPModel::initialiseParameters()
{
/*PROTECTED REGION ID(initialiseParameters1536061745720) ENABLED START*/ //Add additional options here
query->clearStaticVariables();
query->addStaticVariable(getVariableByName("ModelVar"));
result.clear();
/*PROTECTED REGION END*/
}
/*PROTECTED REGION ID(methods1536061745720) ENABLED START*/ //Add additional methods here
/*PROTECTED REGION END*/
} /* namespace alica */
| 37.487179 | 110 | 0.692886 | dasys-lab |
f9d1ed93dae68ffa66228391dfc9dbcc5cc41bf0 | 8,827 | cpp | C++ | samples/gl-320-buffer-uniform.cpp | galek/ogl-samples | 38cada7a9458864265e25415ae61586d500ff5fc | [
"MIT"
] | 571 | 2015-01-08T16:29:38.000Z | 2022-03-16T06:45:42.000Z | samples/gl-320-buffer-uniform.cpp | galek/ogl-samples | 38cada7a9458864265e25415ae61586d500ff5fc | [
"MIT"
] | 45 | 2015-01-15T12:47:28.000Z | 2022-03-04T09:22:32.000Z | samples/gl-320-buffer-uniform.cpp | galek/ogl-samples | 38cada7a9458864265e25415ae61586d500ff5fc | [
"MIT"
] | 136 | 2015-01-31T15:24:57.000Z | 2022-02-17T19:26:24.000Z | #include "test.hpp"
namespace
{
char const* VERT_SHADER_SOURCE("gl-320/buffer-uniform.vert");
char const* FRAG_SHADER_SOURCE("gl-320/buffer-uniform.frag");
struct vertex_v3fn3fc4f
{
vertex_v3fn3fc4f
(
glm::vec3 const & Position,
glm::vec3 const & Normal,
glm::vec4 const & Color
) :
Position(Position),
Normal(Normal),
Color(Color)
{}
glm::vec3 Position;
glm::vec3 Normal;
glm::vec4 Color;
};
GLsizei const VertexCount(4);
GLsizeiptr const VertexSize = VertexCount * sizeof(vertex_v3fn3fc4f);
vertex_v3fn3fc4f const VertexData[VertexCount] =
{
vertex_v3fn3fc4f(glm::vec3(-1.0f,-1.0f, 0.0), glm::vec3(0.0f, 0.0f, 1.0f), glm::vec4(1.0f, 0.0f, 0.0f, 1.0f)),
vertex_v3fn3fc4f(glm::vec3( 1.0f,-1.0f, 0.0), glm::vec3(0.0f, 0.0f, 1.0f), glm::vec4(0.0f, 1.0f, 0.0f, 1.0f)),
vertex_v3fn3fc4f(glm::vec3( 1.0f, 1.0f, 0.0), glm::vec3(0.0f, 0.0f, 1.0f), glm::vec4(0.0f, 0.0f, 1.0f, 1.0f)),
vertex_v3fn3fc4f(glm::vec3(-1.0f, 1.0f, 0.0), glm::vec3(0.0f, 0.0f, 1.0f), glm::vec4(1.0f, 1.0f, 1.0f, 1.0f))
};
GLsizei const ElementCount(6);
GLsizeiptr const ElementSize = ElementCount * sizeof(GLushort);
GLushort const ElementData[ElementCount] =
{
0, 1, 2,
2, 3, 0
};
/*
GLsizei const VertexCount(4);
GLsizeiptr const VertexSize = VertexCount * sizeof(vertex_v3fn3fc4f);
vertex_v3fn3fc4f const VertexData[VertexCount] =
{
vertex_v3fn3fc4f(glm::vec3(-1.000f, -0.732f, -0.732f), glm::normalize(glm::vec3(-1.000f, -0.732f, -0.732f)), glm::vec4(1.0f, 0.0f, 0.0f, 1.0f)),
vertex_v3fn3fc4f(glm::vec3( 1.000f, -0.732f, -0.732f), glm::normalize(glm::vec3( 1.000f, -0.732f, -0.732f)), glm::vec4(0.0f, 1.0f, 0.0f, 1.0f)),
vertex_v3fn3fc4f(glm::vec3( 0.000f, 1.000f, -0.732f), glm::normalize(glm::vec3( 0.000f, 1.000f, -0.732f)), glm::vec4(0.0f, 0.0f, 1.0f, 1.0f)),
vertex_v3fn3fc4f(glm::vec3( 0.000f, 0.000f, 1.000f), glm::normalize(glm::vec3( 0.000f, 0.000f, 1.000f)), glm::vec4(1.0f, 1.0f, 1.0f, 1.0f))
};
GLsizei const ElementCount(12);
GLsizeiptr const ElementSize = ElementCount * sizeof(GLushort);
GLushort const ElementData[ElementCount] =
{
0, 2, 1,
0, 1, 3,
1, 2, 3,
2, 0, 3
};
*/
namespace buffer
{
enum type
{
VERTEX,
ELEMENT,
PER_SCENE,
PER_PASS,
PER_DRAW,
MAX
};
}//namespace buffer
namespace uniform
{
enum type
{
PER_SCENE = 0,
PER_PASS = 1,
PER_DRAW = 2,
LIGHT = 3
};
};
struct material
{
glm::vec3 Ambient;
float Padding1;
glm::vec3 Diffuse;
float Padding2;
glm::vec3 Specular;
float Shininess;
};
struct light
{
glm::vec3 Position;
};
struct transform
{
glm::mat4 P;
glm::mat4 MV;
glm::mat3 Normal;
};
}//namespace
class sample : public framework
{
public:
sample(int argc, char* argv[]) :
framework(argc, argv, "gl-320-buffer-uniform", framework::CORE, 3, 2),
VertexArrayName(0),
ProgramName(0),
UniformPerDraw(0),
UniformPerPass(0),
UniformPerScene(0)
{}
private:
std::array<GLuint, buffer::MAX> BufferName;
GLuint ProgramName;
GLuint VertexArrayName;
GLint UniformPerDraw;
GLint UniformPerPass;
GLint UniformPerScene;
bool initProgram()
{
bool Validated = true;
compiler Compiler;
if(Validated)
{
compiler Compiler;
GLuint VertShaderName = Compiler.create(GL_VERTEX_SHADER, getDataDirectory() + VERT_SHADER_SOURCE, "--version 150 --profile core");
GLuint FragShaderName = Compiler.create(GL_FRAGMENT_SHADER, getDataDirectory() + FRAG_SHADER_SOURCE, "--version 150 --profile core");
ProgramName = glCreateProgram();
glAttachShader(ProgramName, VertShaderName);
glAttachShader(ProgramName, FragShaderName);
glBindAttribLocation(ProgramName, semantic::attr::POSITION, "Position");
glBindAttribLocation(ProgramName, semantic::attr::NORMAL, "Normal");
glBindAttribLocation(ProgramName, semantic::attr::COLOR, "Color");
glBindFragDataLocation(ProgramName, semantic::frag::COLOR, "Color");
glLinkProgram(ProgramName);
Validated = Validated && Compiler.check();
Validated = Validated && Compiler.check_program(ProgramName);
}
if(Validated)
{
this->UniformPerDraw = glGetUniformBlockIndex(ProgramName, "per_draw");
this->UniformPerPass = glGetUniformBlockIndex(ProgramName, "per_pass");
this->UniformPerScene = glGetUniformBlockIndex(ProgramName, "per_scene");
glUniformBlockBinding(ProgramName, this->UniformPerDraw, uniform::PER_DRAW);
glUniformBlockBinding(ProgramName, this->UniformPerPass, uniform::PER_PASS);
glUniformBlockBinding(ProgramName, this->UniformPerScene, uniform::PER_SCENE);
}
return Validated;
}
bool initVertexArray()
{
glGenVertexArrays(1, &VertexArrayName);
glBindVertexArray(VertexArrayName);
glBindBuffer(GL_ARRAY_BUFFER, BufferName[buffer::VERTEX]);
glVertexAttribPointer(semantic::attr::POSITION, 3, GL_FLOAT, GL_FALSE, sizeof(vertex_v3fn3fc4f), BUFFER_OFFSET(0));
glVertexAttribPointer(semantic::attr::NORMAL, 3, GL_FLOAT, GL_FALSE, sizeof(vertex_v3fn3fc4f), BUFFER_OFFSET(sizeof(glm::vec3)));
glVertexAttribPointer(semantic::attr::COLOR, 4, GL_FLOAT, GL_FALSE, sizeof(vertex_v3fn3fc4f), BUFFER_OFFSET(sizeof(glm::vec3) + sizeof(glm::vec3)));
glBindBuffer(GL_ARRAY_BUFFER, 0);
glEnableVertexAttribArray(semantic::attr::POSITION);
glEnableVertexAttribArray(semantic::attr::NORMAL);
glEnableVertexAttribArray(semantic::attr::COLOR);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, BufferName[buffer::ELEMENT]);
glBindVertexArray(0);
return true;
}
bool initBuffer()
{
glGenBuffers(buffer::MAX, &BufferName[0]);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, BufferName[buffer::ELEMENT]);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, ElementSize, ElementData, GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
glBindBuffer(GL_ARRAY_BUFFER, BufferName[buffer::VERTEX]);
glBufferData(GL_ARRAY_BUFFER, VertexSize, VertexData, GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);
{
glBindBuffer(GL_UNIFORM_BUFFER, BufferName[buffer::PER_DRAW]);
glBufferData(GL_UNIFORM_BUFFER, sizeof(transform), nullptr, GL_DYNAMIC_DRAW);
glBindBuffer(GL_UNIFORM_BUFFER, 0);
}
{
light Light = {glm::vec3(0.0f, 0.0f, 100.f)};
glBindBuffer(GL_UNIFORM_BUFFER, BufferName[buffer::PER_PASS]);
glBufferData(GL_UNIFORM_BUFFER, sizeof(Light), &Light, GL_STATIC_DRAW);
glBindBuffer(GL_UNIFORM_BUFFER, 0);
}
{
material Material = {glm::vec3(0.7f, 0.0f, 0.0f), 0.0f, glm::vec3(0.0f, 0.5f, 0.0f), 0.0f, glm::vec3(0.0f, 0.0f, 0.5f), 128.0f};
glBindBuffer(GL_UNIFORM_BUFFER, BufferName[buffer::PER_SCENE]);
glBufferData(GL_UNIFORM_BUFFER, sizeof(Material), &Material, GL_STATIC_DRAW);
glBindBuffer(GL_UNIFORM_BUFFER, 0);
}
return true;
}
bool begin()
{
bool Validated = true;
if(Validated)
Validated = initProgram();
if(Validated)
Validated = initBuffer();
if(Validated)
Validated = initVertexArray();
glEnable(GL_DEPTH_TEST);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glDrawBuffer(GL_BACK);
if(glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
return false;
return Validated;
}
bool end()
{
glDeleteVertexArrays(1, &VertexArrayName);
glDeleteBuffers(buffer::MAX, &BufferName[0]);
glDeleteProgram(ProgramName);
return true;
}
bool render()
{
glm::vec2 WindowSize(this->getWindowSize());
{
glBindBuffer(GL_UNIFORM_BUFFER, BufferName[buffer::PER_DRAW]);
transform* Transform = static_cast<transform*>(glMapBufferRange(GL_UNIFORM_BUFFER,
0, sizeof(transform), GL_MAP_WRITE_BIT | GL_MAP_INVALIDATE_BUFFER_BIT));
glm::mat4 const Projection = glm::perspective(glm::pi<float>() * 0.25f, 4.0f / 3.0f, 0.1f, 100.0f);
glm::mat4 const View = this->view();
glm::mat4 const Model = glm::rotate(glm::mat4(1.0f), -glm::pi<float>() * 0.5f, glm::vec3(0.0f, 0.0f, 1.0f));
Transform->MV = View * Model;
Transform->P = Projection;
Transform->Normal = glm::mat3(glm::transpose(glm::inverse(Transform->MV)));
glUnmapBuffer(GL_UNIFORM_BUFFER);
glBindBuffer(GL_UNIFORM_BUFFER, 0);
}
glViewport(0, 0, static_cast<GLsizei>(WindowSize.x), static_cast<GLsizei>(WindowSize.y));
glClearBufferfv(GL_COLOR, 0, &glm::vec4(0.2f, 0.2f, 0.2f, 1.0f)[0]);
glClearBufferfv(GL_DEPTH, 0, &glm::vec1(1.0f)[0]);
glUseProgram(ProgramName);
glBindBufferBase(GL_UNIFORM_BUFFER, uniform::PER_SCENE, BufferName[buffer::PER_SCENE]);
glBindBufferBase(GL_UNIFORM_BUFFER, uniform::PER_PASS, BufferName[buffer::PER_PASS]);
glBindBufferBase(GL_UNIFORM_BUFFER, uniform::PER_DRAW, BufferName[buffer::PER_DRAW]);
glBindVertexArray(VertexArrayName);
glDrawElementsInstancedBaseVertex(GL_TRIANGLES, ElementCount, GL_UNSIGNED_SHORT, nullptr, 1, 0);
return true;
}
};
int main(int argc, char* argv[])
{
int Error = 0;
sample Sample(argc, argv);
Error += Sample();
return Error;
}
| 28.940984 | 151 | 0.71066 | galek |
f9d74d219afb8904a906f72c4f7923276f721e35 | 527 | cpp | C++ | Day 04/string2.cpp | tushar-nath/100-days-of-code | 860c088968521d953f5ca9222f70037e95cb4ad4 | [
"MIT"
] | null | null | null | Day 04/string2.cpp | tushar-nath/100-days-of-code | 860c088968521d953f5ca9222f70037e95cb4ad4 | [
"MIT"
] | null | null | null | Day 04/string2.cpp | tushar-nath/100-days-of-code | 860c088968521d953f5ca9222f70037e95cb4ad4 | [
"MIT"
] | null | null | null | #include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main()
{
string str = "TUSHAR";
// convert to upper strings
for (int i=0; i<str.length(); i++)
{
if(str[i>='a' && str[i]<='z'])
{
str[i]-=32;
cout<<str[i];
}
}
// convert to lower strings
for (int i=0; i<str.length(); i++)
{
if(str[i>='A' && str[i]<='Z'])
{
str[i]+=32;
cout<<str[i];
}
}
return 0;
} | 15.5 | 38 | 0.421252 | tushar-nath |
f9d94848e645004809d14d815b501d0745c7dc62 | 8,506 | cpp | C++ | deform_control/external_libs/OpenSceneGraph-2.8.5/src/osg/CullStack.cpp | UM-ARM-Lab/mab_ms | f199f05b88060182cfbb47706bd1ff3479032c43 | [
"BSD-2-Clause"
] | 3 | 2018-08-20T12:12:43.000Z | 2021-06-06T09:43:27.000Z | deform_control/external_libs/OpenSceneGraph-2.8.5/src/osg/CullStack.cpp | UM-ARM-Lab/mab_ms | f199f05b88060182cfbb47706bd1ff3479032c43 | [
"BSD-2-Clause"
] | null | null | null | deform_control/external_libs/OpenSceneGraph-2.8.5/src/osg/CullStack.cpp | UM-ARM-Lab/mab_ms | f199f05b88060182cfbb47706bd1ff3479032c43 | [
"BSD-2-Clause"
] | 1 | 2022-03-31T03:12:23.000Z | 2022-03-31T03:12:23.000Z | /* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield
*
* This library is open source and may be redistributed and/or modified under
* the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
* (at your option) any later version. The full license is in LICENSE file
* included with this distribution, and on the openscenegraph.org website.
*
* This library 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
* OpenSceneGraph Public License for more details.
*/
#include <osg/CullStack>
#include <osg/Timer>
#include <osg/Notify>
#include <osg/io_utils>
using namespace osg;
CullStack::CullStack()
{
_frustumVolume=-1.0f;
_bbCornerNear = 0;
_bbCornerFar = 7;
_currentReuseMatrixIndex=0;
_identity = new RefMatrix();
_index_modelviewCullingStack = 0;
_back_modelviewCullingStack = 0;
_referenceViewPoints.push_back(osg::Vec3(0.0f,0.0f,0.0f));
}
CullStack::CullStack(const CullStack& cs):
CullSettings(cs)
{
_frustumVolume=-1.0f;
_bbCornerNear = 0;
_bbCornerFar = 7;
_currentReuseMatrixIndex=0;
_identity = new RefMatrix();
_index_modelviewCullingStack = 0;
_back_modelviewCullingStack = 0;
_referenceViewPoints.push_back(osg::Vec3(0.0f,0.0f,0.0f));
}
CullStack::~CullStack()
{
reset();
}
void CullStack::reset()
{
//
// first unref all referenced objects and then empty the containers.
//
_projectionStack.clear();
_modelviewStack.clear();
_viewportStack.clear();
_referenceViewPoints.clear();
_referenceViewPoints.push_back(osg::Vec3(0.0f,0.0f,0.0f));
_eyePointStack.clear();
_viewPointStack.clear();
_clipspaceCullingStack.clear();
_projectionCullingStack.clear();
//_modelviewCullingStack.clear();
_index_modelviewCullingStack=0;
_back_modelviewCullingStack = 0;
osg::Vec3 lookVector(0.0,0.0,-1.0);
_bbCornerFar = (lookVector.x()>=0?1:0) |
(lookVector.y()>=0?2:0) |
(lookVector.z()>=0?4:0);
_bbCornerNear = (~_bbCornerFar)&7;
_currentReuseMatrixIndex=0;
}
void CullStack::pushCullingSet()
{
_MVPW_Stack.push_back(0L);
if (_index_modelviewCullingStack==0)
{
if (_modelviewCullingStack.empty())
_modelviewCullingStack.push_back(CullingSet());
_modelviewCullingStack[_index_modelviewCullingStack++].set(_projectionCullingStack.back());
}
else
{
const osg::Viewport& W = *_viewportStack.back();
const osg::Matrix& P = *_projectionStack.back();
const osg::Matrix& M = *_modelviewStack.back();
osg::Vec4 pixelSizeVector = CullingSet::computePixelSizeVector(W,P,M);
if (_index_modelviewCullingStack>=_modelviewCullingStack.size())
{
_modelviewCullingStack.push_back(CullingSet());
}
_modelviewCullingStack[_index_modelviewCullingStack++].set(_projectionCullingStack.back(),*_modelviewStack.back(),pixelSizeVector);
}
_back_modelviewCullingStack = &_modelviewCullingStack[_index_modelviewCullingStack-1];
// const osg::Polytope& polytope = _modelviewCullingStack.back()->getFrustum();
// const osg::Polytope::PlaneList& pl = polytope.getPlaneList();
// std::cout <<"new cull stack"<<std::endl;
// for(osg::Polytope::PlaneList::const_iterator pl_itr=pl.begin();
// pl_itr!=pl.end();
// ++pl_itr)
// {
// std::cout << " plane "<<*pl_itr<<std::endl;
// }
}
void CullStack::popCullingSet()
{
_MVPW_Stack.pop_back();
--_index_modelviewCullingStack;
if (_index_modelviewCullingStack>0) _back_modelviewCullingStack = &_modelviewCullingStack[_index_modelviewCullingStack-1];
}
void CullStack::pushViewport(osg::Viewport* viewport)
{
_viewportStack.push_back(viewport);
_MVPW_Stack.push_back(0L);
}
void CullStack::popViewport()
{
_viewportStack.pop_back();
_MVPW_Stack.pop_back();
}
void CullStack::pushProjectionMatrix(RefMatrix* matrix)
{
_projectionStack.push_back(matrix);
_projectionCullingStack.push_back(osg::CullingSet());
osg::CullingSet& cullingSet = _projectionCullingStack.back();
// set up view frustum.
cullingSet.getFrustum().setToUnitFrustum(((_cullingMode&NEAR_PLANE_CULLING)!=0),((_cullingMode&FAR_PLANE_CULLING)!=0));
cullingSet.getFrustum().transformProvidingInverse(*matrix);
// set the culling mask ( There should be a more elegant way!) Nikolaus H.
cullingSet.setCullingMask(_cullingMode);
// set the small feature culling.
cullingSet.setSmallFeatureCullingPixelSize(_smallFeatureCullingPixelSize);
// set up the relevant occluders which a related to this projection.
for(ShadowVolumeOccluderList::iterator itr=_occluderList.begin();
itr!=_occluderList.end();
++itr)
{
//std::cout << " ** testing occluder"<<std::endl;
if (itr->matchProjectionMatrix(*matrix))
{
//std::cout << " ** activating occluder"<<std::endl;
cullingSet.addOccluder(*itr);
}
}
// need to recompute frustum volume.
_frustumVolume = -1.0f;
pushCullingSet();
}
void CullStack::popProjectionMatrix()
{
_projectionStack.pop_back();
_projectionCullingStack.pop_back();
// need to recompute frustum volume.
_frustumVolume = -1.0f;
popCullingSet();
}
void CullStack::pushModelViewMatrix(RefMatrix* matrix, Transform::ReferenceFrame referenceFrame)
{
osg::RefMatrix* originalModelView = _modelviewStack.empty() ? 0 : _modelviewStack.back().get();
_modelviewStack.push_back(matrix);
pushCullingSet();
osg::Matrix inv;
inv.invert(*matrix);
switch(referenceFrame)
{
case(Transform::RELATIVE_RF):
_eyePointStack.push_back(inv.getTrans());
_referenceViewPoints.push_back(getReferenceViewPoint());
_viewPointStack.push_back(getReferenceViewPoint() * inv);
break;
case(Transform::ABSOLUTE_RF):
_eyePointStack.push_back(inv.getTrans());
_referenceViewPoints.push_back(osg::Vec3(0.0,0.0,0.0));
_viewPointStack.push_back(_eyePointStack.back());
break;
case(Transform::ABSOLUTE_RF_INHERIT_VIEWPOINT):
{
_eyePointStack.push_back(inv.getTrans());
osg::Vec3 referenceViewPoint = getReferenceViewPoint();
if (originalModelView)
{
osg::Matrix viewPointTransformMatrix;
viewPointTransformMatrix.invert(*originalModelView);
viewPointTransformMatrix.postMult(*matrix);
referenceViewPoint = referenceViewPoint * viewPointTransformMatrix;
}
_referenceViewPoints.push_back(referenceViewPoint);
_viewPointStack.push_back(getReferenceViewPoint() * inv);
break;
}
}
osg::Vec3 lookVector = getLookVectorLocal();
_bbCornerFar = (lookVector.x()>=0?1:0) |
(lookVector.y()>=0?2:0) |
(lookVector.z()>=0?4:0);
_bbCornerNear = (~_bbCornerFar)&7;
}
void CullStack::popModelViewMatrix()
{
_modelviewStack.pop_back();
_eyePointStack.pop_back();
_referenceViewPoints.pop_back();
_viewPointStack.pop_back();
popCullingSet();
osg::Vec3 lookVector(0.0f,0.0f,-1.0f);
if (!_modelviewStack.empty())
{
lookVector = getLookVectorLocal();
}
_bbCornerFar = (lookVector.x()>=0?1:0) |
(lookVector.y()>=0?2:0) |
(lookVector.z()>=0?4:0);
_bbCornerNear = (~_bbCornerFar)&7;
}
void CullStack::computeFrustumVolume()
{
osg::Matrix invP;
invP.invert(*getProjectionMatrix());
osg::Vec3 f1(-1,-1,-1); f1 = f1*invP;
osg::Vec3 f2(-1, 1,-1); f2 = f2*invP;
osg::Vec3 f3( 1, 1,-1); f3 = f3*invP;
osg::Vec3 f4( 1,-1,-1); f4 = f4*invP;
osg::Vec3 b1(-1,-1,1); b1 = b1*invP;
osg::Vec3 b2(-1, 1,1); b2 = b2*invP;
osg::Vec3 b3( 1, 1,1); b3 = b3*invP;
osg::Vec3 b4( 1,-1,1); b4 = b4*invP;
_frustumVolume = computeVolume(f1,f2,f3,b1,b2,b3)+
computeVolume(f2,f3,f4,b1,b3,b4);
}
| 27.980263 | 139 | 0.641312 | UM-ARM-Lab |
f9dd51dc663a65c0e9c2954e3f9a6bd117a80f77 | 10,537 | cpp | C++ | src/afv/VoiceSession.cpp | pierr3/afv-native | b85ddc102ae25600954f0f528169d701f685132f | [
"BSD-3-Clause"
] | 2 | 2022-02-02T20:50:25.000Z | 2022-02-27T09:21:44.000Z | src/afv/VoiceSession.cpp | xpilot-project/afv-native | afd4e4481a6a2eb373af36d2da322ad7ac104849 | [
"BSD-3-Clause"
] | null | null | null | src/afv/VoiceSession.cpp | xpilot-project/afv-native | afd4e4481a6a2eb373af36d2da322ad7ac104849 | [
"BSD-3-Clause"
] | 1 | 2022-01-10T18:23:32.000Z | 2022-01-10T18:23:32.000Z | /* afv/VoiceSession.cpp
*
* This file is part of AFV-Native.
*
* Copyright (c) 2019 Christopher Collins
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "afv-native/afv/VoiceSession.h"
#include <nlohmann/json.hpp>
#include "afv-native/Log.h"
#include "afv-native/afv/APISession.h"
#include "afv-native/afv/params.h"
#include "afv-native/afv/dto/Transceiver.h"
#include "afv-native/afv/dto/voice_server/Heartbeat.h"
#include "afv-native/http/Request.h"
#include "afv-native/cryptodto/UDPChannel.h"
using namespace afv_native::afv;
using namespace afv_native;
using json = nlohmann::json;
VoiceSession::VoiceSession(APISession &session, const std::string &callsign):
mSession(session),
mCallsign(callsign),
mBaseUrl(""),
mVoiceSessionSetupRequest("", http::Method::POST, json()),
mVoiceSessionTeardownRequest("", http::Method::DEL, json()),
mTransceiverUpdateRequest("", http::Method::POST, json()),
mChannel(session.getEventBase()),
mHeartbeatTimer(mSession.getEventBase(), std::bind(&VoiceSession::sendHeartbeatCallback, this)),
mLastHeartbeatReceived(0),
mHeartbeatTimeout(mSession.getEventBase(), std::bind(&VoiceSession::heartbeatTimedOut, this)),
mLastError(VoiceSessionError::NoError)
{
updateBaseUrl();
}
VoiceSession::~VoiceSession()
{
mHeartbeatTimer.disable();
mHeartbeatTimeout.disable();
mChannel.close();
mVoiceSessionSetupRequest.reset();
}
bool
VoiceSession::Connect()
{
// we cannot start the voice session if the API session is in any state OTHER than running...
if (mSession.getState() != APISessionState::Running) {
return false;
}
mVoiceSessionSetupRequest.reset();
// fix up the request URL
updateBaseUrl();
mSession.setAuthenticationFor(mVoiceSessionSetupRequest);
mVoiceSessionSetupRequest.setCompletionCallback(std::bind(&VoiceSession::voiceSessionSetupRequestCallback, this, std::placeholders::_1, std::placeholders::_2));
auto &transferManager = mSession.getTransferManager();
mVoiceSessionSetupRequest.shareState(transferManager);
mVoiceSessionSetupRequest.doAsync(transferManager);
return true;
}
void VoiceSession::voiceSessionSetupRequestCallback(http::Request *req, bool success) {
if (success) {
if (req->getStatusCode() == 200) {
auto *restreq = dynamic_cast<http::RESTRequest *>(req);
assert(restreq != nullptr);
try {
auto j = restreq->getResponse();
dto::PostCallsignResponse cresp;
j.get_to(cresp);
if (!setupSession(cresp)) {
failSession();
}
} catch (json::exception &e) {
LOG("voicesession", "exception parsing voice session setup: %s", e.what());
mLastError = VoiceSessionError::BadResponseFromAPIServer;
failSession();
}
} else {
LOG("voicesession",
"request for voice session failed: got status %d",
req->getStatusCode());
mLastError = VoiceSessionError::BadResponseFromAPIServer;
failSession();
}
} else {
LOG("voicesession",
"request for voice session failed: got internal error %s",
req->getCurlError().c_str());
mLastError = VoiceSessionError::BadResponseFromAPIServer;
failSession();
}
}
bool VoiceSession::setupSession(const dto::PostCallsignResponse &cresp)
{
mChannel.close();
mChannel.setAddress(cresp.VoiceServer.AddressIpV4);
mChannel.setChannelConfig(cresp.VoiceServer.ChannelConfig);
if (!mChannel.open()) {
LOG("VoiceSession:setupSession", "unable to open UDP session");
mLastError = VoiceSessionError::UDPChannelError;
return false;
}
mVoiceSessionSetupRequest.reset();
mVoiceSessionTeardownRequest.reset();
mLastHeartbeatReceived = util::monotime_get();
mHeartbeatTimer.enable(afvHeartbeatIntervalMs);
mHeartbeatTimeout.enable(afvHeartbeatTimeoutMs);
mChannel.registerDtoHandler(
"HA", [this](const unsigned char *data, size_t len) {
this->receivedHeartbeat();
});
mLastError = VoiceSessionError::NoError;
StateCallback.invokeAll(VoiceSessionState::Connected);
// now that everything's been invoked, attach our callback for reconnect handling
mSession.StateCallback.addCallback(this, std::bind(&VoiceSession::sessionStateCallback, this, std::placeholders::_1));
return true;
}
void VoiceSession::failSession()
{
mHeartbeatTimer.disable();
mHeartbeatTimeout.disable();
mChannel.close();
mVoiceSessionSetupRequest.reset();
// before we invoke state callbacks, remove our session handler so we don't get recursive loops.
mSession.StateCallback.removeCallback(this);
if (mLastError != VoiceSessionError::NoError) {
StateCallback.invokeAll(VoiceSessionState::Error);
} else {
StateCallback.invokeAll(VoiceSessionState::Disconnected);
}
}
void VoiceSession::sendHeartbeatCallback()
{
dto::Heartbeat hbDto(mCallsign);
if (mChannel.isOpen()) {
mChannel.sendDto(hbDto);
mHeartbeatTimer.enable(afvHeartbeatIntervalMs);
}
}
void VoiceSession::receivedHeartbeat()
{
mLastHeartbeatReceived = util::monotime_get();
mHeartbeatTimeout.disable();
mHeartbeatTimeout.enable(afvHeartbeatTimeoutMs);
}
void VoiceSession::heartbeatTimedOut()
{
util::monotime_t now = util::monotime_get();
LOG("voicesession", "heartbeat timeout - %d ms elapsed - disconnecting", now - mLastHeartbeatReceived);
mLastError = VoiceSessionError::Timeout;
Disconnect(true, true);
}
void VoiceSession::Disconnect(bool do_close, bool reconnect)
{
if (do_close) {
mVoiceSessionTeardownRequest.reset();
mVoiceSessionTeardownRequest.setUrl(mBaseUrl);
mSession.setAuthenticationFor(mVoiceSessionTeardownRequest);
// because we're likely going to get discarded by our owner when this function returns, we
// need to hold onto a shared_ptr reference to prevent cleanup until *AFTER* this callback completes.
auto &transferManager = mSession.getTransferManager();
mVoiceSessionTeardownRequest.setCompletionCallback(
[](http::Request *req, bool success) mutable {
if (success) {
if (req->getStatusCode() != 200) {
LOG("VoiceSession:Disconnect", "Callsign Dereg Failed. Status Code: %d", req->getStatusCode());
}
} else {
LOG("VoiceSession:Disconnect", "Callsign Dereg Failed. Internal Error: %s", req->getCurlError().c_str());
}
});
// and now schedule this request to be performed.
mVoiceSessionTeardownRequest.shareState(transferManager);
mVoiceSessionTeardownRequest.doAsync(transferManager);
}
failSession();
if(reconnect) {
mSession.Connect();
}
}
void VoiceSession::postTransceiverUpdate(
const std::vector<dto::Transceiver> &txDto,
std::function<void(http::Request *, bool)> callback)
{
updateBaseUrl();
mTransceiverUpdateRequest.reset();
mSession.setAuthenticationFor(mTransceiverUpdateRequest);
// only send the transceivers that have a valid frequency (read: not zero)
std::vector<dto::Transceiver> filteredDto;
std::copy_if(txDto.begin(), txDto.end(), std::back_inserter(filteredDto), [](dto::Transceiver t){ return t.Frequency > 0; });
mTransceiverUpdateRequest.setRequestBody(filteredDto);
mTransceiverUpdateRequest.setCompletionCallback(callback);
// and now schedule this request to be performed.
auto &transferManager = mSession.getTransferManager();
mTransceiverUpdateRequest.shareState(transferManager);
mTransceiverUpdateRequest.doAsync(transferManager);
LOG("VoiceSession", "postTransceiverUpdate");
}
bool VoiceSession::isConnected() const
{
return mChannel.isOpen();
}
void VoiceSession::setCallsign(const std::string &newCallsign)
{
if (!mChannel.isOpen()) {
mCallsign = newCallsign;
}
}
afv_native::cryptodto::UDPChannel &VoiceSession::getUDPChannel()
{
return mChannel;
}
void VoiceSession::updateBaseUrl()
{
mBaseUrl = mSession.getBaseUrl() + "/api/v1/users/" + mSession.getUsername() + "/callsigns/" + mCallsign;
mVoiceSessionSetupRequest.setUrl(mBaseUrl);
mVoiceSessionTeardownRequest.setUrl(mBaseUrl);
mTransceiverUpdateRequest.setUrl(mBaseUrl + "/transceivers");
}
VoiceSessionError VoiceSession::getLastError() const
{
return mLastError;
}
void VoiceSession::sessionStateCallback(APISessionState state) {
switch (state) {
case afv::APISessionState::Disconnected:
case afv::APISessionState::Error:
if (isConnected()) {
failSession();
}
break;
default:
break;
}
}
| 36.842657 | 164 | 0.690329 | pierr3 |
f9e0b6413b2ef2e1ae6b6723e406dc63f4a53f55 | 52,602 | cpp | C++ | src/frameworks/native/services/surfaceflinger/tests/fakehwc/SFFakeHwc_test.cpp | dAck2cC2/m3e | 475b89b59d5022a94e00b636438b25e27e4eaab2 | [
"Apache-2.0"
] | null | null | null | src/frameworks/native/services/surfaceflinger/tests/fakehwc/SFFakeHwc_test.cpp | dAck2cC2/m3e | 475b89b59d5022a94e00b636438b25e27e4eaab2 | [
"Apache-2.0"
] | null | null | null | src/frameworks/native/services/surfaceflinger/tests/fakehwc/SFFakeHwc_test.cpp | dAck2cC2/m3e | 475b89b59d5022a94e00b636438b25e27e4eaab2 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// #define LOG_NDEBUG 0
#undef LOG_TAG
#define LOG_TAG "FakeHwcTest"
#include "FakeComposerClient.h"
#include "FakeComposerService.h"
#include "FakeComposerUtils.h"
#include <gui/DisplayEventReceiver.h>
#include <gui/ISurfaceComposer.h>
#include <gui/LayerDebugInfo.h>
#include <gui/LayerState.h>
#include <gui/Surface.h>
#include <gui/SurfaceComposerClient.h>
#include <android/hidl/manager/1.0/IServiceManager.h>
#include <android/looper.h>
#include <android/native_window.h>
#include <binder/ProcessState.h>
#include <hwbinder/ProcessState.h>
#include <log/log.h>
#include <private/gui/ComposerService.h>
#include <ui/DisplayInfo.h>
#include <utils/Looper.h>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include <limits>
using namespace std::chrono_literals;
using namespace android;
using namespace android::hardware;
using namespace sftest;
namespace {
// Mock test helpers
using ::testing::Invoke;
using ::testing::Return;
using ::testing::SetArgPointee;
using ::testing::_;
using Transaction = SurfaceComposerClient::Transaction;
///////////////////////////////////////////////
struct TestColor {
public:
uint8_t r;
uint8_t g;
uint8_t b;
uint8_t a;
};
constexpr static TestColor RED = {195, 63, 63, 255};
constexpr static TestColor LIGHT_RED = {255, 177, 177, 255};
constexpr static TestColor GREEN = {63, 195, 63, 255};
constexpr static TestColor BLUE = {63, 63, 195, 255};
constexpr static TestColor DARK_GRAY = {63, 63, 63, 255};
constexpr static TestColor LIGHT_GRAY = {200, 200, 200, 255};
// Fill an RGBA_8888 formatted surface with a single color.
static void fillSurfaceRGBA8(const sp<SurfaceControl>& sc, const TestColor& color,
bool unlock = true) {
ANativeWindow_Buffer outBuffer;
sp<Surface> s = sc->getSurface();
ASSERT_TRUE(s != nullptr);
ASSERT_EQ(NO_ERROR, s->lock(&outBuffer, nullptr));
uint8_t* img = reinterpret_cast<uint8_t*>(outBuffer.bits);
for (int y = 0; y < outBuffer.height; y++) {
for (int x = 0; x < outBuffer.width; x++) {
uint8_t* pixel = img + (4 * (y * outBuffer.stride + x));
pixel[0] = color.r;
pixel[1] = color.g;
pixel[2] = color.b;
pixel[3] = color.a;
}
}
if (unlock) {
ASSERT_EQ(NO_ERROR, s->unlockAndPost());
}
}
inline RenderState makeSimpleRect(int left, int top, int right, int bottom) {
RenderState res;
res.mDisplayFrame = hwc_rect_t{left, top, right, bottom};
res.mPlaneAlpha = 1.0f;
res.mSwapCount = 0;
res.mSourceCrop = hwc_frect_t{0.f, 0.f, static_cast<float>(right - left),
static_cast<float>(bottom - top)};
return res;
}
inline RenderState makeSimpleRect(unsigned int left, unsigned int top, unsigned int right,
unsigned int bottom) {
EXPECT_LE(left, static_cast<unsigned int>(INT_MAX));
EXPECT_LE(top, static_cast<unsigned int>(INT_MAX));
EXPECT_LE(right, static_cast<unsigned int>(INT_MAX));
EXPECT_LE(bottom, static_cast<unsigned int>(INT_MAX));
return makeSimpleRect(static_cast<int>(left), static_cast<int>(top), static_cast<int>(right),
static_cast<int>(bottom));
}
////////////////////////////////////////////////
class DisplayTest : public ::testing::Test {
public:
class MockComposerClient : public FakeComposerClient {
public:
MOCK_METHOD2(getDisplayType, Error(Display display, ComposerClient::DisplayType* outType));
MOCK_METHOD4(getDisplayAttribute,
Error(Display display, Config config, IComposerClient::Attribute attribute,
int32_t* outValue));
// Re-routing to basic fake implementation
Error getDisplayAttributeFake(Display display, Config config,
IComposerClient::Attribute attribute, int32_t* outValue) {
return FakeComposerClient::getDisplayAttribute(display, config, attribute, outValue);
}
};
protected:
static int processDisplayEvents(int fd, int events, void* data);
void SetUp() override;
void TearDown() override;
void waitForDisplayTransaction();
bool waitForHotplugEvent(PhysicalDisplayId displayId, bool connected);
sp<IComposer> mFakeService;
sp<SurfaceComposerClient> mComposerClient;
MockComposerClient* mMockComposer;
std::unique_ptr<DisplayEventReceiver> mReceiver;
sp<Looper> mLooper;;
std::deque<DisplayEventReceiver::Event> mReceivedDisplayEvents;
};
void DisplayTest::SetUp() {
// TODO: The mMockComposer should be a unique_ptr, but it needs to
// outlive the test class. Currently ComposerClient only dies
// when the service is replaced. The Mock deletes itself when
// removeClient is called on it, which is ugly. This can be
// changed if HIDL ServiceManager allows removing services or
// ComposerClient starts taking the ownership of the contained
// implementation class. Moving the fake class to the HWC2
// interface instead of the current Composer interface might also
// change the situation.
mMockComposer = new MockComposerClient;
sp<ComposerClient> client = new ComposerClient(mMockComposer);
mFakeService = new FakeComposerService(client);
(void)mFakeService->registerAsService("mock");
android::hardware::ProcessState::self()->startThreadPool();
android::ProcessState::self()->startThreadPool();
EXPECT_CALL(*mMockComposer, getDisplayType(PRIMARY_DISPLAY, _))
.WillOnce(DoAll(SetArgPointee<1>(IComposerClient::DisplayType::PHYSICAL),
Return(Error::NONE)));
// Primary display will be queried twice for all 5 attributes. One
// set of queries comes from the SurfaceFlinger proper an the
// other set from the VR composer.
// TODO: Is VR composer always present? Change to atLeast(5)?
EXPECT_CALL(*mMockComposer, getDisplayAttribute(PRIMARY_DISPLAY, 1, _, _))
.Times(2 * 5)
.WillRepeatedly(Invoke(mMockComposer, &MockComposerClient::getDisplayAttributeFake));
startSurfaceFlinger();
// Fake composer wants to enable VSync injection
mMockComposer->onSurfaceFlingerStart();
mComposerClient = new SurfaceComposerClient;
ASSERT_EQ(NO_ERROR, mComposerClient->initCheck());
mReceiver.reset(new DisplayEventReceiver());
mLooper = new Looper(false);
mLooper->addFd(mReceiver->getFd(), 0, ALOOPER_EVENT_INPUT, processDisplayEvents, this);
}
void DisplayTest::TearDown() {
mLooper = nullptr;
mReceiver = nullptr;
mComposerClient->dispose();
mComposerClient = nullptr;
// Fake composer needs to release SurfaceComposerClient before the stop.
mMockComposer->onSurfaceFlingerStop();
stopSurfaceFlinger();
mFakeService = nullptr;
// TODO: Currently deleted in FakeComposerClient::removeClient(). Devise better lifetime
// management.
mMockComposer = nullptr;
}
int DisplayTest::processDisplayEvents(int /*fd*/, int /*events*/, void* data) {
auto self = static_cast<DisplayTest*>(data);
ssize_t n;
DisplayEventReceiver::Event buffer[1];
while ((n = self->mReceiver->getEvents(buffer, 1)) > 0) {
for (int i=0 ; i<n ; i++) {
self->mReceivedDisplayEvents.push_back(buffer[i]);
}
}
ALOGD_IF(n < 0, "Error reading events (%s)\n", strerror(-n));
return 1;
}
void DisplayTest::waitForDisplayTransaction() {
// Both a refresh and a vsync event are needed to apply pending display
// transactions.
mMockComposer->refreshDisplay(EXTERNAL_DISPLAY);
mMockComposer->runVSyncAndWait();
// Extra vsync and wait to avoid a 10% flake due to a race.
mMockComposer->runVSyncAndWait();
}
bool DisplayTest::waitForHotplugEvent(PhysicalDisplayId displayId, bool connected) {
int waitCount = 20;
while (waitCount--) {
while (!mReceivedDisplayEvents.empty()) {
auto event = mReceivedDisplayEvents.front();
mReceivedDisplayEvents.pop_front();
ALOGV_IF(event.header.type == DisplayEventReceiver::DISPLAY_EVENT_HOTPLUG,
"event hotplug: displayId %" ANDROID_PHYSICAL_DISPLAY_ID_FORMAT
", connected %d\t",
event.header.displayId, event.hotplug.connected);
if (event.header.type == DisplayEventReceiver::DISPLAY_EVENT_HOTPLUG &&
event.header.displayId == displayId && event.hotplug.connected == connected) {
return true;
}
}
mLooper->pollOnce(1);
}
return false;
}
TEST_F(DisplayTest, Hotplug) {
ALOGD("DisplayTest::Hotplug");
EXPECT_CALL(*mMockComposer, getDisplayType(EXTERNAL_DISPLAY, _))
.Times(2)
.WillRepeatedly(DoAll(SetArgPointee<1>(IComposerClient::DisplayType::PHYSICAL),
Return(Error::NONE)));
// The attribute queries will get done twice. This is for defaults
EXPECT_CALL(*mMockComposer, getDisplayAttribute(EXTERNAL_DISPLAY, 1, _, _))
.Times(2 * 3)
.WillRepeatedly(Invoke(mMockComposer, &MockComposerClient::getDisplayAttributeFake));
// ... and then special handling for dimensions. Specifying these
// rules later means that gmock will try them first, i.e.,
// ordering of width/height vs. the default implementation for
// other queries is significant.
EXPECT_CALL(*mMockComposer,
getDisplayAttribute(EXTERNAL_DISPLAY, 1, IComposerClient::Attribute::WIDTH, _))
.Times(2)
.WillRepeatedly(DoAll(SetArgPointee<3>(400), Return(Error::NONE)));
EXPECT_CALL(*mMockComposer,
getDisplayAttribute(EXTERNAL_DISPLAY, 1, IComposerClient::Attribute::HEIGHT, _))
.Times(2)
.WillRepeatedly(DoAll(SetArgPointee<3>(200), Return(Error::NONE)));
mMockComposer->hotplugDisplay(EXTERNAL_DISPLAY, IComposerCallback::Connection::CONNECTED);
waitForDisplayTransaction();
EXPECT_TRUE(waitForHotplugEvent(EXTERNAL_DISPLAY, true));
{
const auto display = SurfaceComposerClient::getPhysicalDisplayToken(EXTERNAL_DISPLAY);
ASSERT_FALSE(display == nullptr);
DisplayInfo info;
ASSERT_EQ(NO_ERROR, SurfaceComposerClient::getDisplayInfo(display, &info));
ASSERT_EQ(400u, info.w);
ASSERT_EQ(200u, info.h);
auto surfaceControl =
mComposerClient->createSurface(String8("Display Test Surface Foo"), info.w, info.h,
PIXEL_FORMAT_RGBA_8888, 0);
ASSERT_TRUE(surfaceControl != nullptr);
ASSERT_TRUE(surfaceControl->isValid());
fillSurfaceRGBA8(surfaceControl, BLUE);
{
TransactionScope ts(*mMockComposer);
ts.setDisplayLayerStack(display, 0);
ts.setLayer(surfaceControl, INT32_MAX - 2)
.show(surfaceControl);
}
}
mMockComposer->hotplugDisplay(EXTERNAL_DISPLAY, IComposerCallback::Connection::DISCONNECTED);
mMockComposer->clearFrames();
mMockComposer->hotplugDisplay(EXTERNAL_DISPLAY, IComposerCallback::Connection::CONNECTED);
waitForDisplayTransaction();
EXPECT_TRUE(waitForHotplugEvent(EXTERNAL_DISPLAY, false));
EXPECT_TRUE(waitForHotplugEvent(EXTERNAL_DISPLAY, true));
{
const auto display = SurfaceComposerClient::getPhysicalDisplayToken(EXTERNAL_DISPLAY);
ASSERT_FALSE(display == nullptr);
DisplayInfo info;
ASSERT_EQ(NO_ERROR, SurfaceComposerClient::getDisplayInfo(display, &info));
ASSERT_EQ(400u, info.w);
ASSERT_EQ(200u, info.h);
auto surfaceControl =
mComposerClient->createSurface(String8("Display Test Surface Bar"), info.w, info.h,
PIXEL_FORMAT_RGBA_8888, 0);
ASSERT_TRUE(surfaceControl != nullptr);
ASSERT_TRUE(surfaceControl->isValid());
fillSurfaceRGBA8(surfaceControl, BLUE);
{
TransactionScope ts(*mMockComposer);
ts.setDisplayLayerStack(display, 0);
ts.setLayer(surfaceControl, INT32_MAX - 2)
.show(surfaceControl);
}
}
mMockComposer->hotplugDisplay(EXTERNAL_DISPLAY, IComposerCallback::Connection::DISCONNECTED);
}
TEST_F(DisplayTest, HotplugPrimaryDisplay) {
ALOGD("DisplayTest::HotplugPrimaryDisplay");
mMockComposer->hotplugDisplay(PRIMARY_DISPLAY, IComposerCallback::Connection::DISCONNECTED);
waitForDisplayTransaction();
EXPECT_TRUE(waitForHotplugEvent(PRIMARY_DISPLAY, false));
{
const auto display = SurfaceComposerClient::getPhysicalDisplayToken(PRIMARY_DISPLAY);
EXPECT_FALSE(display == nullptr);
DisplayInfo info;
auto result = SurfaceComposerClient::getDisplayInfo(display, &info);
EXPECT_NE(NO_ERROR, result);
}
mMockComposer->clearFrames();
EXPECT_CALL(*mMockComposer, getDisplayType(PRIMARY_DISPLAY, _))
.Times(2)
.WillRepeatedly(DoAll(SetArgPointee<1>(IComposerClient::DisplayType::PHYSICAL),
Return(Error::NONE)));
// The attribute queries will get done twice. This is for defaults
EXPECT_CALL(*mMockComposer, getDisplayAttribute(PRIMARY_DISPLAY, 1, _, _))
.Times(2 * 3)
.WillRepeatedly(Invoke(mMockComposer, &MockComposerClient::getDisplayAttributeFake));
// ... and then special handling for dimensions. Specifying these
// rules later means that gmock will try them first, i.e.,
// ordering of width/height vs. the default implementation for
// other queries is significant.
EXPECT_CALL(*mMockComposer,
getDisplayAttribute(PRIMARY_DISPLAY, 1, IComposerClient::Attribute::WIDTH, _))
.Times(2)
.WillRepeatedly(DoAll(SetArgPointee<3>(400), Return(Error::NONE)));
EXPECT_CALL(*mMockComposer,
getDisplayAttribute(PRIMARY_DISPLAY, 1, IComposerClient::Attribute::HEIGHT, _))
.Times(2)
.WillRepeatedly(DoAll(SetArgPointee<3>(200), Return(Error::NONE)));
mMockComposer->hotplugDisplay(PRIMARY_DISPLAY, IComposerCallback::Connection::CONNECTED);
waitForDisplayTransaction();
EXPECT_TRUE(waitForHotplugEvent(PRIMARY_DISPLAY, true));
{
const auto display = SurfaceComposerClient::getPhysicalDisplayToken(PRIMARY_DISPLAY);
EXPECT_FALSE(display == nullptr);
DisplayInfo info;
auto result = SurfaceComposerClient::getDisplayInfo(display, &info);
EXPECT_EQ(NO_ERROR, result);
ASSERT_EQ(400u, info.w);
ASSERT_EQ(200u, info.h);
}
}
////////////////////////////////////////////////
class TransactionTest : public ::testing::Test {
protected:
// Layer array indexing constants.
constexpr static int BG_LAYER = 0;
constexpr static int FG_LAYER = 1;
static void SetUpTestCase();
static void TearDownTestCase();
void SetUp() override;
void TearDown() override;
sp<SurfaceComposerClient> mComposerClient;
sp<SurfaceControl> mBGSurfaceControl;
sp<SurfaceControl> mFGSurfaceControl;
std::vector<RenderState> mBaseFrame;
uint32_t mDisplayWidth;
uint32_t mDisplayHeight;
static FakeComposerClient* sFakeComposer;
};
FakeComposerClient* TransactionTest::sFakeComposer;
void TransactionTest::SetUpTestCase() {
// TODO: See TODO comment at DisplayTest::SetUp for background on
// the lifetime of the FakeComposerClient.
sFakeComposer = new FakeComposerClient;
sp<ComposerClient> client = new ComposerClient(sFakeComposer);
sp<IComposer> fakeService = new FakeComposerService(client);
(void)fakeService->registerAsService("mock");
android::hardware::ProcessState::self()->startThreadPool();
android::ProcessState::self()->startThreadPool();
startSurfaceFlinger();
// Fake composer wants to enable VSync injection
sFakeComposer->onSurfaceFlingerStart();
}
void TransactionTest::TearDownTestCase() {
// Fake composer needs to release SurfaceComposerClient before the stop.
sFakeComposer->onSurfaceFlingerStop();
stopSurfaceFlinger();
// TODO: This is deleted when the ComposerClient calls
// removeClient. Devise better lifetime control.
sFakeComposer = nullptr;
}
void TransactionTest::SetUp() {
ALOGI("TransactionTest::SetUp");
mComposerClient = new SurfaceComposerClient;
ASSERT_EQ(NO_ERROR, mComposerClient->initCheck());
ALOGI("TransactionTest::SetUp - display");
const auto display = SurfaceComposerClient::getPhysicalDisplayToken(PRIMARY_DISPLAY);
ASSERT_FALSE(display == nullptr);
DisplayInfo info;
ASSERT_EQ(NO_ERROR, SurfaceComposerClient::getDisplayInfo(display, &info));
mDisplayWidth = info.w;
mDisplayHeight = info.h;
// Background surface
mBGSurfaceControl = mComposerClient->createSurface(String8("BG Test Surface"), mDisplayWidth,
mDisplayHeight, PIXEL_FORMAT_RGBA_8888, 0);
ASSERT_TRUE(mBGSurfaceControl != nullptr);
ASSERT_TRUE(mBGSurfaceControl->isValid());
fillSurfaceRGBA8(mBGSurfaceControl, BLUE);
// Foreground surface
mFGSurfaceControl = mComposerClient->createSurface(String8("FG Test Surface"), 64, 64,
PIXEL_FORMAT_RGBA_8888, 0);
ASSERT_TRUE(mFGSurfaceControl != nullptr);
ASSERT_TRUE(mFGSurfaceControl->isValid());
fillSurfaceRGBA8(mFGSurfaceControl, RED);
Transaction t;
t.setDisplayLayerStack(display, 0);
t.setLayer(mBGSurfaceControl, INT32_MAX - 2);
t.show(mBGSurfaceControl);
t.setLayer(mFGSurfaceControl, INT32_MAX - 1);
t.setPosition(mFGSurfaceControl, 64, 64);
t.show(mFGSurfaceControl);
// Synchronous transaction will stop this thread, so we set up a
// delayed, off-thread vsync request before closing the
// transaction. In the test code this is usually done with
// TransactionScope. Leaving here in the 'vanilla' form for
// reference.
ASSERT_EQ(0, sFakeComposer->getFrameCount());
sFakeComposer->runVSyncAfter(1ms);
t.apply();
sFakeComposer->waitUntilFrame(1);
// Reference data. This is what the HWC should see.
static_assert(BG_LAYER == 0 && FG_LAYER == 1, "Unexpected enum values for array indexing");
mBaseFrame.push_back(makeSimpleRect(0u, 0u, mDisplayWidth, mDisplayHeight));
mBaseFrame[BG_LAYER].mSwapCount = 1;
mBaseFrame.push_back(makeSimpleRect(64, 64, 64 + 64, 64 + 64));
mBaseFrame[FG_LAYER].mSwapCount = 1;
auto frame = sFakeComposer->getFrameRects(0);
ASSERT_TRUE(framesAreSame(mBaseFrame, frame));
}
void TransactionTest::TearDown() {
ALOGD("TransactionTest::TearDown");
mComposerClient->dispose();
mBGSurfaceControl = 0;
mFGSurfaceControl = 0;
mComposerClient = 0;
sFakeComposer->runVSyncAndWait();
mBaseFrame.clear();
sFakeComposer->clearFrames();
ASSERT_EQ(0, sFakeComposer->getFrameCount());
sp<ISurfaceComposer> sf(ComposerService::getComposerService());
std::vector<LayerDebugInfo> layers;
status_t result = sf->getLayerDebugInfo(&layers);
if (result != NO_ERROR) {
ALOGE("Failed to get layers %s %d", strerror(-result), result);
} else {
// If this fails, the test being torn down leaked layers.
EXPECT_EQ(0u, layers.size());
if (layers.size() > 0) {
for (auto layer = layers.begin(); layer != layers.end(); ++layer) {
std::cout << to_string(*layer).c_str();
}
// To ensure the next test has clean slate, will run the class
// tear down and setup here.
TearDownTestCase();
SetUpTestCase();
}
}
ALOGD("TransactionTest::TearDown - complete");
}
TEST_F(TransactionTest, LayerMove) {
ALOGD("TransactionTest::LayerMove");
// The scope opens and closes a global transaction and, at the
// same time, makes sure the SurfaceFlinger progresses one frame
// after the transaction closes. The results of the transaction
// should be available in the latest frame stored by the fake
// composer.
{
TransactionScope ts(*sFakeComposer);
ts.setPosition(mFGSurfaceControl, 128, 128);
// NOTE: No changes yet, so vsync will do nothing, HWC does not get any calls.
// (How to verify that? Throw in vsync and wait a 2x frame time? Separate test?)
//
// sFakeComposer->runVSyncAndWait();
}
fillSurfaceRGBA8(mFGSurfaceControl, GREEN);
sFakeComposer->runVSyncAndWait();
ASSERT_EQ(3, sFakeComposer->getFrameCount()); // Make sure the waits didn't time out and there's
// no extra frames.
// NOTE: Frame 0 is produced in the SetUp.
auto frame1Ref = mBaseFrame;
frame1Ref[FG_LAYER].mDisplayFrame =
hwc_rect_t{128, 128, 128 + 64, 128 + 64}; // Top-most layer moves.
EXPECT_TRUE(framesAreSame(frame1Ref, sFakeComposer->getFrameRects(1)));
auto frame2Ref = frame1Ref;
frame2Ref[FG_LAYER].mSwapCount++;
EXPECT_TRUE(framesAreSame(frame2Ref, sFakeComposer->getFrameRects(2)));
}
TEST_F(TransactionTest, LayerResize) {
ALOGD("TransactionTest::LayerResize");
{
TransactionScope ts(*sFakeComposer);
ts.setSize(mFGSurfaceControl, 128, 128);
}
fillSurfaceRGBA8(mFGSurfaceControl, GREEN);
sFakeComposer->runVSyncAndWait();
ASSERT_EQ(3, sFakeComposer->getFrameCount()); // Make sure the waits didn't time out and there's
// no extra frames.
auto frame1Ref = mBaseFrame;
// NOTE: The resize should not be visible for frame 1 as there's no buffer with new size posted.
EXPECT_TRUE(framesAreSame(frame1Ref, sFakeComposer->getFrameRects(1)));
auto frame2Ref = frame1Ref;
frame2Ref[FG_LAYER].mSwapCount++;
frame2Ref[FG_LAYER].mDisplayFrame = hwc_rect_t{64, 64, 64 + 128, 64 + 128};
frame2Ref[FG_LAYER].mSourceCrop = hwc_frect_t{0.f, 0.f, 128.f, 128.f};
EXPECT_TRUE(framesAreSame(frame2Ref, sFakeComposer->getFrameRects(2)));
}
TEST_F(TransactionTest, LayerCrop) {
// TODO: Add scaling to confirm that crop happens in buffer space?
{
TransactionScope ts(*sFakeComposer);
Rect cropRect(16, 16, 32, 32);
ts.setCrop_legacy(mFGSurfaceControl, cropRect);
}
ASSERT_EQ(2, sFakeComposer->getFrameCount());
auto referenceFrame = mBaseFrame;
referenceFrame[FG_LAYER].mSourceCrop = hwc_frect_t{16.f, 16.f, 32.f, 32.f};
referenceFrame[FG_LAYER].mDisplayFrame = hwc_rect_t{64 + 16, 64 + 16, 64 + 32, 64 + 32};
EXPECT_TRUE(framesAreSame(referenceFrame, sFakeComposer->getLatestFrame()));
}
TEST_F(TransactionTest, LayerSetLayer) {
{
TransactionScope ts(*sFakeComposer);
ts.setLayer(mFGSurfaceControl, INT_MAX - 3);
}
ASSERT_EQ(2, sFakeComposer->getFrameCount());
// The layers will switch order, but both are rendered because the background layer is
// transparent (RGBA8888).
std::vector<RenderState> referenceFrame(2);
referenceFrame[0] = mBaseFrame[FG_LAYER];
referenceFrame[1] = mBaseFrame[BG_LAYER];
EXPECT_TRUE(framesAreSame(referenceFrame, sFakeComposer->getLatestFrame()));
}
TEST_F(TransactionTest, LayerSetLayerOpaque) {
{
TransactionScope ts(*sFakeComposer);
ts.setLayer(mFGSurfaceControl, INT_MAX - 3);
ts.setFlags(mBGSurfaceControl, layer_state_t::eLayerOpaque,
layer_state_t::eLayerOpaque);
}
ASSERT_EQ(2, sFakeComposer->getFrameCount());
// The former foreground layer is now covered with opaque layer - it should have disappeared
std::vector<RenderState> referenceFrame(1);
referenceFrame[BG_LAYER] = mBaseFrame[BG_LAYER];
EXPECT_TRUE(framesAreSame(referenceFrame, sFakeComposer->getLatestFrame()));
}
TEST_F(TransactionTest, SetLayerStack) {
ALOGD("TransactionTest::SetLayerStack");
{
TransactionScope ts(*sFakeComposer);
ts.setLayerStack(mFGSurfaceControl, 1);
}
// Foreground layer should have disappeared.
ASSERT_EQ(2, sFakeComposer->getFrameCount());
std::vector<RenderState> refFrame(1);
refFrame[BG_LAYER] = mBaseFrame[BG_LAYER];
EXPECT_TRUE(framesAreSame(refFrame, sFakeComposer->getLatestFrame()));
}
TEST_F(TransactionTest, LayerShowHide) {
ALOGD("TransactionTest::LayerShowHide");
{
TransactionScope ts(*sFakeComposer);
ts.hide(mFGSurfaceControl);
}
// Foreground layer should have disappeared.
ASSERT_EQ(2, sFakeComposer->getFrameCount());
std::vector<RenderState> refFrame(1);
refFrame[BG_LAYER] = mBaseFrame[BG_LAYER];
EXPECT_TRUE(framesAreSame(refFrame, sFakeComposer->getLatestFrame()));
{
TransactionScope ts(*sFakeComposer);
ts.show(mFGSurfaceControl);
}
// Foreground layer should be back
ASSERT_EQ(3, sFakeComposer->getFrameCount());
EXPECT_TRUE(framesAreSame(mBaseFrame, sFakeComposer->getLatestFrame()));
}
TEST_F(TransactionTest, LayerSetAlpha) {
{
TransactionScope ts(*sFakeComposer);
ts.setAlpha(mFGSurfaceControl, 0.75f);
}
ASSERT_EQ(2, sFakeComposer->getFrameCount());
auto referenceFrame = mBaseFrame;
referenceFrame[FG_LAYER].mPlaneAlpha = 0.75f;
EXPECT_TRUE(framesAreSame(referenceFrame, sFakeComposer->getLatestFrame()));
}
TEST_F(TransactionTest, LayerSetFlags) {
{
TransactionScope ts(*sFakeComposer);
ts.setFlags(mFGSurfaceControl, layer_state_t::eLayerHidden,
layer_state_t::eLayerHidden);
}
// Foreground layer should have disappeared.
ASSERT_EQ(2, sFakeComposer->getFrameCount());
std::vector<RenderState> refFrame(1);
refFrame[BG_LAYER] = mBaseFrame[BG_LAYER];
EXPECT_TRUE(framesAreSame(refFrame, sFakeComposer->getLatestFrame()));
}
TEST_F(TransactionTest, LayerSetMatrix) {
struct matrixTestData {
float matrix[4];
hwc_transform_t expectedTransform;
hwc_rect_t expectedDisplayFrame;
};
// The matrix operates on the display frame and is applied before
// the position is added. So, the foreground layer rect is (0, 0,
// 64, 64) is first transformed, potentially yielding negative
// coordinates and then the position (64, 64) is added yielding
// the final on-screen rectangles given.
const matrixTestData MATRIX_TESTS[7] = // clang-format off
{{{-1.f, 0.f, 0.f, 1.f}, HWC_TRANSFORM_FLIP_H, {0, 64, 64, 128}},
{{1.f, 0.f, 0.f, -1.f}, HWC_TRANSFORM_FLIP_V, {64, 0, 128, 64}},
{{0.f, 1.f, -1.f, 0.f}, HWC_TRANSFORM_ROT_90, {0, 64, 64, 128}},
{{-1.f, 0.f, 0.f, -1.f}, HWC_TRANSFORM_ROT_180, {0, 0, 64, 64}},
{{0.f, -1.f, 1.f, 0.f}, HWC_TRANSFORM_ROT_270, {64, 0, 128, 64}},
{{0.f, 1.f, 1.f, 0.f}, HWC_TRANSFORM_FLIP_H_ROT_90, {64, 64, 128, 128}},
{{0.f, 1.f, 1.f, 0.f}, HWC_TRANSFORM_FLIP_V_ROT_90, {64, 64, 128, 128}}};
// clang-format on
constexpr int TEST_COUNT = sizeof(MATRIX_TESTS) / sizeof(matrixTestData);
for (int i = 0; i < TEST_COUNT; i++) {
// TODO: How to leverage the HWC2 stringifiers?
const matrixTestData& xform = MATRIX_TESTS[i];
SCOPED_TRACE(i);
{
TransactionScope ts(*sFakeComposer);
ts.setMatrix(mFGSurfaceControl, xform.matrix[0], xform.matrix[1],
xform.matrix[2], xform.matrix[3]);
}
auto referenceFrame = mBaseFrame;
referenceFrame[FG_LAYER].mTransform = xform.expectedTransform;
referenceFrame[FG_LAYER].mDisplayFrame = xform.expectedDisplayFrame;
EXPECT_TRUE(framesAreSame(referenceFrame, sFakeComposer->getLatestFrame()));
}
}
#if 0
TEST_F(TransactionTest, LayerSetMatrix2) {
{
TransactionScope ts(*sFakeComposer);
// TODO: PLEASE SPEC THE FUNCTION!
ts.setMatrix(mFGSurfaceControl, 0.11f, 0.123f,
-2.33f, 0.22f);
}
auto referenceFrame = mBaseFrame;
// TODO: Is this correct for sure?
//referenceFrame[FG_LAYER].mTransform = HWC_TRANSFORM_FLIP_V & HWC_TRANSFORM_ROT_90;
EXPECT_TRUE(framesAreSame(referenceFrame, sFakeComposer->getLatestFrame()));
}
#endif
TEST_F(TransactionTest, DeferredTransaction) {
// Synchronization surface
constexpr static int SYNC_LAYER = 2;
auto syncSurfaceControl = mComposerClient->createSurface(String8("Sync Test Surface"), 1, 1,
PIXEL_FORMAT_RGBA_8888, 0);
ASSERT_TRUE(syncSurfaceControl != nullptr);
ASSERT_TRUE(syncSurfaceControl->isValid());
fillSurfaceRGBA8(syncSurfaceControl, DARK_GRAY);
{
TransactionScope ts(*sFakeComposer);
ts.setLayer(syncSurfaceControl, INT32_MAX - 1);
ts.setPosition(syncSurfaceControl, mDisplayWidth - 2, mDisplayHeight - 2);
ts.show(syncSurfaceControl);
}
auto referenceFrame = mBaseFrame;
referenceFrame.push_back(makeSimpleRect(mDisplayWidth - 2, mDisplayHeight - 2,
mDisplayWidth - 1, mDisplayHeight - 1));
referenceFrame[SYNC_LAYER].mSwapCount = 1;
EXPECT_EQ(2, sFakeComposer->getFrameCount());
EXPECT_TRUE(framesAreSame(referenceFrame, sFakeComposer->getLatestFrame()));
// set up two deferred transactions on different frames - these should not yield composited
// frames
{
TransactionScope ts(*sFakeComposer);
ts.setAlpha(mFGSurfaceControl, 0.75);
ts.deferTransactionUntil_legacy(mFGSurfaceControl, syncSurfaceControl->getHandle(),
syncSurfaceControl->getSurface()->getNextFrameNumber());
}
EXPECT_TRUE(framesAreSame(referenceFrame, sFakeComposer->getLatestFrame()));
{
TransactionScope ts(*sFakeComposer);
ts.setPosition(mFGSurfaceControl, 128, 128);
ts.deferTransactionUntil_legacy(mFGSurfaceControl, syncSurfaceControl->getHandle(),
syncSurfaceControl->getSurface()->getNextFrameNumber() + 1);
}
EXPECT_EQ(4, sFakeComposer->getFrameCount());
EXPECT_TRUE(framesAreSame(referenceFrame, sFakeComposer->getLatestFrame()));
// should trigger the first deferred transaction, but not the second one
fillSurfaceRGBA8(syncSurfaceControl, DARK_GRAY);
sFakeComposer->runVSyncAndWait();
EXPECT_EQ(5, sFakeComposer->getFrameCount());
referenceFrame[FG_LAYER].mPlaneAlpha = 0.75f;
referenceFrame[SYNC_LAYER].mSwapCount++;
EXPECT_TRUE(framesAreSame(referenceFrame, sFakeComposer->getLatestFrame()));
// should show up immediately since it's not deferred
{
TransactionScope ts(*sFakeComposer);
ts.setAlpha(mFGSurfaceControl, 1.0);
}
referenceFrame[FG_LAYER].mPlaneAlpha = 1.f;
EXPECT_EQ(6, sFakeComposer->getFrameCount());
EXPECT_TRUE(framesAreSame(referenceFrame, sFakeComposer->getLatestFrame()));
// trigger the second deferred transaction
fillSurfaceRGBA8(syncSurfaceControl, DARK_GRAY);
sFakeComposer->runVSyncAndWait();
// TODO: Compute from layer size?
referenceFrame[FG_LAYER].mDisplayFrame = hwc_rect_t{128, 128, 128 + 64, 128 + 64};
referenceFrame[SYNC_LAYER].mSwapCount++;
EXPECT_EQ(7, sFakeComposer->getFrameCount());
EXPECT_TRUE(framesAreSame(referenceFrame, sFakeComposer->getLatestFrame()));
}
TEST_F(TransactionTest, SetRelativeLayer) {
constexpr int RELATIVE_LAYER = 2;
auto relativeSurfaceControl = mComposerClient->createSurface(String8("Test Surface"), 64, 64,
PIXEL_FORMAT_RGBA_8888, 0);
fillSurfaceRGBA8(relativeSurfaceControl, LIGHT_RED);
// Now we stack the surface above the foreground surface and make sure it is visible.
{
TransactionScope ts(*sFakeComposer);
ts.setPosition(relativeSurfaceControl, 64, 64);
ts.show(relativeSurfaceControl);
ts.setRelativeLayer(relativeSurfaceControl, mFGSurfaceControl->getHandle(), 1);
}
auto referenceFrame = mBaseFrame;
// NOTE: All three layers will be visible as the surfaces are
// transparent because of the RGBA format.
referenceFrame.push_back(makeSimpleRect(64, 64, 64 + 64, 64 + 64));
referenceFrame[RELATIVE_LAYER].mSwapCount = 1;
EXPECT_TRUE(framesAreSame(referenceFrame, sFakeComposer->getLatestFrame()));
// A call to setLayer will override a call to setRelativeLayer
{
TransactionScope ts(*sFakeComposer);
ts.setLayer(relativeSurfaceControl, 0);
}
// Previous top layer will now appear at the bottom.
auto referenceFrame2 = mBaseFrame;
referenceFrame2.insert(referenceFrame2.begin(), referenceFrame[RELATIVE_LAYER]);
EXPECT_EQ(3, sFakeComposer->getFrameCount());
EXPECT_TRUE(framesAreSame(referenceFrame2, sFakeComposer->getLatestFrame()));
}
class ChildLayerTest : public TransactionTest {
protected:
constexpr static int CHILD_LAYER = 2;
void SetUp() override {
TransactionTest::SetUp();
mChild = mComposerClient->createSurface(String8("Child surface"), 10, 10,
PIXEL_FORMAT_RGBA_8888, 0, mFGSurfaceControl.get());
fillSurfaceRGBA8(mChild, LIGHT_GRAY);
sFakeComposer->runVSyncAndWait();
mBaseFrame.push_back(makeSimpleRect(64, 64, 64 + 10, 64 + 10));
mBaseFrame[CHILD_LAYER].mSwapCount = 1;
ASSERT_EQ(2, sFakeComposer->getFrameCount());
ASSERT_TRUE(framesAreSame(mBaseFrame, sFakeComposer->getLatestFrame()));
}
void TearDown() override {
mChild = 0;
TransactionTest::TearDown();
}
sp<SurfaceControl> mChild;
};
TEST_F(ChildLayerTest, Positioning) {
{
TransactionScope ts(*sFakeComposer);
ts.show(mChild);
ts.setPosition(mChild, 10, 10);
// Move to the same position as in the original setup.
ts.setPosition(mFGSurfaceControl, 64, 64);
}
auto referenceFrame = mBaseFrame;
referenceFrame[FG_LAYER].mDisplayFrame = hwc_rect_t{64, 64, 64 + 64, 64 + 64};
referenceFrame[CHILD_LAYER].mDisplayFrame =
hwc_rect_t{64 + 10, 64 + 10, 64 + 10 + 10, 64 + 10 + 10};
EXPECT_TRUE(framesAreSame(referenceFrame, sFakeComposer->getLatestFrame()));
{
TransactionScope ts(*sFakeComposer);
ts.setPosition(mFGSurfaceControl, 0, 0);
}
auto referenceFrame2 = mBaseFrame;
referenceFrame2[FG_LAYER].mDisplayFrame = hwc_rect_t{0, 0, 0 + 64, 0 + 64};
referenceFrame2[CHILD_LAYER].mDisplayFrame =
hwc_rect_t{0 + 10, 0 + 10, 0 + 10 + 10, 0 + 10 + 10};
EXPECT_TRUE(framesAreSame(referenceFrame2, sFakeComposer->getLatestFrame()));
}
TEST_F(ChildLayerTest, Cropping) {
{
TransactionScope ts(*sFakeComposer);
ts.show(mChild);
ts.setPosition(mChild, 0, 0);
ts.setPosition(mFGSurfaceControl, 0, 0);
ts.setCrop_legacy(mFGSurfaceControl, Rect(0, 0, 5, 5));
}
// NOTE: The foreground surface would be occluded by the child
// now, but is included in the stack because the child is
// transparent.
auto referenceFrame = mBaseFrame;
referenceFrame[FG_LAYER].mDisplayFrame = hwc_rect_t{0, 0, 0 + 5, 0 + 5};
referenceFrame[FG_LAYER].mSourceCrop = hwc_frect_t{0.f, 0.f, 5.f, 5.f};
referenceFrame[CHILD_LAYER].mDisplayFrame = hwc_rect_t{0, 0, 0 + 5, 0 + 5};
referenceFrame[CHILD_LAYER].mSourceCrop = hwc_frect_t{0.f, 0.f, 5.f, 5.f};
EXPECT_TRUE(framesAreSame(referenceFrame, sFakeComposer->getLatestFrame()));
}
TEST_F(ChildLayerTest, Constraints) {
{
TransactionScope ts(*sFakeComposer);
ts.show(mChild);
ts.setPosition(mFGSurfaceControl, 0, 0);
ts.setPosition(mChild, 63, 63);
}
auto referenceFrame = mBaseFrame;
referenceFrame[FG_LAYER].mDisplayFrame = hwc_rect_t{0, 0, 64, 64};
referenceFrame[CHILD_LAYER].mDisplayFrame = hwc_rect_t{63, 63, 64, 64};
referenceFrame[CHILD_LAYER].mSourceCrop = hwc_frect_t{0.f, 0.f, 1.f, 1.f};
EXPECT_TRUE(framesAreSame(referenceFrame, sFakeComposer->getLatestFrame()));
}
TEST_F(ChildLayerTest, Scaling) {
{
TransactionScope ts(*sFakeComposer);
ts.setPosition(mFGSurfaceControl, 0, 0);
}
auto referenceFrame = mBaseFrame;
referenceFrame[FG_LAYER].mDisplayFrame = hwc_rect_t{0, 0, 64, 64};
referenceFrame[CHILD_LAYER].mDisplayFrame = hwc_rect_t{0, 0, 10, 10};
EXPECT_TRUE(framesAreSame(referenceFrame, sFakeComposer->getLatestFrame()));
{
TransactionScope ts(*sFakeComposer);
ts.setMatrix(mFGSurfaceControl, 2.0, 0, 0, 2.0);
}
auto referenceFrame2 = mBaseFrame;
referenceFrame2[FG_LAYER].mDisplayFrame = hwc_rect_t{0, 0, 128, 128};
referenceFrame2[CHILD_LAYER].mDisplayFrame = hwc_rect_t{0, 0, 20, 20};
EXPECT_TRUE(framesAreSame(referenceFrame2, sFakeComposer->getLatestFrame()));
}
TEST_F(ChildLayerTest, LayerAlpha) {
{
TransactionScope ts(*sFakeComposer);
ts.show(mChild);
ts.setPosition(mChild, 0, 0);
ts.setPosition(mFGSurfaceControl, 0, 0);
ts.setAlpha(mChild, 0.5);
}
auto referenceFrame = mBaseFrame;
referenceFrame[FG_LAYER].mDisplayFrame = hwc_rect_t{0, 0, 64, 64};
referenceFrame[CHILD_LAYER].mDisplayFrame = hwc_rect_t{0, 0, 10, 10};
referenceFrame[CHILD_LAYER].mPlaneAlpha = 0.5f;
EXPECT_TRUE(framesAreSame(referenceFrame, sFakeComposer->getLatestFrame()));
{
TransactionScope ts(*sFakeComposer);
ts.setAlpha(mFGSurfaceControl, 0.5);
}
auto referenceFrame2 = referenceFrame;
referenceFrame2[FG_LAYER].mPlaneAlpha = 0.5f;
referenceFrame2[CHILD_LAYER].mPlaneAlpha = 0.25f;
EXPECT_TRUE(framesAreSame(referenceFrame2, sFakeComposer->getLatestFrame()));
}
TEST_F(ChildLayerTest, ReparentChildren) {
{
TransactionScope ts(*sFakeComposer);
ts.show(mChild);
ts.setPosition(mChild, 10, 10);
ts.setPosition(mFGSurfaceControl, 64, 64);
}
auto referenceFrame = mBaseFrame;
referenceFrame[FG_LAYER].mDisplayFrame = hwc_rect_t{64, 64, 64 + 64, 64 + 64};
referenceFrame[CHILD_LAYER].mDisplayFrame =
hwc_rect_t{64 + 10, 64 + 10, 64 + 10 + 10, 64 + 10 + 10};
EXPECT_TRUE(framesAreSame(referenceFrame, sFakeComposer->getLatestFrame()));
{
TransactionScope ts(*sFakeComposer);
ts.reparentChildren(mFGSurfaceControl, mBGSurfaceControl->getHandle());
}
auto referenceFrame2 = referenceFrame;
referenceFrame2[FG_LAYER].mDisplayFrame = hwc_rect_t{64, 64, 64 + 64, 64 + 64};
referenceFrame2[CHILD_LAYER].mDisplayFrame = hwc_rect_t{10, 10, 10 + 10, 10 + 10};
EXPECT_TRUE(framesAreSame(referenceFrame2, sFakeComposer->getLatestFrame()));
}
TEST_F(ChildLayerTest, DetachChildrenSameClient) {
{
TransactionScope ts(*sFakeComposer);
ts.show(mChild);
ts.setPosition(mChild, 10, 10);
ts.setPosition(mFGSurfaceControl, 64, 64);
}
auto referenceFrame = mBaseFrame;
referenceFrame[FG_LAYER].mDisplayFrame = hwc_rect_t{64, 64, 64 + 64, 64 + 64};
referenceFrame[CHILD_LAYER].mDisplayFrame =
hwc_rect_t{64 + 10, 64 + 10, 64 + 10 + 10, 64 + 10 + 10};
EXPECT_TRUE(framesAreSame(referenceFrame, sFakeComposer->getLatestFrame()));
{
TransactionScope ts(*sFakeComposer);
ts.setPosition(mFGSurfaceControl, 0, 0);
ts.detachChildren(mFGSurfaceControl);
}
{
TransactionScope ts(*sFakeComposer);
ts.setPosition(mFGSurfaceControl, 64, 64);
ts.hide(mChild);
}
std::vector<RenderState> refFrame(2);
refFrame[BG_LAYER] = mBaseFrame[BG_LAYER];
refFrame[FG_LAYER] = mBaseFrame[FG_LAYER];
EXPECT_TRUE(framesAreSame(refFrame, sFakeComposer->getLatestFrame()));
}
TEST_F(ChildLayerTest, DetachChildrenDifferentClient) {
sp<SurfaceComposerClient> newComposerClient = new SurfaceComposerClient;
sp<SurfaceControl> childNewClient =
newComposerClient->createSurface(String8("New Child Test Surface"), 10, 10,
PIXEL_FORMAT_RGBA_8888, 0, mFGSurfaceControl.get());
ASSERT_TRUE(childNewClient != nullptr);
ASSERT_TRUE(childNewClient->isValid());
fillSurfaceRGBA8(childNewClient, LIGHT_GRAY);
{
TransactionScope ts(*sFakeComposer);
ts.hide(mChild);
ts.show(childNewClient);
ts.setPosition(childNewClient, 10, 10);
ts.setPosition(mFGSurfaceControl, 64, 64);
}
auto referenceFrame = mBaseFrame;
referenceFrame[FG_LAYER].mDisplayFrame = hwc_rect_t{64, 64, 64 + 64, 64 + 64};
referenceFrame[CHILD_LAYER].mDisplayFrame =
hwc_rect_t{64 + 10, 64 + 10, 64 + 10 + 10, 64 + 10 + 10};
EXPECT_TRUE(framesAreSame(referenceFrame, sFakeComposer->getLatestFrame()));
{
TransactionScope ts(*sFakeComposer);
ts.detachChildren(mFGSurfaceControl);
ts.setPosition(mFGSurfaceControl, 0, 0);
}
{
TransactionScope ts(*sFakeComposer);
ts.setPosition(mFGSurfaceControl, 64, 64);
ts.setPosition(childNewClient, 0, 0);
ts.hide(childNewClient);
}
// Nothing should have changed. The child control becomes a no-op
// zombie on detach. See comments for detachChildren in the
// SurfaceControl.h file.
EXPECT_TRUE(framesAreSame(referenceFrame, sFakeComposer->getLatestFrame()));
}
TEST_F(ChildLayerTest, InheritNonTransformScalingFromParent) {
{
TransactionScope ts(*sFakeComposer);
ts.show(mChild);
ts.setPosition(mChild, 0, 0);
ts.setPosition(mFGSurfaceControl, 0, 0);
}
{
TransactionScope ts(*sFakeComposer);
ts.setOverrideScalingMode(mFGSurfaceControl, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
// We cause scaling by 2.
ts.setSize(mFGSurfaceControl, 128, 128);
}
auto referenceFrame = mBaseFrame;
referenceFrame[FG_LAYER].mDisplayFrame = hwc_rect_t{0, 0, 128, 128};
referenceFrame[FG_LAYER].mSourceCrop = hwc_frect_t{0.f, 0.f, 64.f, 64.f};
referenceFrame[CHILD_LAYER].mDisplayFrame = hwc_rect_t{0, 0, 20, 20};
referenceFrame[CHILD_LAYER].mSourceCrop = hwc_frect_t{0.f, 0.f, 10.f, 10.f};
EXPECT_TRUE(framesAreSame(referenceFrame, sFakeComposer->getLatestFrame()));
}
// Regression test for b/37673612
TEST_F(ChildLayerTest, ChildrenWithParentBufferTransform) {
{
TransactionScope ts(*sFakeComposer);
ts.show(mChild);
ts.setPosition(mChild, 0, 0);
ts.setPosition(mFGSurfaceControl, 0, 0);
}
// We set things up as in b/37673612 so that there is a mismatch between the buffer size and
// the WM specified state size.
{
TransactionScope ts(*sFakeComposer);
ts.setSize(mFGSurfaceControl, 128, 64);
}
sp<Surface> s = mFGSurfaceControl->getSurface();
auto anw = static_cast<ANativeWindow*>(s.get());
native_window_set_buffers_transform(anw, NATIVE_WINDOW_TRANSFORM_ROT_90);
native_window_set_buffers_dimensions(anw, 64, 128);
fillSurfaceRGBA8(mFGSurfaceControl, RED);
sFakeComposer->runVSyncAndWait();
// The child should still be in the same place and not have any strange scaling as in
// b/37673612.
auto referenceFrame = mBaseFrame;
referenceFrame[FG_LAYER].mDisplayFrame = hwc_rect_t{0, 0, 128, 64};
referenceFrame[FG_LAYER].mSourceCrop = hwc_frect_t{0.f, 0.f, 64.f, 128.f};
referenceFrame[FG_LAYER].mSwapCount++;
referenceFrame[CHILD_LAYER].mDisplayFrame = hwc_rect_t{0, 0, 10, 10};
EXPECT_TRUE(framesAreSame(referenceFrame, sFakeComposer->getLatestFrame()));
}
TEST_F(ChildLayerTest, Bug36858924) {
// Destroy the child layer
mChild.clear();
// Now recreate it as hidden
mChild = mComposerClient->createSurface(String8("Child surface"), 10, 10,
PIXEL_FORMAT_RGBA_8888, ISurfaceComposerClient::eHidden,
mFGSurfaceControl.get());
// Show the child layer in a deferred transaction
{
TransactionScope ts(*sFakeComposer);
ts.deferTransactionUntil_legacy(mChild, mFGSurfaceControl->getHandle(),
mFGSurfaceControl->getSurface()->getNextFrameNumber());
ts.show(mChild);
}
// Render the foreground surface a few times
//
// Prior to the bugfix for b/36858924, this would usually hang while trying to fill the third
// frame because SurfaceFlinger would never process the deferred transaction and would therefore
// never acquire/release the first buffer
ALOGI("Filling 1");
fillSurfaceRGBA8(mFGSurfaceControl, GREEN);
sFakeComposer->runVSyncAndWait();
ALOGI("Filling 2");
fillSurfaceRGBA8(mFGSurfaceControl, BLUE);
sFakeComposer->runVSyncAndWait();
ALOGI("Filling 3");
fillSurfaceRGBA8(mFGSurfaceControl, RED);
sFakeComposer->runVSyncAndWait();
ALOGI("Filling 4");
fillSurfaceRGBA8(mFGSurfaceControl, GREEN);
sFakeComposer->runVSyncAndWait();
}
class ChildColorLayerTest : public ChildLayerTest {
protected:
void SetUp() override {
TransactionTest::SetUp();
mChild = mComposerClient->createSurface(String8("Child surface"), 0, 0,
PIXEL_FORMAT_RGBA_8888,
ISurfaceComposerClient::eFXSurfaceColor,
mFGSurfaceControl.get());
{
TransactionScope ts(*sFakeComposer);
ts.setColor(mChild,
{LIGHT_GRAY.r / 255.0f, LIGHT_GRAY.g / 255.0f, LIGHT_GRAY.b / 255.0f});
ts.setCrop_legacy(mChild, Rect(0, 0, 10, 10));
}
sFakeComposer->runVSyncAndWait();
mBaseFrame.push_back(makeSimpleRect(64, 64, 64 + 10, 64 + 10));
mBaseFrame[CHILD_LAYER].mSourceCrop = hwc_frect_t{0.0f, 0.0f, 0.0f, 0.0f};
mBaseFrame[CHILD_LAYER].mSwapCount = 0;
ASSERT_EQ(2, sFakeComposer->getFrameCount());
ASSERT_TRUE(framesAreSame(mBaseFrame, sFakeComposer->getLatestFrame()));
}
};
TEST_F(ChildColorLayerTest, LayerAlpha) {
{
TransactionScope ts(*sFakeComposer);
ts.show(mChild);
ts.setPosition(mChild, 0, 0);
ts.setPosition(mFGSurfaceControl, 0, 0);
ts.setAlpha(mChild, 0.5);
}
auto referenceFrame = mBaseFrame;
referenceFrame[FG_LAYER].mDisplayFrame = hwc_rect_t{0, 0, 64, 64};
referenceFrame[CHILD_LAYER].mDisplayFrame = hwc_rect_t{0, 0, 10, 10};
referenceFrame[CHILD_LAYER].mPlaneAlpha = 0.5f;
EXPECT_TRUE(framesAreSame(referenceFrame, sFakeComposer->getLatestFrame()));
{
TransactionScope ts(*sFakeComposer);
ts.setAlpha(mFGSurfaceControl, 0.5);
}
auto referenceFrame2 = referenceFrame;
referenceFrame2[FG_LAYER].mPlaneAlpha = 0.5f;
referenceFrame2[CHILD_LAYER].mPlaneAlpha = 0.25f;
EXPECT_TRUE(framesAreSame(referenceFrame2, sFakeComposer->getLatestFrame()));
}
TEST_F(ChildColorLayerTest, LayerZeroAlpha) {
{
TransactionScope ts(*sFakeComposer);
ts.show(mChild);
ts.setPosition(mChild, 0, 0);
ts.setPosition(mFGSurfaceControl, 0, 0);
ts.setAlpha(mChild, 0.5);
}
auto referenceFrame = mBaseFrame;
referenceFrame[FG_LAYER].mDisplayFrame = hwc_rect_t{0, 0, 64, 64};
referenceFrame[CHILD_LAYER].mDisplayFrame = hwc_rect_t{0, 0, 10, 10};
referenceFrame[CHILD_LAYER].mPlaneAlpha = 0.5f;
EXPECT_TRUE(framesAreSame(referenceFrame, sFakeComposer->getLatestFrame()));
{
TransactionScope ts(*sFakeComposer);
ts.setAlpha(mFGSurfaceControl, 0.0f);
}
std::vector<RenderState> refFrame(1);
refFrame[BG_LAYER] = mBaseFrame[BG_LAYER];
EXPECT_TRUE(framesAreSame(refFrame, sFakeComposer->getLatestFrame()));
}
class LatchingTest : public TransactionTest {
protected:
void lockAndFillFGBuffer() { fillSurfaceRGBA8(mFGSurfaceControl, RED, false); }
void unlockFGBuffer() {
sp<Surface> s = mFGSurfaceControl->getSurface();
ASSERT_EQ(NO_ERROR, s->unlockAndPost());
sFakeComposer->runVSyncAndWait();
}
void completeFGResize() {
fillSurfaceRGBA8(mFGSurfaceControl, RED);
sFakeComposer->runVSyncAndWait();
}
void restoreInitialState() {
TransactionScope ts(*sFakeComposer);
ts.setSize(mFGSurfaceControl, 64, 64);
ts.setPosition(mFGSurfaceControl, 64, 64);
ts.setCrop_legacy(mFGSurfaceControl, Rect(0, 0, 64, 64));
}
};
TEST_F(LatchingTest, SurfacePositionLatching) {
// By default position can be updated even while
// a resize is pending.
{
TransactionScope ts(*sFakeComposer);
ts.setSize(mFGSurfaceControl, 32, 32);
ts.setPosition(mFGSurfaceControl, 100, 100);
}
// The size should not have updated as we have not provided a new buffer.
auto referenceFrame1 = mBaseFrame;
referenceFrame1[FG_LAYER].mDisplayFrame = hwc_rect_t{100, 100, 100 + 64, 100 + 64};
EXPECT_TRUE(framesAreSame(referenceFrame1, sFakeComposer->getLatestFrame()));
restoreInitialState();
// Now we repeat with setGeometryAppliesWithResize
// and verify the position DOESN'T latch.
{
TransactionScope ts(*sFakeComposer);
ts.setGeometryAppliesWithResize(mFGSurfaceControl);
ts.setSize(mFGSurfaceControl, 32, 32);
ts.setPosition(mFGSurfaceControl, 100, 100);
}
EXPECT_TRUE(framesAreSame(mBaseFrame, sFakeComposer->getLatestFrame()));
completeFGResize();
auto referenceFrame2 = mBaseFrame;
referenceFrame2[FG_LAYER].mDisplayFrame = hwc_rect_t{100, 100, 100 + 32, 100 + 32};
referenceFrame2[FG_LAYER].mSourceCrop = hwc_frect_t{0.f, 0.f, 32.f, 32.f};
referenceFrame2[FG_LAYER].mSwapCount++;
EXPECT_TRUE(framesAreSame(referenceFrame2, sFakeComposer->getLatestFrame()));
}
TEST_F(LatchingTest, CropLatching) {
// Normally the crop applies immediately even while a resize is pending.
{
TransactionScope ts(*sFakeComposer);
ts.setSize(mFGSurfaceControl, 128, 128);
ts.setCrop_legacy(mFGSurfaceControl, Rect(0, 0, 63, 63));
}
auto referenceFrame1 = mBaseFrame;
referenceFrame1[FG_LAYER].mDisplayFrame = hwc_rect_t{64, 64, 64 + 63, 64 + 63};
referenceFrame1[FG_LAYER].mSourceCrop = hwc_frect_t{0.f, 0.f, 63.f, 63.f};
EXPECT_TRUE(framesAreSame(referenceFrame1, sFakeComposer->getLatestFrame()));
restoreInitialState();
{
TransactionScope ts(*sFakeComposer);
ts.setSize(mFGSurfaceControl, 128, 128);
ts.setGeometryAppliesWithResize(mFGSurfaceControl);
ts.setCrop_legacy(mFGSurfaceControl, Rect(0, 0, 63, 63));
}
EXPECT_TRUE(framesAreSame(mBaseFrame, sFakeComposer->getLatestFrame()));
completeFGResize();
auto referenceFrame2 = mBaseFrame;
referenceFrame2[FG_LAYER].mDisplayFrame = hwc_rect_t{64, 64, 64 + 63, 64 + 63};
referenceFrame2[FG_LAYER].mSourceCrop = hwc_frect_t{0.f, 0.f, 63.f, 63.f};
referenceFrame2[FG_LAYER].mSwapCount++;
EXPECT_TRUE(framesAreSame(referenceFrame2, sFakeComposer->getLatestFrame()));
}
} // namespace
int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
sftest::FakeHwcEnvironment* fakeEnvironment = new sftest::FakeHwcEnvironment;
::testing::AddGlobalTestEnvironment(fakeEnvironment);
::testing::InitGoogleMock(&argc, argv);
return RUN_ALL_TESTS();
}
| 37.734577 | 100 | 0.675221 | dAck2cC2 |
f9e5a60f7a735128de1122dc680f61d875f676bf | 519 | cpp | C++ | Baekjoon/Problem_2566/Problem_2566.cpp | ShinYoung-hwan/Problem_Solving | 3f181b0b978ed22f1bbca102d41d45679cfb288f | [
"MIT"
] | null | null | null | Baekjoon/Problem_2566/Problem_2566.cpp | ShinYoung-hwan/Problem_Solving | 3f181b0b978ed22f1bbca102d41d45679cfb288f | [
"MIT"
] | null | null | null | Baekjoon/Problem_2566/Problem_2566.cpp | ShinYoung-hwan/Problem_Solving | 3f181b0b978ed22f1bbca102d41d45679cfb288f | [
"MIT"
] | null | null | null | #include <iostream>
#include <utility>
using namespace std;
/*
int main(void)
{
pair<int, int> p;
int Maxv = 0;
int matrix[9][9];
for(int i = 0; i < 9; i++)
{
for(int j = 0; j < 9; j++)
{
cin >> matrix[i][j];
if(matrix[i][j] > Maxv)
{
Maxv = matrix[i][j];
p.first = i + 1; p.second = j + 1;
}
}
}
cout << Maxv << endl;
cout << p.first << ' ' << p.second << endl;
return 0;
}
*/ | 18.535714 | 50 | 0.391137 | ShinYoung-hwan |
f9e7b6666e7721cd253c562107c7a71029b49ad3 | 2,789 | cpp | C++ | problem_105.cpp | Xinghui-Wu/LeetCode | 531d6a0bfa37ec4c729940f35a438c764e71e699 | [
"MIT"
] | null | null | null | problem_105.cpp | Xinghui-Wu/LeetCode | 531d6a0bfa37ec4c729940f35a438c764e71e699 | [
"MIT"
] | null | null | null | problem_105.cpp | Xinghui-Wu/LeetCode | 531d6a0bfa37ec4c729940f35a438c764e71e699 | [
"MIT"
] | null | null | null | /**
* 105. Construct Binary Tree from Preorder and Inorder Traversal
*
* Given two integer arrays preorder and inorder where preorder is the preorder traversal of a binary tree and inorder is the inorder traversal of the same tree, construct and return the binary tree.
*
* Constraints:
* 1 <= preorder.length <= 3000
* inorder.length == preorder.length
* -3000 <= preorder[i], inorder[i] <= 3000
* preorder and inorder consist of unique values.
* Each value of inorder also appears in preorder.
* preorder is guaranteed to be the preorder traversal of the tree.
* inorder is guaranteed to be the inorder traversal of the tree.
*
* Difficulty: Medium
* Related Topics: Array, Hash Table, Divide and Conquer, Tree, Binary Tree
*/
#include <iostream>
#include <vector>
#include <unordered_map>
#include "node.h"
using namespace std;
class Solution
{
private:
// Build a hashmap to record the relation of value and index for inorder.
unordered_map<int, size_t> inorder_index_map;
// Keep track of the element that will be used to construct the root.
int current_preorder;
public:
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder)
{
inorder_index_map.clear();
for (size_t i = 0; i < inorder.size(); i++)
{
inorder_index_map.insert({inorder[i], i});
}
current_preorder = 0;
TreeNode* root = build_subtree(preorder, 0, preorder.size() - 1);
return root;
}
/**
* To find the left and right subtrees, it will look for the root in inorder.
* Everything on the left should be the left subtree, and everything on the right should be the right subtree.
* Both subtrees can be constructed by making another recursion call.
* Always use the next element in preorder to initialize a root.
*/
TreeNode* build_subtree(vector<int>& preorder, int left, int right)
{
if (left > right)
{
return nullptr;
}
// Select the element indexed by current_preorder as the root.
TreeNode* root = new TreeNode(preorder[current_preorder++]);
// Locate the element indexed by current_preorder in inorder list.
int inorder_index = inorder_index_map[root->val];
// Recursively build the left and right subtrees.
root->left = build_subtree(preorder, left, inorder_index - 1);
root->right = build_subtree(preorder, inorder_index + 1, right);
return root;
}
};
int main()
{
vector<int> preorder = {3, 9, 20, 15, 7};
vector<int> inorder = {9, 3, 15, 20, 7};
Solution solution;
TreeNode* root = solution.buildTree(preorder, inorder);
output_level_order_traversal(root);
return 0;
}
| 30.315217 | 199 | 0.660452 | Xinghui-Wu |
f9eb6dde76294a6fed01b8ee185b4cd3d7d40988 | 20,516 | cpp | C++ | Server/Modules/InfoModule/src/InfoProcessor.cpp | wayfinder/Wayfinder-Server | a688546589f246ee12a8a167a568a9c4c4ef8151 | [
"BSD-3-Clause"
] | 4 | 2015-08-17T20:12:22.000Z | 2020-05-30T19:53:26.000Z | Server/Modules/InfoModule/src/InfoProcessor.cpp | wayfinder/Wayfinder-Server | a688546589f246ee12a8a167a568a9c4c4ef8151 | [
"BSD-3-Clause"
] | null | null | null | Server/Modules/InfoModule/src/InfoProcessor.cpp | wayfinder/Wayfinder-Server | a688546589f246ee12a8a167a568a9c4c4ef8151 | [
"BSD-3-Clause"
] | null | null | null | /*
Copyright (c) 1999 - 2010, Vodafone Group Services Ltd
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 Vodafone Group Services Ltd 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 "config.h"
#include "InfoProcessor.h"
#include "DisturbanceInfoPacket.h"
#include "DisturbanceList.h"
#include "GfxFeatureMap.h"
#include "MC2BoundingBox.h"
#include "MapSettings.h"
#include "MapUtility.h"
#include "UserRightsMapInfo.h"
#include "DeleteHelpers.h"
#include "InfoDatexUtils.h"
#include "IDTranslationTable.h"
#include "InfoSQL.h"
#include "GetTMCCoordinatePacket.h"
#include "DisturbancePacket.h"
#include "GfxFeatureMapPacket.h"
#include "RouteTrafficCostPacket.h"
#include "UpdateDisturbancePacket.h"
#include "DisturbanceChangesetPacket.h"
#include "FetchAllDisturbancesPacket.h"
#include "SQLTrafficElementDatabase.h"
#include "DisturbanceChangeset.h"
#include "BitUtility.h"
#include "TrafficMapInfo.h"
// TODO: remove
#include "TrafficSituationElement.h"
#define INFOP "[INFOP:" << __LINE__ << "] "
InfoProcessor::InfoProcessor( MapSafeVector* loadedMaps ):
MapHandlingProcessor( loadedMaps ),
m_database( new InfoSQL() ),
m_trafficDatabase( new SQLTrafficElementDatabase() )
{
if ( ! m_database->deleteOldDisturbances() ) {
mc2log << error
<< "[InfoProcessor] Deletion of old disturbances failed!" << endl;
}
}
InfoProcessor::~InfoProcessor() {
}
TrafficMapInfo*
InfoProcessor::getTrafficMapInfo( uint32 mapID ) {
map<uint32, TrafficMapInfo*>::iterator it;
it = m_handleUnitMap.find(mapID);
if( it != m_handleUnitMap.end() ) {
return it->second;
} else {
return NULL;
}
}
StringTable::stringCode
InfoProcessor::loadMap( uint32 mapID, uint32 &mapSize) {
TrafficMapInfo* foundUnit = getTrafficMapInfo(mapID);
if ( foundUnit != NULL ) {
mc2log << warn << "[InfoProcessor] map "
<< mapID << " already loaded" << endl;
return StringTable::ERROR_MAP_LOADED;
} else {
TrafficMapInfo* newUnit = new TrafficMapInfo( mapID );
// load from InfoSQL
bool status = newUnit->load( *m_database );
// Allready added to safevector outside the function
if ( status ) {
m_handleUnitMap.insert( make_pair( mapID, newUnit ) );
mapSize = newUnit->mapSize();
return StringTable::OK;
} else {
delete newUnit;
mapSize = 0;
return StringTable::NOTOK;
}
}
}
StringTable::stringCode
InfoProcessor::deleteMap(uint32 mapID)
{
TrafficMap::iterator tMap = m_handleUnitMap.find(mapID);
if(tMap != m_handleUnitMap.end()){
TrafficMapInfo* unit = tMap->second;
m_handleUnitMap.erase(tMap);
delete unit;
return StringTable::OK;
} else {
return StringTable::MAPNOTFOUND;
}
}
MC2String getDistText( const DisturbanceElement* dist,
StringTable::languageCode langCode ) {
// Here special tricks can be done to get a better string, especially
// if dist->getText() is empty.
MC2String text;
text = dist->getText();
mc2dbg4 << INFOP << "Disturbance text: " << text << endl;
return text;
}
inline GfxFeatureMapReplyPacket*
InfoProcessor::handleGfxFeatureMapRequest(const GfxFeatureMapRequestPacket* p,
char* packetInfo )
{
mc2dbg4 << "InfoProcessor::handleGfxFeatureMapRequest" << endl;
uint32 mapID = p->getMapID();
TrafficMapInfo* tu = getTrafficMapInfo( mapID );
if ( tu == NULL ) {
// ERROR - Maybe ackpack here instead?
GfxFeatureMapReplyPacket* reply = new GfxFeatureMapReplyPacket(p);
reply->setStatus(StringTable::MAPNOTFOUND);
return reply;
}
MC2BoundingBox bbox;
p->getMC2BoundingBox(&bbox);
ScreenSize screenSize = p->getScreenSize();
MapSettings mapSettings;
UserRightsMapInfo rights;
p->getMapSettingsAndRights( mapSettings, rights );
updateUserRights(rights);
// Set the boundingbox for the coordinates that will be included in
// the area
//
// Calculate the extra distance that shuold be added to each side
// of the bbox. The distance corresponds to approximately 30 pixels.
// FIXME: Add filtering.
// int filtScaleLevel = p->getFiltScaleLevel();
int minScaleLevel = p->getMinScaleLevel();
int maxScaleLevel = p->getMaxScaleLevel();
// Create and init map
GfxFeatureMap gfxFeatureMap;
gfxFeatureMap.setMC2BoundingBox(&bbox);
gfxFeatureMap.setScreenSize( screenSize );
gfxFeatureMap.setScaleLevel( maxScaleLevel );
const map<uint32, const DisturbanceElement*>& distList = tu->getDisturbanceList();
map<uint32, const DisturbanceElement*>::const_iterator it;
// FIXME: Add real IDTranslationTable. Not really needed since
// we never use 0x90000000 for drawing.
IDTranslationTable transTable;
mc2dbg4 << "[InfoP] maprights for user: \n" << rights << "\n[InfoP] distList: "
<< STLUtility::co_dump(distList, ",") << endl;
for(it = distList.begin(); it != distList.end(); ++it) {
// Check user rights
{
/// Get one node and check the provider id
const set<uint32>& nodeIDs = it->second->getNodeIDSet();
IDPair_t idToCheck( p->getMapID(), *( nodeIDs.begin() ) );
if ( ! rights.itemAllowed( it->second->getNeededRights(),
idToCheck,
transTable ) ) {
mc2dbg4 << "[InfoP] item " << (it->second) << " needs rights: "
<< it->second->getNeededRights() << endl;
// Not allowed - skip
continue;
}
}
// Only add disturbances if the we are at
// or a more detalied level (see MapUtility)
// Same constant is used in the GfxFeatureMapImageRequest
// to avoid sending packets.
if ( maxScaleLevel >= TRAFFIC_INFO_LEVEL ) {
const DisturbanceElement* dist = it->second;
MC2String distText = getDistText(
dist,
ItemTypes::getLanguageTypeAsLanguageCode( p->getLanguage() ) );
// create a new GfxTrafficInfoFeature this will in the end set the
// angle to 0...
GfxFeature* feature =
GfxFeature::createNewFeature( GfxFeature::TRAFFIC_INFO,
distText.c_str() );
GfxTrafficInfoFeature* trafficInfo =
static_cast<GfxTrafficInfoFeature*> (feature);
trafficInfo->setTrafficInfoType(dist->getType());
trafficInfo->setStartTime( dist->getStartTime() );
trafficInfo->setEndTime( dist->getEndTime() );
// setAngle?? its set to zero when created...
// what do we use the angle for?
// Add the single coordinate to the polygon.
feature->addNewPolygon(true, 1);
map<uint32, int32>::const_iterator it = dist->getLatMap().begin();
int32 latitude = it->second;
it = dist->getLonMap().begin();
int32 longitude = it->second;
feature->addCoordinateToLast(latitude, longitude);
feature->setScaleLevel(minScaleLevel);
// Check insideness
if ( bbox.contains( MC2Coordinate( latitude, longitude ) ) ) {
gfxFeatureMap.addFeature(feature);
} else {
delete feature;
}
}
}
// Create the reply
GfxFeatureMapReplyPacket* reply = new GfxFeatureMapReplyPacket(p);
DataBuffer buf(gfxFeatureMap.getMapSize());
gfxFeatureMap.save(&buf);
// Copied from GfxFeatureMapProcessor...
const uint32 EXTRALENGTH = 200;
if ( (gfxFeatureMap.getMapSize()+EXTRALENGTH) > reply->getBufSize()) {
reply->resize(gfxFeatureMap.getMapSize() +
REPLY_HEADER_SIZE + EXTRALENGTH);
}
reply->setGfxFeatureMapData(buf.getCurrentOffset(), &buf);
reply->setStatus( StringTable::OK );
{
// Add some info to the JT-printout (number of features added )
char tmpInfo[1024];
sprintf( tmpInfo, "f=%d", gfxFeatureMap.getNbrFeatures() );
strcat( packetInfo, tmpInfo );
}
return reply;
}
inline
DisturbanceReplyPacket*
InfoProcessor::handleDisturbanceRequest(const DisturbanceRequestPacket* p)
{
uint32 mapID = p->getRequestedMapID();
map<uint32, const DisturbanceElement*> distMap;
bool removeDisturbances = false;
TrafficMapInfo* currentUnit = getTrafficMapInfo(mapID);
if( currentUnit != NULL ) {
// Return all the disturbances
//currentUnit->getDisturbances(distMap, 0, MAX_UINT32);
distMap = currentUnit->getDisturbanceList();
}
return new DisturbanceReplyPacket(p,
distMap,
removeDisturbances);
}
inline
DisturbanceInfoReplyPacket*
InfoProcessor::handleDisturbanceInfoRequest(const DisturbanceInfoRequestPacket* p)
{
mc2dbg4 << "InfoProcessor: Processing DisturbanceInfoRequestPacket"
<< endl;
DisturbanceInfoReplyPacket* replyPacket =
new DisturbanceInfoReplyPacket(p);
UserRightsMapInfo userRights;
p->getRights(userRights);
updateUserRights(userRights);
set<uint32> mapIDs;
multimap<uint32, uint32> nodeMap;
uint32 nbrNodes = p->getNumberOfNodes();
for(uint32 i = 0; i < nbrNodes; i++) {
IDPair_t idPair = p->getMapAndNode(i);
uint32 mapID = idPair.first;
uint32 nodeID = idPair.second;
mapIDs.insert(mapID);
nodeMap.insert(pair<uint32,uint32>(mapID,nodeID));
}
set<uint32>::iterator mi;
multimap<uint32, uint32>::iterator ni;
multimap<uint32, uint32>::iterator lower;
multimap<uint32, uint32>::iterator upper;
for(mi = mapIDs.begin(); mi != mapIDs.end(); ++mi) {
uint32 mapID = *mi;
lower = nodeMap.lower_bound(mapID);
upper = nodeMap.upper_bound(mapID);
set<uint32> nodeIDs;
for( ni = lower; ni != upper; ++ni) {
uint32 nodeID = ni->second;
nodeIDs.insert(nodeID);
}
TrafficMapInfo* thu = getTrafficMapInfo(mapID);
if ( thu != NULL ) {
TrafficMapInfo::NodeIDsToDisturbances distElems =
thu->findNodeID( nodeIDs, userRights );
TrafficMapInfo::NodeIDsToDisturbances::iterator it;
for( it = distElems.begin(); it != distElems.end(); it++) {
// Add disturbance to packet
TrafficMapInfo::NodeIDsToDisturbances::value_type thePair = *it;
TrafficMapInfo::NodeIDsToDisturbances::value_type::second_type
distElem = thePair.second;
replyPacket->addDisturbance( mapID,
thePair.first,
distElem->getType(),
distElem->getDisturbanceID(),
distElem->getText() );
}
} else {
mc2dbg << "InfoProcessor: TrafficMapInfo == NULL!"
<< ", map " << mapID <<endl;
}
}
return replyPacket;
}
inline
RouteTrafficCostReplyPacket*
InfoProcessor::
handleRouteTrafficCostRequest( const RouteTrafficCostRequestPacket* rtcrp,
char* packetInfo )
{
TrafficMapInfo::NodesWithDelays vect;
// FIXME: Fill that vector with disturbances.
uint32 mapID = rtcrp->getMapID();
TrafficMapInfo* thu = getTrafficMapInfo(mapID);
int nodeCounter = 0;
if( thu != NULL ) {
UserRightsMapInfo rights;
rtcrp->getRights(rights);
mc2dbg2 << "[IP]: Packet rights " << rights << endl;
updateUserRights(rights);
nodeCounter = thu->getNodesWithDelays(rights, vect);
{
// Add some info to the JT-printout
char tmpInfo[1024];
sprintf( tmpInfo, "n=%d", nodeCounter );
strcat( packetInfo, tmpInfo );
}
} else {
return new RouteTrafficCostReplyPacket( rtcrp,
StringTable::MAPNOTFOUND,
vect );
}
mc2dbg2 << "added costs to " << nodeCounter
<< " nodes on map " << mapID << "." << endl;
return new RouteTrafficCostReplyPacket( rtcrp,
StringTable::OK,
vect );
}
GetTMCCoordinateReplyPacket*
InfoProcessor::
handleGetTmcCoordRequest( const GetTMCCoordinateRequestPacket& gtcrp )
{
TrafficSituationElement::CoordCont firstCoords;
TrafficSituationElement::CoordCont secondCoords;
MC2String firstLocation;
MC2String secondLocation;
int32 extent;
TrafficDataTypes::direction direction;
gtcrp.getPoints( firstLocation, secondLocation, extent, direction );
const bool ok = m_database->getTMCCoords( firstLocation, secondLocation,
extent, direction,
firstCoords, secondCoords );
mc2dbg << INFOP << "Fetching TMC '" << firstLocation << "' and '"
<< secondLocation << "' with extent " << extent << " and direction "
<< direction << " gave " << firstCoords.size() << "("
<< secondCoords.size() << ") coordinates" << endl;
GetTMCCoordinateReplyPacket* answer = NULL;
if ( ok ) {
const uint32 size = ( firstCoords.size() + secondCoords.size() ) * 8;
answer = new GetTMCCoordinateReplyPacket(>crp, StringTable::OK, size);
answer->addCoordinatesToPacket(firstCoords, secondCoords);
} else {
answer = new GetTMCCoordinateReplyPacket(>crp, StringTable::NOTOK, 0);
}
return answer;
}
void InfoProcessor::
updateTrafficUnits( DisturbanceChangeset& changes ) {
uint32 mapID = MAX_UINT32;
if ( ! changes.getUpdateSet().empty() ) {
mapID = changes.getUpdateSet().front()->getMapID();
} else if ( ! changes.getRemoveSet().empty() ) {
mapID = changes.getRemoveSet().front()->getMapID();
} else {
// nothing we can do without map id
return;
}
TrafficMapInfo* unit = getTrafficMapInfo( mapID );
if ( unit == NULL ) {
// If the map was not loaded, then just ignore traffic unit update.
// The unit will be loaded next time it is needed.
return;
}
// send the updated and removed set to the unit,
// the unit will take ownership of the updated disturbances but not
// the removed disturbances.
DisturbanceChangeset::Elements updated;
changes.swapUpdateSet( updated );
unit->updateDisturbances( updated, changes.getRemoveSet() );
}
DisturbanceChangesetReplyPacket*
InfoProcessor::
handleDisturbanceChangesetRequest( const DisturbanceChangesetRequestPacket&
packet ) {
// get changset from packet and update the database
DisturbanceChangeset changes;
packet.getChangeset( changes );
int status = m_trafficDatabase->updateChangeset( changes );
// get separate status bits
using BitUtility::getBit;
bool updateStat = getBit( (uint32)status,
TrafficElementDatabase::UPDATE_FAILED );
bool removeStat = getBit( (uint32)status,
TrafficElementDatabase::REMOVE_FAILED );
// if we updated the database, we also need to update traffic handler units
// that were affected.
if ( status == TrafficElementDatabase::OK ) {
// Find and reload any traffic units for each map that was affected,
// so they get the new data.
updateTrafficUnits( changes );
} else if ( updateStat && ! removeStat ) {
// only update traffic units for updated elements.
DisturbanceChangeset::Elements empty;
DisturbanceChangeset::Elements updates;
changes.swapUpdateSet( updates );
DisturbanceChangeset updateChanges( updates, empty );
updateTrafficUnits( updateChanges );
} else if ( ! updateStat && removeStat ) {
// only update traffic units for removed elements.
DisturbanceChangeset::Elements empty;
DisturbanceChangeset::Elements removed;
changes.swapRemoveSet( removed );
DisturbanceChangeset removeChanges( empty, removed );
updateTrafficUnits( removeChanges );
}
return new DisturbanceChangesetReplyPacket( &packet,
updateStat, removeStat );
}
FetchAllDisturbancesReplyPacket*
InfoProcessor::
handleFetchAllDisturbances( const FetchAllDisturbancesRequestPacket& pack ) {
TrafficElementDatabase::TrafficElements disturbances;
bool ok = m_trafficDatabase->fetchAllDisturbances( pack.getProviderID(),
disturbances );
FetchAllDisturbancesReplyPacket* reply =
new FetchAllDisturbancesReplyPacket( &pack, disturbances );
if ( ! ok ) {
reply->setStatus( StringTable::NOTOK );
} else {
reply->setStatus( StringTable::OK );
}
return reply;
}
Packet*
InfoProcessor::handleRequestPacket( const RequestPacket& pack,
char* packetInfo )
{
uint16 subType = pack.getSubType();
mc2dbg2 << "InfoProcessor recieved packet with subtype = "
<< subType << endl;
Packet* answerPacket = NULL;
switch (subType) {
case Packet::PACKETTYPE_GETTMCCOORREQUEST : {
answerPacket = handleGetTmcCoordRequest(
static_cast<const GetTMCCoordinateRequestPacket&>( pack ) );
}
break;
case Packet::PACKETTYPE_GFXFEATUREMAPREQUEST: {
answerPacket =
handleGfxFeatureMapRequest(
static_cast<const GfxFeatureMapRequestPacket*>(&pack), packetInfo );
break;
}
case Packet::PACKETTYPE_DISTURBANCEREQUEST:
{
answerPacket =
handleDisturbanceRequest(
static_cast<const DisturbanceRequestPacket*>(&pack));
break;
}
case Packet::PACKETTYPE_DISTURBANCEINFOREQUEST:
{
answerPacket =
handleDisturbanceInfoRequest(
static_cast<const DisturbanceInfoRequestPacket*>(&pack));
break;
}
case Packet::PACKETTYPE_ROUTETRAFFICCOSTREQUEST: {
answerPacket = handleRouteTrafficCostRequest(
static_cast<const RouteTrafficCostRequestPacket*>(&pack), packetInfo );
}
break;
case Packet::PACKETTYPE_FETCH_ALL_DISTURBANCES_REQUEST:
answerPacket =
handleFetchAllDisturbances( static_cast
<const FetchAllDisturbancesRequestPacket&>( pack ) );
break;
case Packet::PACKETTYPE_DISTURBANCE_CHANGESET_REQUEST:
answerPacket =
handleDisturbanceChangesetRequest( static_cast
< const DisturbanceChangesetRequestPacket& >( pack ) );
break;
default : {
mc2log << warn << "InfoProcessor: Packet with subtype = " <<
(uint32) subType << " not supported."
<< endl;
}
break;
}
return (answerPacket);
}
int
InfoProcessor::getCurrentStatus()
{
return (1);
}
void
InfoProcessor::updateUserRights(UserRightsMapInfo& userRights)
{
userRights.filterAllRights();
}
| 33.522876 | 755 | 0.645155 | wayfinder |
f9ec0f6e56600ed22249c204b1a057766ca2955a | 19,323 | cc | C++ | src/cymoca/compiler.cc | jgoppert/cymoca | 45a991f56a397a7fea3429eacad6f33dfbf5a6d4 | [
"BSD-3-Clause"
] | 6 | 2018-06-24T17:49:33.000Z | 2020-06-13T20:43:20.000Z | src/cymoca/compiler.cc | jgoppert/cymoca | 45a991f56a397a7fea3429eacad6f33dfbf5a6d4 | [
"BSD-3-Clause"
] | 3 | 2018-07-01T10:15:00.000Z | 2018-07-09T21:35:18.000Z | src/cymoca/compiler.cc | jgoppert/cymoca | 45a991f56a397a7fea3429eacad6f33dfbf5a6d4 | [
"BSD-3-Clause"
] | 1 | 2018-07-01T10:10:31.000Z | 2018-07-01T10:10:31.000Z | #include "compiler.h"
namespace cymoca {
Compiler::Compiler(std::ifstream &text)
: ModelicaBaseListener(),
m_parser(nullptr),
m_input(text),
m_lexer(&m_input),
m_token_stream(&m_lexer),
m_root(nullptr),
m_verbose(false),
m_ast() {
m_token_stream.fill();
m_parser = std::make_unique<ModelicaParser>(&m_token_stream);
antlr4::tree::ParseTree *tree = m_parser->stored_definition();
antlr4::tree::ParseTreeWalker::DEFAULT.walk(this, tree);
}
std::string Compiler::indent(int n) {
std::string s;
for (int i = 0; i < n; i++) {
s.append(" ");
}
return s;
}
void Compiler::visitTerminal(antlr4::tree::TerminalNode *node) {
if (m_verbose) {
std::cout << "terminal: " << node->getText() << std::endl;
}
}
void Compiler::visitErrorNode(antlr4::tree::ErrorNode * /*node*/) {}
void Compiler::enterEveryRule(antlr4::ParserRuleContext *ctx) {
if (m_verbose) {
std::cout << indent(ctx->depth()) << ">> "
<< m_parser->getRuleNames()[ctx->getRuleIndex()] << std::endl;
}
}
void Compiler::exitEveryRule(antlr4::ParserRuleContext *ctx) {
if (m_verbose) {
std::cout << indent(ctx->depth()) << "<< "
<< m_parser->getRuleNames()[ctx->getRuleIndex()] << std::endl;
}
}
//-----------------------------------------------------------------------------
// model
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// condition
//-----------------------------------------------------------------------------
void Compiler::exitCond_bool(ModelicaParser::Cond_boolContext *ctx) {
auto res = std::make_unique<ast::condition::Boolean>(false);
if (ctx->TRUE()) {
res->setValue(true);
} else if (ctx->FALSE()) {
res->setValue(false);
} else {
assert(false);
}
setAst(ctx, std::move(res));
}
void Compiler::exitCond_binary(ModelicaParser::Cond_binaryContext *ctx) {
std::string op = ctx->op->getText();
auto left = cloneAst<ast::condition::Base>(ctx->condition(0));
auto right = cloneAst<ast::condition::Base>(ctx->condition(1));
if (op == "and") {
setAst(ctx, std::make_unique<ast::condition::And>(std::move(left),
std::move(right)));
} else if (op == "or") {
setAst(ctx, std::make_unique<ast::condition::Or>(std::move(left),
std::move(right)));
} else {
assert(false);
}
}
void Compiler::exitCond_unary(ModelicaParser::Cond_unaryContext *ctx) {
assert(ctx->op->getText() == "-");
auto e = cloneAst<ast::condition::Base>(ctx->condition());
setAst(ctx, std::make_unique<ast::condition::Not>(std::move(e)));
}
void Compiler::exitCond_compare(ModelicaParser::Cond_compareContext *ctx) {
auto left = cloneAst<ast::expression::Base>(ctx->expr(0));
auto right = cloneAst<ast::expression::Base>(ctx->expr(1));
std::string op = ctx->op->getText();
if (op == "<") {
setAst(ctx, std::make_unique<ast::condition::LessThan>(std::move(left),
std::move(right)));
} else if (op == "<=") {
setAst(ctx, std::make_unique<ast::condition::LessThanOrEqual>(
std::move(left), std::move(right)));
} else if (op == ">") {
setAst(ctx, std::make_unique<ast::condition::GreaterThan>(
std::move(left), std::move(right)));
} else if (op == ">=") {
setAst(ctx, std::make_unique<ast::condition::GreaterThanOrEqual>(
std::move(left), std::move(right)));
} else if (op == "==") {
setAst(ctx, std::make_unique<ast::condition::Equal>(std::move(left),
std::move(right)));
} else if (op == "<>") {
setAst(ctx, std::make_unique<ast::condition::NotEqual>(std::move(left),
std::move(right)));
} else {
throw compiler_exception(std::string("unhandled operator") + op);
}
}
void Compiler::exitCond_func(ModelicaParser::Cond_funcContext *ctx) {
throw compiler_exception("not implemented");
}
void Compiler::exitCond_ref(ModelicaParser::Cond_refContext *ctx) {
throw compiler_exception("not implemented");
}
//-----------------------------------------------------------------------------
// equations
//-----------------------------------------------------------------------------
void Compiler::exitEq_simple(ModelicaParser::Eq_simpleContext *ctx) {
auto left = cloneAst<ast::expression::Base>(ctx->expr());
auto right = cloneAst<ast::expression::Base>(ctx->expression());
setAst(ctx, std::make_unique<ast::equation::Simple>(std::move(left),
std::move(right)));
}
void Compiler::exitEq_block(ModelicaParser::Eq_blockContext *ctx) {
auto res = std::make_unique<ast::equation::List>();
for (auto eq : ctx->equation()) {
res->append(cloneAst<ast::equation::Base>(eq));
}
setAst(ctx, std::move(res));
}
void Compiler::exitEq_if(ModelicaParser::Eq_ifContext *ctx) {
throw compiler_exception("not implemented");
}
void Compiler::exitEq_for(ModelicaParser::Eq_forContext *ctx) {
throw compiler_exception("not implemented");
}
void Compiler::exitEq_connect(ModelicaParser::Eq_connectContext *ctx) {
throw compiler_exception("not implemented");
}
void Compiler::exitEq_when(ModelicaParser::Eq_whenContext *ctx) {
assert(ctx->condition().size() == ctx->eq_block().size());
auto when = std::make_unique<ast::equation::When>();
for (size_t i = 0; i < ctx->condition().size(); i++) {
auto block = std::make_unique<ast::equation::Block>(
cloneAst<ast::condition::Base>(ctx->condition(i)),
cloneAst<ast::equation::List>(ctx->eq_block(i)));
when->append(std::move(block));
}
setAst(ctx, std::move(when));
}
void Compiler::exitEq_func(ModelicaParser::Eq_funcContext *ctx) {
throw compiler_exception("not implemented");
}
//-----------------------------------------------------------------------------
// statements
//-----------------------------------------------------------------------------
void Compiler::exitStmt_ref(ModelicaParser::Stmt_refContext *ctx) {
throw compiler_exception("not implemented");
}
void Compiler::exitStmt_func(ModelicaParser::Stmt_funcContext *ctx) {
throw compiler_exception("not implemented");
}
void Compiler::exitStmt_key(ModelicaParser::Stmt_keyContext *ctx) {
throw compiler_exception("not implemented");
}
void Compiler::exitStmt_if(ModelicaParser::Stmt_ifContext *ctx) {
throw compiler_exception("not implemented");
}
void Compiler::exitStmt_for(ModelicaParser::Stmt_forContext *ctx) {
throw compiler_exception("not implemented");
}
void Compiler::exitStmt_while(ModelicaParser::Stmt_whileContext *ctx) {
throw compiler_exception("not implemented");
}
void Compiler::exitStmt_when(ModelicaParser::Stmt_whenContext *ctx) {
throw compiler_exception("not implemented");
}
void Compiler::exitFor_indices(ModelicaParser::For_indicesContext *ctx) {
throw compiler_exception("not implemented");
}
void Compiler::exitFor_index(ModelicaParser::For_indexContext *ctx) {
throw compiler_exception("not implemented");
}
//-----------------------------------------------------------------------------
// expressions
//-----------------------------------------------------------------------------
void Compiler::exitExpr_number(ModelicaParser::Expr_numberContext *ctx) {
std::stringstream ss(ctx->getText());
double value = 0;
ss >> value;
auto num = std::make_unique<ast::expression::Number>(value);
setAst(ctx, std::move(num));
}
void Compiler::exitExpr_ref(ModelicaParser::Expr_refContext *ctx) {
std::vector<std::string> ids;
for (auto id : ctx->component_reference()->IDENT()) {
ids.push_back(id->getText());
}
// TODO handle more than one string
setAst(ctx, std::make_unique<ast::expression::Reference>(ids[0]));
}
void Compiler::exitExpr_simple(ModelicaParser::Expr_simpleContext *ctx) {
linkAst(ctx, ctx->expr());
}
void Compiler::exitExpr_if(ModelicaParser::Expr_ifContext *ctx) {
throw compiler_exception("not implemented");
}
void Compiler::exitExpr_func(ModelicaParser::Expr_funcContext *ctx) {
if (ctx->component_reference()) {
setAst(ctx,
std::make_unique<ast::expression::Function>(
cloneAst<ast::expression::Reference>(ctx->component_reference()),
cloneAst<ast::expression::List>(ctx->function_call_args())));
} else if (ctx->func) {
setAst(
ctx,
std::make_unique<ast::expression::Function>(
std::make_unique<ast::expression::Reference>(ctx->func->getText()),
cloneAst<ast::expression::List>(ctx->function_call_args())));
} else {
assert(false);
}
}
void Compiler::exitExpr_string(ModelicaParser::Expr_stringContext *ctx) {
throw compiler_exception("not implemented");
}
void Compiler::exitExpr_range(ModelicaParser::Expr_rangeContext *ctx) {
throw compiler_exception("not implemented");
}
void Compiler::exitExpr_unary(ModelicaParser::Expr_unaryContext *ctx) {
setAst(ctx, std::make_unique<ast::expression::Negative>(
cloneAst<ast::expression::Base>(ctx->expr())));
}
void Compiler::exitExpr_binary(ModelicaParser::Expr_binaryContext *ctx) {
throw compiler_exception("not implemented");
}
void Compiler::exitExpr_output(ModelicaParser::Expr_outputContext *ctx) {
throw compiler_exception("not implemented");
}
void Compiler::exitExpr_list(ModelicaParser::Expr_listContext *ctx) {
throw compiler_exception("not implemented");
}
void Compiler::exitExpr_end(ModelicaParser::Expr_endContext *ctx) {
throw compiler_exception("not implemented");
}
void Compiler::exitExpr_array(ModelicaParser::Expr_arrayContext *ctx) {
throw compiler_exception("not implemented");
}
//-----------------------------------------------------------------------------
// function arguments
//-----------------------------------------------------------------------------
void Compiler::exitFunction_call_args(
ModelicaParser::Function_call_argsContext *ctx) {
auto args = std::make_unique<ast::expression::List>();
for (auto arg_ctx : ctx->function_argument()) {
args->append(cloneAst<ast::expression::Base>(arg_ctx));
}
setAst(ctx, std::move(args));
}
void Compiler::exitFunc_arg_expr(ModelicaParser::Func_arg_exprContext *ctx) {
setAst(ctx, cloneAst<ast::expression::Base>(ctx->expression()));
}
void Compiler::exitFunc_arg_for(ModelicaParser::Func_arg_forContext *ctx) {
throw compiler_exception("not implemented");
}
void Compiler::exitFunc_arg_func(ModelicaParser::Func_arg_funcContext *ctx) {
throw compiler_exception("not implemented");
}
void Compiler::exitFunc_arg_named(ModelicaParser::Func_arg_namedContext *ctx) {
throw compiler_exception("not implemented");
}
//-----------------------------------------------------------------------------
// elements
//-----------------------------------------------------------------------------
void Compiler::exitElem_import(ModelicaParser::Elem_importContext *ctx) {
throw compiler_exception("not implemented");
}
void Compiler::exitElem_extends(ModelicaParser::Elem_extendsContext *ctx) {
throw compiler_exception("not implemented");
}
void Compiler::exitElem_class(ModelicaParser::Elem_classContext *ctx) {
throw compiler_exception("not implemented");
}
void Compiler::exitElem_comp(ModelicaParser::Elem_compContext *ctx) {
linkAst(ctx, ctx->component_clause());
}
//-----------------------------------------------------------------------------
// misc
//-----------------------------------------------------------------------------
void Compiler::exitClass_prefixes(ModelicaParser::Class_prefixesContext *ctx) {
// pass, just a string, let level above handle this
}
void Compiler::exitStored_definition(
ModelicaParser::Stored_definitionContext *ctx) {
// throw compiler_exception("not implemented");
// TODO
}
void Compiler::exitEnumeration_literal(
ModelicaParser::Enumeration_literalContext *ctx) {
throw compiler_exception("not implemented");
}
void Compiler::exitComposition(ModelicaParser::CompositionContext *ctx) {
auto c = std::make_unique<ast::model::Class>(
std::make_unique<ast::model::ElementDict>(),
std::make_unique<ast::equation::List>());
// elements
enum class Visibility { PUBLIC, PRIVATE, PROTECTED };
for (auto elem_sect :
{std::make_pair(Visibility::PUBLIC, ctx->public_elem),
std::make_pair(Visibility::PRIVATE, ctx->private_elem),
std::make_pair(Visibility::PROTECTED, ctx->protected_elem)}) {
for (auto e_ctx : elem_sect.second) {
// TODO set visibility for element
auto edict = getAst<ast::model::ElementDict>(e_ctx);
for (auto &key_val : edict->getMap()) {
auto e = key_val.second->cloneAs<ast::element::Base>();
c->getElements().set(key_val.first, std::move(e));
}
}
}
// equations
for (auto eq_sec : ctx->equation_section()) {
for (auto eq : eq_sec->equation()) {
c->getEquations().append(cloneAst<ast::equation::Base>(eq));
}
}
// statements
for (auto algo_sec : ctx->algorithm_section()) {
for (auto s_ctx : algo_sec->statement()) {
auto s = cloneAst<ast::statement::Base>(s_ctx);
c->getStatements().append(std::move(s));
}
}
m_root = c.get();
setAst(ctx, std::move(c));
}
void Compiler::exitExternal_function_call(
ModelicaParser::External_function_callContext *ctx) {
throw compiler_exception("not implemented");
}
void Compiler::exitConstraining_clause(
ModelicaParser::Constraining_clauseContext *ctx) {
throw compiler_exception("not implemented");
}
void Compiler::exitComponent_clause(
ModelicaParser::Component_clauseContext *ctx) {
// TODO handle multi-level names
auto elements = std::make_unique<ast::model::ElementDict>();
auto type = ctx->type_specifier()->getText();
auto prefix_str = ctx->type_prefix()->getText();
ast::element::Prefix prefix;
if (prefix_str == "parameter") {
prefix = ast::element::Prefix::PARAMETER;
} else if (prefix_str == "constant") {
prefix = ast::element::Prefix::CONSTANT;
} else if (prefix_str == "discrete") {
prefix = ast::element::Prefix::DISCRETE;
} else if (prefix_str == "") {
prefix = ast::element::Prefix::VARIABLE;
} else {
throw compiler_exception("unhandled type prefix " + type);
}
for (auto d : ctx->component_declaration()) {
std::string name = d->IDENT()->getText();
elements->set(
name, std::make_unique<ast::element::Component>(name, type, prefix));
}
setAst(ctx, std::move(elements));
}
void Compiler::exitType_prefix(ModelicaParser::Type_prefixContext *ctx) {
// pass, just text, let level above handle this
}
void Compiler::exitComponent_declaration(
ModelicaParser::Component_declarationContext *ctx) {
// pass, handle in component_clause
}
void Compiler::exitClass_modification(
ModelicaParser::Class_modificationContext *ctx) {
throw compiler_exception("not implemented");
}
void Compiler::exitStmt_block(ModelicaParser::Stmt_blockContext *ctx) {
throw compiler_exception("not implemented");
}
void Compiler::exitEquation_section(
ModelicaParser::Equation_sectionContext *ctx) {
auto eqs = std::make_unique<ast::equation::List>();
for (auto eq : ctx->equation()) {
eqs->append(cloneAst<ast::equation::Base>(eq));
}
setAst(ctx, std::move(eqs));
}
void Compiler::exitAlgorithm_section(
ModelicaParser::Algorithm_sectionContext *ctx) {
throw compiler_exception("not implemented");
}
void Compiler::exitType_specifier(ModelicaParser::Type_specifierContext *ctx) {
// pass, just strings, let level above handle this
}
void Compiler::exitName(ModelicaParser::NameContext *ctx) {
throw compiler_exception("not implemented");
}
void Compiler::exitComponent_reference(
ModelicaParser::Component_referenceContext *ctx) {
// TODO, split names
setAst(ctx, std::make_unique<ast::expression::Reference>(ctx->getText()));
}
void Compiler::exitArray_arg_expr(ModelicaParser::Array_arg_exprContext *ctx) {
throw compiler_exception("not implemented");
}
void Compiler::exitArray_arg_for(ModelicaParser::Array_arg_forContext *ctx) {
throw compiler_exception("not implemented");
}
void Compiler::exitArray_arguments(
ModelicaParser::Array_argumentsContext *ctx) {
throw compiler_exception("not implemented");
}
void Compiler::exitNamed_arguments(
ModelicaParser::Named_argumentsContext *ctx) {
throw compiler_exception("not implemented");
}
void Compiler::exitNamed_argument(ModelicaParser::Named_argumentContext *ctx) {
throw compiler_exception("not implemented");
}
void Compiler::exitOutput_expression_list(
ModelicaParser::Output_expression_listContext *ctx) {
throw compiler_exception("not implemented");
}
void Compiler::exitExpression_list(
ModelicaParser::Expression_listContext *ctx) {
throw compiler_exception("not implemented");
}
void Compiler::exitArray_subscripts(
ModelicaParser::Array_subscriptsContext *ctx) {
throw compiler_exception("not implemented");
}
void Compiler::exitSubscript(ModelicaParser::SubscriptContext *ctx) {
throw compiler_exception("not implemented");
}
void Compiler::exitComment(ModelicaParser::CommentContext *ctx) {
throw compiler_exception("not implemented");
}
void Compiler::exitString_comment(ModelicaParser::String_commentContext *ctx) {
throw compiler_exception("not implemented");
}
void Compiler::exitAnnotation(ModelicaParser::AnnotationContext *ctx) {
throw compiler_exception("not implemented");
}
void Compiler::exitClass_def_long(ModelicaParser::Class_def_longContext *ctx) {
// TODO
// throw compiler_exception("not implemented");
}
void Compiler::exitClass_def_der(ModelicaParser::Class_def_derContext *ctx) {
throw compiler_exception("not implemented");
}
void Compiler::exitClass_def_short(
ModelicaParser::Class_def_shortContext *ctxt) {
throw compiler_exception("not implemented");
}
void Compiler::exitClass_def_type(ModelicaParser::Class_def_typeContext *ctxt) {
throw compiler_exception("not implemented");
}
void Compiler::exitClass_def_enum(ModelicaParser::Class_def_enumContext *ctxt) {
throw compiler_exception("not implemented");
}
void Compiler::exitArg_modification(
ModelicaParser::Arg_modificationContext *ctxt) {
throw compiler_exception("not implemented");
}
void Compiler::exitArg_redeclare_class(
ModelicaParser::Arg_redeclare_classContext *ctxt) {
throw compiler_exception("not implemented");
}
void Compiler::exitArg_redeclare_element(
ModelicaParser::Arg_redeclare_elementContext *ctxt) {
throw compiler_exception("not implemented");
}
void Compiler::exitModification_class(
ModelicaParser::Modification_classContext *ctx) {
throw compiler_exception("not implemented");
}
void Compiler::exitModification_equation(
ModelicaParser::Modification_equationContext *ctx) {
auto e = cloneAst<ast::expression::Base>(ctx->expression());
// TODO
}
void Compiler::exitModification_statement(
ModelicaParser::Modification_statementContext *ctx) {
auto e = cloneAst<ast::expression::Base>(ctx->expression());
// throw compiler_exception("not implemented");
}
} // namespace cymoca
| 36.946463 | 80 | 0.657921 | jgoppert |
f9ed1a6ff70fbe1cad9b750ec3fc6ced9712456a | 1,633 | cpp | C++ | console/PhraseManager.cpp | mwgit00/cpox | 9c3a1e1f7c8b077cd2b52aa8af2eb88fc260229c | [
"MIT"
] | null | null | null | console/PhraseManager.cpp | mwgit00/cpox | 9c3a1e1f7c8b077cd2b52aa8af2eb88fc260229c | [
"MIT"
] | null | null | null | console/PhraseManager.cpp | mwgit00/cpox | 9c3a1e1f7c8b077cd2b52aa8af2eb88fc260229c | [
"MIT"
] | null | null | null | #include <fstream>
#include <sstream>
#include <iostream>
#include <opencv2/core/core.hpp>
#include "PhraseManager.h"
PhraseManager::PhraseManager() :
default_phrase({ "this is a test", "" }),
phrases(),
next_phrase_index(0)
{
}
PhraseManager::~PhraseManager()
{
}
bool PhraseManager::load(const std::string& rs)
{
bool result = false;
cv::FileStorage fs;
fs.open(rs, cv::FileStorage::READ);
if (fs.isOpened())
{
cv::FileNode n;
n = fs["phrases"];
if (n.isSeq())
{
cv::FileNodeIterator iter;
for (iter = n.begin(); iter != n.end(); iter++)
{
cv::FileNode& rnn = *iter;
phrases.push_back(T_phrase_info({ rnn["text"], rnn["wav"] }));
}
// sanity check
result = true;
for (const auto& r : phrases)
{
if (!r.text.length())
{
result = false;
break;
}
}
}
}
next_phrase_index = 0;
return result;
}
const PhraseManager::T_phrase_info& PhraseManager::next_phrase(void)
{
if (phrases.size())
{
int n = next_phrase_index;
if (false)
{
// random for next time
///@TODO -- add support for a random mode
}
else
{
// in sequence from file
next_phrase_index = (next_phrase_index + 1) % phrases.size();
}
return phrases[n];
}
else
{
return default_phrase;
}
}
| 19.211765 | 78 | 0.478261 | mwgit00 |
f9ef68b3f4a152704f40152de6f699cbe5575b07 | 726 | hpp | C++ | include/fcppt/detail/strong_typedef/assignment_operator.hpp | vinzenz/fcppt | 3f8cc5babdee178a9bbd06ca3ce7ad405d19aa6a | [
"BSL-1.0"
] | null | null | null | include/fcppt/detail/strong_typedef/assignment_operator.hpp | vinzenz/fcppt | 3f8cc5babdee178a9bbd06ca3ce7ad405d19aa6a | [
"BSL-1.0"
] | null | null | null | include/fcppt/detail/strong_typedef/assignment_operator.hpp | vinzenz/fcppt | 3f8cc5babdee178a9bbd06ca3ce7ad405d19aa6a | [
"BSL-1.0"
] | null | null | null | // Copyright Carl Philipp Reh 2009 - 2016.
// 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 FCPPT_DETAIL_STRONG_TYPEDEF_ASSIGNMENT_OPERATOR_HPP_INCLUDED
#define FCPPT_DETAIL_STRONG_TYPEDEF_ASSIGNMENT_OPERATOR_HPP_INCLUDED
#define FCPPT_DETAIL_STRONG_TYPEDEF_ASSIGNMENT_OPERATOR(\
op\
) \
template< \
typename T,\
typename Tag\
> \
fcppt::strong_typedef< \
T, \
Tag \
> & \
operator op( \
fcppt::strong_typedef< \
T, \
Tag \
> &_left, \
fcppt::strong_typedef< \
T, \
Tag \
> const &_right \
) \
{ \
_left.value_ \
op \
_right.get(); \
\
return \
_left; \
}
#endif
| 17.707317 | 68 | 0.684573 | vinzenz |
f9f330b47249d3ddf405e16784aa1468cc151bfa | 1,339 | cc | C++ | client/components/ui/about_dialog.cc | zamorajavi/google-input-tools | fc9f11d80d957560f7accf85a5fc27dd23625f70 | [
"Apache-2.0"
] | 175 | 2015-01-01T12:40:33.000Z | 2019-05-24T22:33:59.000Z | client/components/ui/about_dialog.cc | zamorajavi/google-input-tools | fc9f11d80d957560f7accf85a5fc27dd23625f70 | [
"Apache-2.0"
] | 11 | 2015-01-19T16:30:56.000Z | 2018-04-25T01:06:52.000Z | client/components/ui/about_dialog.cc | zamorajavi/google-input-tools | fc9f11d80d957560f7accf85a5fc27dd23625f70 | [
"Apache-2.0"
] | 97 | 2015-01-19T15:35:29.000Z | 2019-05-15T05:48:02.000Z | /*
Copyright 2014 Google 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 <atlbase.h>
#include <atlwin.h>
#include "components/ui/about_dialog.h"
#include "base/logging.h"
#include "components/ui/skin_ui_component_utils.h"
#include "resources/about_dialog_resource.h"
namespace ime_goopy {
namespace components {
LRESULT AboutDialog::OnInitDialog(UINT msg, WPARAM wparam, LPARAM lparam,
BOOL& handled) {
// Reinforce the focus to stay in the popup dialog, as some applications
// like PaoPaoTang will make the popup to lose focus.
SetFocus();
return 0;
}
LRESULT AboutDialog::OnClose(WORD nofity, WORD id, HWND hwnd, BOOL& handled) {
bool checked = IsDlgButtonChecked(IDC_CHECK_USER_METRICS);
EndDialog(id);
return 0;
}
} // namespace components
} // namespace ime_goopy
| 31.880952 | 78 | 0.737117 | zamorajavi |
f9f3d2a2b250479d5d0ce89f366ed1fa5d9c6245 | 672 | hpp | C++ | include/RED4ext/Types/generated/ink/SingleDrawMetric.hpp | Cyberpunk-Extended-Development-Team/RED4ext.SDK | 2dc828c761d87a1b4235ce9ca4fbdf9fb4312fae | [
"MIT"
] | 1 | 2021-02-01T23:07:50.000Z | 2021-02-01T23:07:50.000Z | include/RED4ext/Types/generated/ink/SingleDrawMetric.hpp | Cyberpunk-Extended-Development-Team/RED4ext.SDK | 2dc828c761d87a1b4235ce9ca4fbdf9fb4312fae | [
"MIT"
] | null | null | null | include/RED4ext/Types/generated/ink/SingleDrawMetric.hpp | Cyberpunk-Extended-Development-Team/RED4ext.SDK | 2dc828c761d87a1b4235ce9ca4fbdf9fb4312fae | [
"MIT"
] | null | null | null | #pragma once
// This file is generated from the Game's Reflection data
#include <cstdint>
#include <RED4ext/Common.hpp>
#include <RED4ext/REDhash.hpp>
#include <RED4ext/DynArray.hpp>
#include <RED4ext/Types/generated/Vector2.hpp>
namespace RED4ext
{
namespace ink {
struct SingleDrawMetric
{
static constexpr const char* NAME = "inkSingleDrawMetric";
static constexpr const char* ALIAS = NAME;
bool exeedsLimit; // 00
uint8_t unk01[0x4 - 0x1]; // 1
Vector2 hierarchySize; // 04
uint8_t unk0C[0x10 - 0xC]; // C
DynArray<uint32_t> usedTextures; // 10
};
RED4EXT_ASSERT_SIZE(SingleDrawMetric, 0x20);
} // namespace ink
} // namespace RED4ext
| 24 | 62 | 0.720238 | Cyberpunk-Extended-Development-Team |
f9f9a222a14c52510d075523aa03d36299b01e98 | 853 | cpp | C++ | CodeChef/Easy/LEBOMBS.cpp | ritwik1503/Competitive-Coding-1 | ffefe5f8b299c623af1ef01bf024af339401de0b | [
"MIT"
] | 29 | 2016-09-02T04:48:59.000Z | 2016-09-08T18:13:05.000Z | CodeChef/Easy/LEBOMBS.cpp | ritwik1503/Competitive-Coding-1 | ffefe5f8b299c623af1ef01bf024af339401de0b | [
"MIT"
] | 2 | 2016-09-02T05:20:02.000Z | 2016-10-13T06:31:31.000Z | CodeChef/Easy/LEBOMBS.cpp | ritwik1503/Competitive-Coding-1 | ffefe5f8b299c623af1ef01bf024af339401de0b | [
"MIT"
] | 7 | 2017-04-01T20:07:03.000Z | 2020-10-16T12:28:54.000Z | #include "bits/stdc++.h"
using namespace std;
# define s(n) scanf("%d",&n)
# define sc(n) scanf("%c",&n)
# define sl(n) scanf("%lld",&n)
# define sf(n) scanf("%lf",&n)
# define ss(n) scanf("%s",n)
# define INF (int)1e9
# define EPS 1e-9
# define MOD 1000000007
typedef long long ll;
int main()
{
int t;
cin >> t;
while(t--){
int n;
s(n);
int a[n];
for(int i=0;i<n;i++)
scanf("%1d",&a[i]);
if(n==1)
if(a[0]==0)
printf("1\n");
else
printf("0\n");
else
{
int count=0;
if(a[0]==0 && a[1]==0)
count++;
if(a[n-1]==0 && a[n-2]==0)
count++;
for(int i=1;i<n-1;i++){
if(a[i-1]==0 && a[i]==0 && a[i+1]==0)
count++;
}
printf("%d\n",count );
}
}
return 0;
}
| 17.06 | 53 | 0.410317 | ritwik1503 |
f9f9d16de2b711be2cd02a3f67e4759abeabb55f | 561 | hh | C++ | Sources/AGEngine/Render/Textures/PixelTypesFormats.hh | Another-Game-Engine/AGE | d5d9e98235198fe580a43007914f515437635830 | [
"MIT"
] | 47 | 2015-03-29T09:44:25.000Z | 2020-11-30T10:05:56.000Z | Sources/AGEngine/Render/Textures/PixelTypesFormats.hh | Another-Game-Engine/AGE | d5d9e98235198fe580a43007914f515437635830 | [
"MIT"
] | 313 | 2015-01-01T18:16:30.000Z | 2015-11-30T07:54:07.000Z | Sources/AGEngine/Render/Textures/PixelTypesFormats.hh | Another-Game-Engine/AGE | d5d9e98235198fe580a43007914f515437635830 | [
"MIT"
] | 9 | 2015-06-07T13:21:54.000Z | 2020-08-25T09:50:07.000Z | #pragma once
# include <Utils/OpenGL.hh>
# include <unordered_map>
struct PixelType
{
public:
size_t size;
public:
PixelType() :
size(0)
{
}
PixelType(size_t size) :
size(size)
{
}
PixelType(PixelType const ©) :
size(copy.size)
{
}
PixelType(PixelType &&move) :
size(move.size)
{
}
};
std::unordered_map<GLenum, PixelType> available_type_pixel =
{
{ GL_UNSIGNED_BYTE, PixelType(1) },
{ GL_UNSIGNED_INT, PixelType(4) },
{ GL_UNSIGNED_SHORT, PixelType(2) },
{ GL_UNSIGNED_INT_24_8, PixelType(4) },
{ GL_FLOAT, PixelType(4) }
}; | 14.384615 | 60 | 0.673797 | Another-Game-Engine |
f9ffd4f894110e546edada31d6a467ef6443e7f9 | 953 | cpp | C++ | test/source/controllers/serial_test.cpp | kremi151/FunkyBoy | d70ea8724b2ca22c5af31305b7e4b09d5caa203f | [
"Apache-2.0"
] | 2 | 2020-08-17T20:48:01.000Z | 2020-10-04T15:02:11.000Z | test/source/controllers/serial_test.cpp | kremi151/FunkyBoy | d70ea8724b2ca22c5af31305b7e4b09d5caa203f | [
"Apache-2.0"
] | 34 | 2020-07-25T17:10:24.000Z | 2022-03-22T17:41:29.000Z | test/source/controllers/serial_test.cpp | kremi151/FunkyBoy | d70ea8724b2ca22c5af31305b7e4b09d5caa203f | [
"Apache-2.0"
] | null | null | null | /**
* Copyright 2020 Michel Kremer (kremi151)
*
* 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 "serial_test.h"
using namespace FunkyBoy::Controller;
void SerialControllerTest::sendByte(FunkyBoy::u8 data) {
std::cout << data;
for (u8 i = 1 ; i < FB_TEST_SERIAL_CONTROLLER_LWORD_SIZE ; i++) {
lastWord[i - 1] = lastWord[i];
}
lastWord[FB_TEST_SERIAL_CONTROLLER_LWORD_SIZE - 1] = data;
}
| 32.862069 | 75 | 0.718783 | kremi151 |
e6013180dcfd4783f0ec756ec1979cc001bb67b0 | 2,540 | cpp | C++ | Tempest/ui/controls/dialog.cpp | enotio/Tempest | 1a7105cfca3669d54c696ad8188f04f25159c0a0 | [
"MIT"
] | 5 | 2017-05-31T21:25:57.000Z | 2020-01-14T14:11:41.000Z | Tempest/ui/controls/dialog.cpp | enotio/Tempest | 1a7105cfca3669d54c696ad8188f04f25159c0a0 | [
"MIT"
] | 2 | 2017-11-13T14:32:21.000Z | 2018-10-03T17:07:36.000Z | Tempest/ui/controls/dialog.cpp | enotio/Tempest | 1a7105cfca3669d54c696ad8188f04f25159c0a0 | [
"MIT"
] | 2 | 2018-01-31T14:06:58.000Z | 2018-10-02T11:46:34.000Z | #include "dialog.h"
#include <Tempest/SystemAPI>
#include <Tempest/Window>
#include <Tempest/Layout>
#include <Tempest/Application>
using namespace Tempest;
struct Dialog::LayShadow : Tempest::Layout {
void applyLayout(){
for(Widget* w:widgets()){
Point pos = w->pos();
if(w->x()+w->w()>owner()->w())
pos.x = owner()->w()-w->w();
if(w->y()+w->h()>owner()->h())
pos.y = owner()->h()-w->h();
if(pos.x<=0)
pos.x = 0;
if(pos.y<=0)
pos.y = 0;
w->setPosition(pos);
}
}
};
struct Dialog::Overlay : public Tempest::WindowOverlay {
bool isModal = true;
Dialog * dlg = nullptr;
void mouseDownEvent(MouseEvent& e){
e.accept();
}
void mouseMoveEvent(MouseEvent& e){
e.accept();
}
void mouseWheelEvent(MouseEvent& e){
e.accept();
}
void paintEvent(PaintEvent& e){
dlg->paintShadow(e);
paintNested(e);
}
void keyDownEvent(Tempest::KeyEvent& e){
dlg->keyDownEvent(e);
e.accept();
}
void keyUpEvent(Tempest::KeyEvent& e){
dlg->keyUpEvent(e);
e.accept();
}
void gestureEvent(Tempest::AbstractGestureEvent &e) {
e.accept();
}
};
Dialog::Dialog() : owner_ov(nullptr) {
resize(300,200);
setDragable(1);
}
Dialog::~Dialog() {
close();
}
int Dialog::exec() {
if(!owner_ov){
owner_ov = new Overlay();
owner_ov->dlg = this;
T_ASSERT( SystemAPI::instance().addOverlay( owner_ov )!=0 );
owner_ov->setLayout( new LayShadow() );
owner_ov->layout().add( this );
}
setVisible(true);
setPosition( (owner_ov->w()-w())/2,
(owner_ov->h()-h())/2 );
while( owner_ov && !Application::isQuit() ) {
Application::processEvents();
}
return 0;
}
void Dialog::close() {
if( owner_ov ){
Tempest::WindowOverlay* ov = owner_ov;
owner_ov = 0;
setVisible(0);
CloseEvent e;
this->closeEvent(e);
ov->layout().take(this);
ov->deleteLater();
}
}
void Dialog::setModal(bool m) {
if(owner_ov)
owner_ov->isModal = m;
}
bool Dialog::isModal() const {
return owner_ov ? owner_ov->isModal : false;
}
void Dialog::closeEvent( CloseEvent & e ) {
if(!owner_ov)
e.ignore(); else
close();
}
void Dialog::keyDownEvent(KeyEvent &e) {
if(e.key==KeyEvent::K_ESCAPE)
close();
}
void Dialog::paintShadow(PaintEvent &e) {
if(!owner_ov)
return;
Painter p(e);
p.setBlendMode(alphaBlend);
p.setColor(0,0,0,0.5);
p.drawRect(0,0,owner_ov->w(),owner_ov->h());
}
| 18.676471 | 64 | 0.583071 | enotio |
e601af42c7968e56411ca1a9afbc905c6b1658c8 | 1,485 | cpp | C++ | src/DataWriter/LocalFile.cpp | NIMML/ENISI-MSM | 1faf7a6b7f67e1a1eb05afd7ae45abb470d17ba4 | [
"Apache-2.0"
] | 2 | 2017-01-23T15:33:07.000Z | 2017-01-23T17:51:24.000Z | src/DataWriter/LocalFile.cpp | NIMML/ENISI-MSM | 1faf7a6b7f67e1a1eb05afd7ae45abb470d17ba4 | [
"Apache-2.0"
] | null | null | null | src/DataWriter/LocalFile.cpp | NIMML/ENISI-MSM | 1faf7a6b7f67e1a1eb05afd7ae45abb470d17ba4 | [
"Apache-2.0"
] | 2 | 2016-12-09T18:44:46.000Z | 2017-08-30T00:02:15.000Z | /*
* LocalFile.cpp
*
* Created on: Apr 8, 2016
* Author: shoops
*/
#include "LocalFile.h"
#include "repast_hpc/RepastProcess.h"
#include "grid/Properties.h"
#include <sstream>
using namespace ENISI;
// static
std::map< std::string, LocalFile * > LocalFile::INSTANCES;
// static
std::ofstream & LocalFile::debug()
{
return LocalFile::instance("", "log")->stream();
}
// static
LocalFile * LocalFile::instance(const std::string & name,
const std::string extension)
{
std::map< std::string, LocalFile * >::iterator found = INSTANCES.find(name);
if (found == INSTANCES.end())
{
found = INSTANCES.insert(std::make_pair(name, new LocalFile(name, extension))).first;
}
return found->second;
}
// static
void LocalFile::close()
{
std::map< std::string, LocalFile * >::iterator it = INSTANCES.begin();
std::map< std::string, LocalFile * >::iterator end = INSTANCES.end();
for (; it != end; ++it)
{
delete it->second;
}
}
LocalFile::LocalFile(const std::string & name, const std::string extension):
mOstream()
{
std::string config;
Properties::instance(Properties::model)->getValue("config", config);
std::stringstream Name;
Name << config << "/" << name << "_" << repast::RepastProcess::instance()->rank() << "." << extension;
mOstream.open(Name.str().c_str());
}
// virtual
LocalFile::~LocalFile()
{
mOstream.close();
}
std::ofstream & LocalFile::stream()
{
return mOstream;
}
| 20.342466 | 104 | 0.63165 | NIMML |
e6043b61083693edbce8bb0af6929e97e3dee1d4 | 15,611 | cc | C++ | problems/ObsDrivingModel/ObsDrivingModel.cc | ppnathan/HMSHS | ae65c7622cf4b10d710722084d73a2ad8636bc9e | [
"Apache-2.0"
] | null | null | null | problems/ObsDrivingModel/ObsDrivingModel.cc | ppnathan/HMSHS | ae65c7622cf4b10d710722084d73a2ad8636bc9e | [
"Apache-2.0"
] | null | null | null | problems/ObsDrivingModel/ObsDrivingModel.cc | ppnathan/HMSHS | ae65c7622cf4b10d710722084d73a2ad8636bc9e | [
"Apache-2.0"
] | null | null | null | #include "ObsDrivingModel.h"
#include "Utilities.h"
#include <cmath>
#include <cstdlib>
#include <random>
#include <iostream>
#include <array>
using namespace std;
const double Discount_ObsDrMdl = 0.95;
const int NumCStateVar_ObsDrMdl = 2; // number of continuous state variables
const int NumDState_ObsDrMdl = 8; //number of discrete states
const int NumCObsVar_ObsDrMdl = 2; // number of continuous observation variables
const int NumDObs_ObsDrMdl = 3; //number of discrete observations
const int NumDControls_ObsDrMdl = 4; // number of discrete controls
enum { ASC0 = 0, ASC1 = 1, ATC0 = 2, ATC1 = 3, DSC0 = 4, DSC1 = 5, DTC0 = 6, DTC1 = 7}; // q: AC0:(Attentive, Controller 0); AC1:(Attentive, Controller 1); DC0:(Distracted, Controller 0); DC1:(Distracted, Controller 1);
//(q>>2: 0=Attentive or 1=Distracted), (q & 0x02: 0=Straight or 1=Turn), (q & 0x01: 0 = C0 or 1 = C1)
enum {V00 = 0, V01 = 1, V10 = 2, V11 = 3}; // sigma: V00:(Reminder off, Execute C0); V01:(Reminder off, Execute C1); V10:(Reminder on, Execute C0); V11:(Reminder on, Execute C1);
//((sigma>>1): 0 = Reminder off or 1 = Reminder on; (sigma & 0x01): 0 = Controller0 or 1 = Controller1)
ObsDrivingModel::ObsDrivingModel():Model(NumCStateVar_ObsDrMdl, NumDState_ObsDrMdl,NumCObsVar_ObsDrMdl, NumDObs_ObsDrMdl, NumDControls_ObsDrMdl, Discount_ObsDrMdl),
deltaT(1),noisemean(0), AttStraightNoiseStdDev(0.0361), AttTurnNoiseStdDev(0.0539), DisStraightNoiseStdDev(0.0548),
DisTurnNoiseStdDev(0.0678), AttCarDistNoiseStdDev(0.2555), DisCarDistNoiseStdDev(0.2337), AttTurnConst(0.0117),
DisTurnConst(0.0065), AttRelSpd(-0.1767), DisRelSpd(-0.2012), c(0.25)
{
double rewardcoefficient[NumDControls_ObsDrMdl][6] = {{0, 0, 0, 0, 1, 0}, //0 + 0x +0x^2 + 0xy + 0y + y^2
{0, 0, 0, 0, 1, -0.01},
{0, 0, 0, 0, 1, -0.01},
{0, 0, 0, 0, 1, -0.02} };
double attentiverewardcoefficient[NumDControls_ObsDrMdl][6] = {{15, 0, 0, 0, 1, 0}, //0 + 0x +0x^2 + 0xy + 0y + y^2
{15, 0, 0, 0, 1, -0.02},
{15, 0, 0, 0, 1, -0.02},
{15, 0, 0, 0, 1, -0.04} };
vector<vector<double> > tmpvector(NumDState_ObsDrMdl, vector<double>(6, 0));
for(int i =0; i<NumDControls_ObsDrMdl; i++){
for(int j =0; j<NumDState_ObsDrMdl; j++) {
for(int k =0; k<6; k++){
if(j>>2 == 0)
tmpvector[j][k] = attentiverewardcoefficient[i][k];
else
tmpvector[j][k] = rewardcoefficient[i][k];
}
}
RewardCoeff.push_back(tmpvector);
}
};
DState ObsDrivingModel::sampleDState(const DState& q, const DControl& sigma) const{
array<double,8> init = {this->getDStateTransProb(ASC0, q, sigma), this->getDStateTransProb(ASC1, q, sigma),
this->getDStateTransProb(ATC0, q, sigma), this->getDStateTransProb(ATC1, q, sigma),
this->getDStateTransProb(DSC0, q, sigma), this->getDStateTransProb(DSC1, q, sigma),
this->getDStateTransProb(DTC0, q, sigma), this->getDStateTransProb(DTC1, q, sigma) };
discrete_distribution<int> distribution(init.begin(), init.end());
return distribution(generator);
};
CState ObsDrivingModel::sampleCState(const DState& q_next, const CState& x_k) const {
normal_distribution<double> attStraightNormalRand(this->noisemean, this->AttStraightNoiseStdDev);
normal_distribution<double> attTurnNormalRand(this->noisemean, this->AttTurnNoiseStdDev);
normal_distribution<double> disStraightNormalRand(this->noisemean, this->DisStraightNoiseStdDev);
normal_distribution<double> disTurnNormalRand(this->noisemean, this->DisTurnNoiseStdDev);
normal_distribution<double> attCarDistNormalRand(this->noisemean, this->AttCarDistNoiseStdDev);
normal_distribution<double> disCarDistNormalRand(this->noisemean, this->DisCarDistNoiseStdDev);
double attStraightNoise = attStraightNormalRand(generator);
double attTurnNoise = attTurnNormalRand(generator);
double disStraightNoise = disStraightNormalRand(generator);
double disTurnNoise = disTurnNormalRand(generator);
double attCarDistNoise = attCarDistNormalRand(generator);
double disCarDistNoise = disCarDistNormalRand(generator);
CState x_next;
switch(q_next){
case ASC0:
x_next.push_back(x_k[0] + attStraightNoise);
x_next.push_back(x_k[1] + AttRelSpd + attCarDistNoise);
break;
case ASC1:
x_next.push_back(x_k[0] + attStraightNoise);
x_next.push_back(x_k[1] + AttRelSpd + c + attCarDistNoise);
break;
case ATC0:
x_next.push_back(x_k[0] + AttTurnConst + attTurnNoise);
x_next.push_back(x_k[1] + AttRelSpd + attCarDistNoise);
break;
case ATC1:
x_next.push_back(x_k[0] + AttTurnConst + attTurnNoise);
x_next.push_back(x_k[1] + AttRelSpd + c + attCarDistNoise);
break;
case DSC0:
x_next.push_back(x_k[0] + disStraightNoise);
x_next.push_back(x_k[1] + DisRelSpd + disCarDistNoise);
break;
case DSC1:
x_next.push_back(x_k[0] + disStraightNoise);
x_next.push_back(x_k[1] + DisRelSpd + c + disCarDistNoise);
break;
case DTC0:
x_next.push_back(x_k[0] + DisTurnConst + disTurnNoise);
x_next.push_back(x_k[1] + DisRelSpd + disCarDistNoise);
break;
case DTC1:
x_next.push_back(x_k[0] + DisTurnConst + disTurnNoise);
x_next.push_back(x_k[1] + DisRelSpd + c + disCarDistNoise);
break;
default:
printf("q_next out of domain\n");
exit(1);
}
return x_next;
};
DObs ObsDrivingModel::sampleDObs(const DState& q_next) const {
double ObsProb[3][2] = { {0.7617, 0.0145},
{0.2225, 0.42},
{0.0158, 0.5655} };
array<double,3> init = {ObsProb[1][q_next>>2], ObsProb[2][q_next>>2], ObsProb[3][q_next>>2]};
discrete_distribution<int> distribution(init.begin(), init.end());
return distribution(generator);
// bernoulli_distribution bernlRand(1 - this->obserr);
// if(bernlRand(generator))
// return q_next>>1;
// else
// return ((q_next>>1) == 0)? 1:0;
};
double ObsDrivingModel::getCStateTransProb(CState const& x_next, DState const& q_next, CState const& x_k) const {
double difference[2];
double p1, p2;
switch(q_next){
case ASC0:
difference[0] = x_next[0] - x_k[0];
difference[1] = x_next[1] - x_k[1] - AttRelSpd;
p1 = 1.0/(AttStraightNoiseStdDev*sqrt(2*PI))*exp(-0.5*(difference[0]-noisemean)*(difference[0]-noisemean)/(AttStraightNoiseStdDev*AttStraightNoiseStdDev));
p2 = 1.0/(AttCarDistNoiseStdDev*sqrt(2*PI))*exp(-0.5*(difference[1]-noisemean)*(difference[1]-noisemean)/(AttCarDistNoiseStdDev*AttCarDistNoiseStdDev));
return p1*p2;
case ASC1:
difference[0] = x_next[0] - x_k[0];
difference[1] = x_next[1] -x_k[1] - AttRelSpd - c;
p1 = 1.0/(AttStraightNoiseStdDev*sqrt(2*PI))*exp(-0.5*(difference[0]-noisemean)*(difference[0]-noisemean)/(AttStraightNoiseStdDev*AttStraightNoiseStdDev));
p2 = 1.0/(AttCarDistNoiseStdDev*sqrt(2*PI))*exp(-0.5*(difference[1]-noisemean)*(difference[1]-noisemean)/(AttCarDistNoiseStdDev*AttCarDistNoiseStdDev));
return p1*p2;
case ATC0:
difference[0] = x_next[0] - x_k[0] - AttTurnConst;
difference[1] = x_next[1] - x_k[1] - AttRelSpd;
p1 = 1.0/(AttTurnNoiseStdDev*sqrt(2*PI))*exp(-0.5*(difference[0]-noisemean)*(difference[0]-noisemean)/(AttTurnNoiseStdDev*AttTurnNoiseStdDev));
p2 = 1.0/(AttCarDistNoiseStdDev*sqrt(2*PI))*exp(-0.5*(difference[1]-noisemean)*(difference[1]-noisemean)/(AttCarDistNoiseStdDev*AttCarDistNoiseStdDev));
return p1*p2;
case ATC1:
difference[0] = x_next[0] - x_k[0] - AttTurnConst;
difference[1] = x_next[1] - x_k[1] - AttRelSpd - c;
p1 = 1.0/(AttTurnNoiseStdDev*sqrt(2*PI))*exp(-0.5*(difference[0]-noisemean)*(difference[0]-noisemean)/(AttTurnNoiseStdDev*AttTurnNoiseStdDev));
p2 = 1.0/(AttCarDistNoiseStdDev*sqrt(2*PI))*exp(-0.5*(difference[1]-noisemean)*(difference[1]-noisemean)/(AttCarDistNoiseStdDev*AttCarDistNoiseStdDev));
return p1*p2;
case DSC0:
difference[0] = x_next[0] - x_k[0];
difference[1] = x_next[1] - x_k[1] - DisRelSpd;
p1 = 1.0/(DisStraightNoiseStdDev*sqrt(2*PI))*exp(-0.5*(difference[0]-noisemean)*(difference[0]-noisemean)/(DisStraightNoiseStdDev*DisStraightNoiseStdDev));
p2 = 1.0/(DisCarDistNoiseStdDev*sqrt(2*PI))*exp(-0.5*(difference[1]-noisemean)*(difference[1]-noisemean)/(DisCarDistNoiseStdDev*DisCarDistNoiseStdDev));
return p1*p2;
case DSC1:
difference[0] = x_next[0] -x_k[0];
difference[1] = x_next[1] -x_k[1]- DisRelSpd -c;
p1 = 1.0/(DisStraightNoiseStdDev*sqrt(2*PI))*exp(-0.5*(difference[0]-noisemean)*(difference[0]-noisemean)/(DisStraightNoiseStdDev*DisStraightNoiseStdDev));
p2 = 1.0/(DisCarDistNoiseStdDev*sqrt(2*PI))*exp(-0.5*(difference[1]-noisemean)*(difference[1]-noisemean)/(DisCarDistNoiseStdDev*DisCarDistNoiseStdDev));
return p1*p2;
case DTC0:
difference[0] = x_next[0] - x_k[0] - DisTurnConst;
difference[1] = x_next[1] - x_k[1] - DisRelSpd;
p1 = 1.0/(DisTurnNoiseStdDev*sqrt(2*PI))*exp(-0.5*(difference[0]-noisemean)*(difference[0]-noisemean)/(DisTurnNoiseStdDev*DisTurnNoiseStdDev));
p2 = 1.0/(DisCarDistNoiseStdDev*sqrt(2*PI))*exp(-0.5*(difference[1]-noisemean)*(difference[1]-noisemean)/(DisCarDistNoiseStdDev*DisCarDistNoiseStdDev));
return p1*p2;
case DTC1:
difference[0] = x_next[0] - x_k[0] - DisTurnConst;
difference[1] = x_next[1] - x_k[1] - DisRelSpd - c;
p1 = 1.0/(DisTurnNoiseStdDev*sqrt(2*PI))*exp(-0.5*(difference[0]-noisemean)*(difference[0]-noisemean)/(DisTurnNoiseStdDev*DisTurnNoiseStdDev));
p2 = 1.0/(DisCarDistNoiseStdDev*sqrt(2*PI))*exp(-0.5*(difference[1]-noisemean)*(difference[1]-noisemean)/(DisCarDistNoiseStdDev*DisCarDistNoiseStdDev));
return p1*p2;
default:
printf("q_next out of domain\n");
exit(1);
}
};
double ObsDrivingModel::getDStateTransProb(DState const& q_next, DState const& q_k, DControl const& sigma_k) const {
double sigma0[2][2] = { {0.95, 0.05},
{0.05, 0.95} };
double sigma1[2][2] = { {0.95, 0.8},
{0.05, 0.2}};
double P_att_S2T = 0.0377;
double P_dis_S2T = 0.2797;
double transprob_sigma0[4][4] = { { sigma0[0][0]*(1-P_att_S2T), 0 , sigma0[0][1] , 0 },
{ sigma0[0][0]*P_att_S2T , sigma0[0][0], 0 , sigma0[0][1] },
{ sigma0[1][0] , 0 , sigma0[1][1]*(1-P_dis_S2T), 0 },
{ 0 , sigma0[1][0], sigma0[1][1]*P_dis_S2T , sigma0[1][1] } };
double transprob_sigma1[4][4] = { { sigma1[0][0]*(1-P_att_S2T), 0 , sigma1[0][1] , 0 },
{ sigma1[0][0]*P_att_S2T , sigma1[0][0], 0 , sigma1[0][1] },
{ sigma1[1][0] , 0 , sigma1[1][1]*(1-P_dis_S2T), 0 },
{ 0 , sigma1[1][0], sigma1[1][1]*P_dis_S2T , sigma1[1][1] } };
if((sigma_k>>1) == 0) // (sigma_k == V00) || (sigma_k == V01)
{
return transprob_sigma0[q_next>>1][q_k>>1]*((q_next & 0x01) == (sigma_k & 0x01));
}
else // (sigma_k == V10) || (sigma_k == V11)
{
return transprob_sigma1[q_next>>1][q_k>>1]*((q_next & 0x01) == (sigma_k & 0x01));
}
};
double ObsDrivingModel::getDiscreteObsProb(DObs const& zq_k, DState const& q_k) const {
double ObsProb[3][2] = { {0.7617, 0.0145},
{0.2225, 0.42},
{0.0158, 0.5655} };
return ObsProb[zq_k][q_k>>2];
};
CState ObsDrivingModel::getNextCStateNoNoise(const DState& q_next, const CState& x_k) const{
CState x_next;
switch(q_next){
case ASC0:
x_next.push_back(x_k[0]);
x_next.push_back(x_k[1] + AttRelSpd);
break;
case ASC1:
x_next.push_back(x_k[0]);
x_next.push_back(x_k[1] + AttRelSpd+c);
break;
case ATC0:
x_next.push_back(x_k[0]+AttTurnConst);
x_next.push_back(x_k[1] + AttRelSpd);
break;
case ATC1:
x_next.push_back(x_k[0]+AttTurnConst);
x_next.push_back(x_k[1] + AttRelSpd+c);
break;
case DSC0:
x_next.push_back(x_k[0]);
x_next.push_back(x_k[1] + DisRelSpd);
break;
case DSC1:
x_next.push_back(x_k[0]);
x_next.push_back(x_k[1] + DisRelSpd+c);
break;
case DTC0:
x_next.push_back(x_k[0] + DisTurnConst);
x_next.push_back(x_k[1] + DisRelSpd);
break;
case DTC1:
x_next.push_back(x_k[0] + DisTurnConst);
x_next.push_back(x_k[1] + DisRelSpd+c);
break;
default:
printf("q_next out of domain\n");
exit(1);
}
return x_next;
};
vector<double> ObsDrivingModel::get1stDerivative(const DState& q, const CState& x) const {
vector<double> firstderivative;
firstderivative.push_back(1);
firstderivative.push_back(0);
firstderivative.push_back(0);
firstderivative.push_back(1);
return firstderivative;
};
vector<double> ObsDrivingModel::get2ndDerivative(const DState& q, const CState& x) const{
return vector<double>(1, 0);
};
double ObsDrivingModel::getReward(DState const& q, CState const& x, DControl const& sigma) const {
return RewardCoeff[sigma][q][0] + RewardCoeff[sigma][q][1]*x[0] + RewardCoeff[sigma][q][2]*x[0]*x[0] +
RewardCoeff[sigma][q][3]*x[0]*x[1] + RewardCoeff[sigma][q][4]*x[1] + RewardCoeff[sigma][q][5]*x[1]*x[1];
};
vector<vector<vector<double> > > ObsDrivingModel::getRewardCoeff() const {
return RewardCoeff;
};
vector<vector<double> > ObsDrivingModel::getCovariance() const {
vector<vector<double> > covariance;
for(DState q =0; q<NumDState_ObsDrMdl; q++) {
vector<double> cov_tmp;
if (q>>1 ==0 ){ //AS
cov_tmp.push_back(AttStraightNoiseStdDev*AttStraightNoiseStdDev);
cov_tmp.push_back(AttCarDistNoiseStdDev*AttCarDistNoiseStdDev);
}
else if(q>>1 ==1 ){ //AT
cov_tmp.push_back(AttTurnNoiseStdDev*AttTurnNoiseStdDev);
cov_tmp.push_back(AttCarDistNoiseStdDev*AttCarDistNoiseStdDev);
}
else if(q>>1 == 2){ //DS
cov_tmp.push_back(DisStraightNoiseStdDev*DisStraightNoiseStdDev);
cov_tmp.push_back(DisCarDistNoiseStdDev*DisCarDistNoiseStdDev);
}
else{ //DT
cov_tmp.push_back(DisTurnNoiseStdDev*DisTurnNoiseStdDev);
cov_tmp.push_back(DisCarDistNoiseStdDev*DisCarDistNoiseStdDev);
}
covariance.push_back(cov_tmp);
}
return covariance;
}
double ObsDrivingModel::getCost(const DState& q, const CState& x, const DControl& sigma) const {
double R_sigma1[2] = {0, 5};
double R_sigma2[2] = {0, 5};
return x[0]*x[0] + R_sigma1[sigma>>1] + R_sigma2[sigma&0x01];
};
double ObsDrivingModel::sample(const DState& q_k, const CState& x_k, const DControl& sigma_k, DState& q_next, CState& x_next, DObs& obs_out) const{
q_next = sampleDState(q_k, sigma_k);
// cout<<"q_next = "<<q_next<<" ";
x_next = sampleCState(q_next, x_k);
// cout<<"x_next[0] = "<<x_next[0]<<" ";
obs_out = sampleDObs(q_next);
// cout<<"obs_out = "<<obs_out<<endl;
return this->getDStateTransProb(q_next, q_k, sigma_k)* this->getCStateTransProb(x_next, q_next, x_k) * this->getDiscreteObsProb(q_next, obs_out);
};
| 38.450739 | 219 | 0.637819 | ppnathan |
e604cad676c67c985b25e9bf86e5c0771f6d6ab4 | 243 | cpp | C++ | src/core/nes.cpp | yvbbrjdr/lwnes | 3621dedb1f4871eb181109daee0c3020b4a2d5a8 | [
"BSD-3-Clause"
] | null | null | null | src/core/nes.cpp | yvbbrjdr/lwnes | 3621dedb1f4871eb181109daee0c3020b4a2d5a8 | [
"BSD-3-Clause"
] | null | null | null | src/core/nes.cpp | yvbbrjdr/lwnes | 3621dedb1f4871eb181109daee0c3020b4a2d5a8 | [
"BSD-3-Clause"
] | null | null | null | #include "nes.h"
using namespace std;
NES::NES() : cpu(dma) {}
void NES::load_rom(const string &filename)
{
rom.load_file(filename);
dma.load_cartridge(rom.to_cartridge());
cpu.reset();
}
void NES::start()
{
cpu.start();
}
| 13.5 | 43 | 0.633745 | yvbbrjdr |
e60eefd2a4367f50df8e934ceef2a4e4b7effb88 | 2,114 | cpp | C++ | src/Jogo/Parametros/ParametrosJogo.cpp | MatheusKunnen/Jogo-TecProg | 66f4320e51e42d12da74e487cc8552377ce865bb | [
"MIT"
] | null | null | null | src/Jogo/Parametros/ParametrosJogo.cpp | MatheusKunnen/Jogo-TecProg | 66f4320e51e42d12da74e487cc8552377ce865bb | [
"MIT"
] | null | null | null | src/Jogo/Parametros/ParametrosJogo.cpp | MatheusKunnen/Jogo-TecProg | 66f4320e51e42d12da74e487cc8552377ce865bb | [
"MIT"
] | null | null | null | //
// ParametrosJogo.cpp
// Jogo-SFML
//
// Created by Matheus Kunnen Ledesma on 11/15/19.
// Copyright © 2019 Matheus Kunnen Ledesma. All rights reserved.
//
#include "ParametrosJogo.hpp"
namespace Game { namespace Parametros {
ParametrosJogo::ParametrosJogo(const string& filename):
Parametro(filename),
player_name("Sem Nome"),
is_dual_player(false)
{
}
ParametrosJogo::~ParametrosJogo() {
this->g_arquivos.clear();
}
bool ParametrosJogo::loadFromFile(const string &filename){
bool status = true;
try {
if (this->filename != this->g_arquivos.getFilename())
this->g_arquivos.setFilename(filename);
// Check file load
if (!this->g_arquivos.load())
throw runtime_error("Error loading file.");
// Obtem informação do arquivo
//this->setPlayerName(this->g_arquivos.getData()["player_name"]); // Sempre inicia sem nome
this->setDualPlayer(this->g_arquivos.getData()["is_dual_player"] == 1);
} catch(std::exception e){
status = false;
cerr << "ERROR: ParametrosJogo::loadFromFile(): " << e.what() << endl;
}
return status;
}
bool ParametrosJogo::saveToFile(const string &filename) {
if (this->filename != this->g_arquivos.getFilename())
this->g_arquivos.setFilename(filename);
// Cria json com valores da classe
json data;
data["player_name"] = this->getPlayerName();
data["is_dual_player"] = this->is_dual_player ? 1 : 0;
// Passa json para o gerenciador de arquivos
g_arquivos.setData(data);
// Manda ao gerenciador de arquivos guardar o json
g_arquivos.save();
data.clear();
return true;
}
// Getters & Setters
void ParametrosJogo::setDualPlayer(const bool &is_dual_player) {
this->is_dual_player = is_dual_player;
}
const bool& ParametrosJogo::isDualPlayer() const {
return this->is_dual_player;
}
void ParametrosJogo::setPlayerName(const string &player_name) {
this->player_name = player_name;
}
const string& ParametrosJogo::getPlayerName() const {
return this->player_name;
}
}}
| 26.425 | 99 | 0.666982 | MatheusKunnen |
e60ff26bd5095b87dc0cb0d5aae014cd36140f54 | 3,146 | hpp | C++ | stapl_release/stapl/views/proxy/stl_vector_accessor.hpp | parasol-ppl/PPL_utils | 92728bb89692fda1705a0dee436592d97922a6cb | [
"BSD-3-Clause"
] | null | null | null | stapl_release/stapl/views/proxy/stl_vector_accessor.hpp | parasol-ppl/PPL_utils | 92728bb89692fda1705a0dee436592d97922a6cb | [
"BSD-3-Clause"
] | null | null | null | stapl_release/stapl/views/proxy/stl_vector_accessor.hpp | parasol-ppl/PPL_utils | 92728bb89692fda1705a0dee436592d97922a6cb | [
"BSD-3-Clause"
] | null | null | null | /*
// Copyright (c) 2000-2009, Texas Engineering Experiment Station (TEES), a
// component of the Texas A&M University System.
// All rights reserved.
// The information and source code contained herein is the exclusive
// property of TEES and may not be disclosed, examined or reproduced
// in whole or in part without explicit written authorization from TEES.
*/
#ifndef STAPL_VIEWS_PROXY_STL_VECTOR_ACCESSOR_HPP
#define STAPL_VIEWS_PROXY_STL_VECTOR_ACCESSOR_HPP
#include <stapl/views/proxy/accessor_base.hpp>
#include <stapl/runtime/serialization_fwd.hpp>
namespace stapl {
//////////////////////////////////////////////////////////////////////
/// @brief Defines an accessor for std::vector.
///
/// @tparam C Type of std::vector that is accessed.
//////////////////////////////////////////////////////////////////////
template <typename C>
struct stl_vector_accessor
: public accessor_base<typename C::value_type, stl_vector_accessor<C>>
{
private:
using index_type = typename container_traits<C>::domain_type::index_type;
C* m_container;
index_type m_index;
typedef typename C::value_type value_type;
friend class accessor_core_access;
public:
stl_vector_accessor(C* container, index_type index)
: m_container(container),
m_index(index)
{ }
bool is_local(void) const
{
return true;
}
bool is_null(void) const
{
return m_container == NULL;
}
template<typename F>
void apply_set(const F& f) const
{
f(m_container->operator[](m_index));
}
template<typename F>
typename F::result_type apply_get(F const& f) const
{
return f(m_container->operator[](m_index));
}
void define_type(typer& t)
{
t.member(m_container);
t.member(m_index);
}
};
//////////////////////////////////////////////////////////////////////
/// @brief Defines a const_accessor for std::vector.
///
/// @tparam C Type of std::vector that is accessed.
//////////////////////////////////////////////////////////////////////
template <typename C>
struct stl_vector_const_accessor
: public accessor_base<typename C::value_type, stl_vector_const_accessor<C>>
{
private:
using index_type = typename container_traits<C>::domain_type::index_type;
C const* m_container;
index_type m_index;
typedef typename C::value_type value_type;
friend class accessor_core_access;
public:
stl_vector_const_accessor(C const* container, index_type index)
: m_container(container),
m_index(index)
{ }
bool is_local(void) const
{
return true;
}
bool is_null(void) const
{
return m_container == NULL;
}
template<typename F>
typename F::result_type apply_get(F const& f) const
{
return f(m_container->operator[](m_index));
}
void define_type(typer& t)
{
t.member(m_container);
t.member(m_index);
}
};
template<typename C>
struct accessor_traits<stl_vector_accessor<C>>
{
using is_localized = std::true_type;
};
template<typename C>
struct accessor_traits<stl_vector_const_accessor<C>>
{
using is_localized = std::true_type;
};
} // namespace stapl
#endif /* STAPL_VIEWS_PROXY_STL_VECTOR_ACCESSOR_HPP */
| 22.633094 | 78 | 0.657661 | parasol-ppl |
e610610c4ac6c02db0e766e301c853bd10a164ff | 2,694 | hpp | C++ | libs/fnd/cstddef/include/bksge/fnd/cstddef/byte.hpp | myoukaku/bksge | 0f8b60e475a3f1709723906e4796b5e60decf06e | [
"MIT"
] | 4 | 2018-06-10T13:35:32.000Z | 2021-06-03T14:27:41.000Z | libs/fnd/cstddef/include/bksge/fnd/cstddef/byte.hpp | myoukaku/bksge | 0f8b60e475a3f1709723906e4796b5e60decf06e | [
"MIT"
] | 566 | 2017-01-31T05:36:09.000Z | 2022-02-09T05:04:37.000Z | libs/fnd/cstddef/include/bksge/fnd/cstddef/byte.hpp | myoukaku/bksge | 0f8b60e475a3f1709723906e4796b5e60decf06e | [
"MIT"
] | 1 | 2018-07-05T04:40:53.000Z | 2018-07-05T04:40:53.000Z | /**
* @file byte.hpp
*
* @brief byte の定義
*
* @author myoukaku
*/
#ifndef BKSGE_FND_CSTDDEF_BYTE_HPP
#define BKSGE_FND_CSTDDEF_BYTE_HPP
#include <cstddef>
#if defined(__cpp_lib_byte) && (__cpp_lib_byte >= 201603)
namespace bksge
{
using std::byte;
using std::to_integer;
} // namespace bksge
#else
#include <bksge/fnd/type_traits/enable_if.hpp>
#include <bksge/fnd/type_traits/is_integral.hpp>
#include <bksge/fnd/config.hpp>
namespace bksge
{
enum class byte : unsigned char {};
template <typename IntegerType>
inline BKSGE_CONSTEXPR bksge::enable_if_t<bksge::is_integral<IntegerType>::value, IntegerType>
to_integer(byte b) BKSGE_NOEXCEPT
{
return IntegerType(b);
}
inline BKSGE_CONSTEXPR byte operator|(byte lhs, byte rhs) BKSGE_NOEXCEPT
{
return byte(static_cast<unsigned char>(lhs) | static_cast<unsigned char>(rhs));
}
inline BKSGE_CONSTEXPR byte operator&(byte lhs, byte rhs) BKSGE_NOEXCEPT
{
return byte(static_cast<unsigned char>(lhs) & static_cast<unsigned char>(rhs));
}
inline BKSGE_CONSTEXPR byte operator^(byte lhs, byte rhs) BKSGE_NOEXCEPT
{
return byte(static_cast<unsigned char>(lhs) ^ static_cast<unsigned char>(rhs));
}
inline BKSGE_CONSTEXPR byte operator~(byte b) BKSGE_NOEXCEPT
{
return byte(~static_cast<unsigned char>(b));
}
inline BKSGE_CXX14_CONSTEXPR byte& operator|=(byte& lhs, byte rhs) BKSGE_NOEXCEPT
{
return lhs = lhs | rhs;
}
inline BKSGE_CXX14_CONSTEXPR byte& operator&=(byte& lhs, byte rhs) BKSGE_NOEXCEPT
{
return lhs = lhs & rhs;
}
inline BKSGE_CXX14_CONSTEXPR byte& operator^=(byte& lhs, byte rhs) BKSGE_NOEXCEPT
{
return lhs = lhs ^ rhs;
}
template <typename IntegerType>
inline BKSGE_CONSTEXPR bksge::enable_if_t<bksge::is_integral<IntegerType>::value, byte>
operator<<(byte lhs, IntegerType shift) BKSGE_NOEXCEPT
{
return byte(static_cast<unsigned char>(lhs) << shift);
}
template <typename IntegerType>
inline BKSGE_CONSTEXPR bksge::enable_if_t<bksge::is_integral<IntegerType>::value, byte>
operator>>(byte lhs, IntegerType shift) BKSGE_NOEXCEPT
{
return byte(static_cast<unsigned char>(lhs) >> shift);
}
template <typename IntegerType>
inline BKSGE_CXX14_CONSTEXPR bksge::enable_if_t<bksge::is_integral<IntegerType>::value, byte>&
operator<<=(byte& lhs, IntegerType shift) BKSGE_NOEXCEPT
{
return lhs = lhs << shift;
}
template <typename IntegerType>
inline BKSGE_CXX14_CONSTEXPR bksge::enable_if_t<bksge::is_integral<IntegerType>::value, byte>&
operator>>=(byte& lhs, IntegerType shift) BKSGE_NOEXCEPT
{
return lhs = lhs >> shift;
}
} // namespace bksge
#endif
#endif // BKSGE_FND_CSTDDEF_BYTE_HPP
| 24.490909 | 95 | 0.732739 | myoukaku |
e6111ba72bcbbcd5f557f20d51683624e1914201 | 10,397 | cpp | C++ | hanoi/eis-core/common/libs/ConfigManager/tests/configmgr_tests.cpp | emmanueltech1/edgex-go | cbcb11ee374850eb63010f80aaff7822c21725be | [
"Apache-2.0"
] | null | null | null | hanoi/eis-core/common/libs/ConfigManager/tests/configmgr_tests.cpp | emmanueltech1/edgex-go | cbcb11ee374850eb63010f80aaff7822c21725be | [
"Apache-2.0"
] | null | null | null | hanoi/eis-core/common/libs/ConfigManager/tests/configmgr_tests.cpp | emmanueltech1/edgex-go | cbcb11ee374850eb63010f80aaff7822c21725be | [
"Apache-2.0"
] | null | null | null | // Copyright (c) 2019 Intel Corporation.
//
// 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 Config Manager GTests unit tests
* @author Varalakshmi KA (varalakshmi.ka@intel.com)
*/
#include <gtest/gtest.h>
#include <string.h>
#include <unistd.h>
#include "eis/config_manager/config_manager.h"
#define COMMAND_LENGTH 40
#define PUT_VAL_CMD 30
#define TEST_PUT_VAL_CMD 32
static char* cert_file = NULL;
static char* key_file = NULL;
static char* ca_file = NULL;
static const char* app_name = "";
static char* root_cert = NULL;
static char* root_key = NULL;
static int watch_key_cb = 0;
static int watch_dir_cb = 0;
static int dev_mode = 0;
static char* command = "";
void watch_key_callback(char* key, char* value){
std::cout << "watch key callback....." << std::endl;
watch_key_cb++;
}
void watch_dir_callback(char* key, char* value){
std::cout << "watch dir callback....." << std::endl;
watch_dir_cb++;
}
void init(){
if(ca_file == NULL && cert_file == NULL && key_file == NULL){
dev_mode = 1;
return;
}
command = (char*)malloc((strlen(ca_file) + strlen(root_cert) + strlen(root_key) + COMMAND_LENGTH) * sizeof(char));
sprintf(command, " --cacert=%s --cert=%s --key=%s", ca_file, root_cert, root_key);
}
config_mgr_t* get_config_mgr_client(char *storage_type){
config_mgr_t *config_mgr_client = config_mgr_new(storage_type, cert_file, key_file, ca_file);
return config_mgr_client;
}
// Return the key in /[AppName]/key format
char* get_app_key(char* key){
char* app_key = (char*)malloc((strlen(app_name) + strlen(key) + 3) * sizeof(char));
strcpy(app_key, "/");
if(strcmp(app_name,"")){
// output of the below sprintf() will be: '/<app_name/'
sprintf(app_key, "%s%s/", app_key, app_name);
}
strcat(app_key, key);
return app_key;
}
TEST(configmgr_test, configmgr_init) {
std::cout << "Test case: create configmgr instance.." << std::endl;
config_mgr_t* config_mgr_client = get_config_mgr_client((char*)"etcd");
ASSERT_NE(nullptr, config_mgr_client);
config_mgr_config_destroy(config_mgr_client);
}
TEST(configmgr_test, configmgr_get_config) {
std::cout << "Test case: get_config()..." << std::endl;
config_mgr_t* config_mgr_client = get_config_mgr_client((char*)"etcd");
if (config_mgr_client == NULL){
FAIL() << "Failed to create config manager client";
}
char* put_cmd = (char*)malloc((strlen(command) + COMMAND_LENGTH) * sizeof(char));
char* key = get_app_key((char*)"test");
sprintf(put_cmd, "./etcdctl put %s test12356", key);
if(dev_mode == 0){
strcat(put_cmd, command);
}
system(put_cmd);
std::cout << "get_config() API on key:" << key << std::endl;
char* value = config_mgr_client->get_config(key);
free(put_cmd);
free(key);
config_mgr_config_destroy(config_mgr_client);
ASSERT_STREQ("test12356", value);
}
TEST(configmgr_test, configmgr_put_config) {
std::cout << "Test case: put_config()..." << std::endl;
config_mgr_t *config_mgr_client = get_config_mgr_client((char*)"etcd");
if (config_mgr_client == NULL){
FAIL() << "Failed to create config manager client";
}
char* key = get_app_key((char*)"datastore");
std::cout << "put_config() API on key:" << key << std::endl;
char* val = "UnitTesting put_config api";
int err_status = config_mgr_client->put_config(key, val);
if (err_status == -1){
FAIL() << "put_config() API is failed";
}
char *value = config_mgr_client->get_config(key);
free(key);
config_mgr_config_destroy(config_mgr_client);
ASSERT_STREQ(val, value);
}
TEST(configmgr_test, configmgr_register_watch_key) {
std::cout << "Test case: register_watch_key()..." << std::endl;
config_mgr_t *config_mgr_client = get_config_mgr_client((char*)"etcd");
if (config_mgr_client == NULL){
FAIL() << "Failed to create config manager client";
}
char* key = get_app_key((char*)"watch_key_test");
char* put_value_cmd = (char*)malloc((strlen(key) + strlen(command) + PUT_VAL_CMD + 20) * sizeof(char));
char* test_put_cmd = (char*)malloc((strlen(key) + strlen(command) + TEST_PUT_VAL_CMD + 20)* sizeof(char));
sprintf(put_value_cmd, "./etcdctl put %s test123", key);
sprintf(test_put_cmd, "./etcdctl put %s test123456", key);
if(dev_mode == 0){
strcat(put_value_cmd, command);
strcat(test_put_cmd, command);
}
system(put_value_cmd);
config_mgr_client->register_watch_key(key, watch_key_callback);
std::cout << "register_watch_key() API on key:" << key << std::endl;
sleep(2);
system(test_put_cmd);
config_mgr_config_destroy(config_mgr_client);
free(key);
free(put_value_cmd);
free(test_put_cmd);
ASSERT_EQ(1, watch_key_cb);
}
TEST(configmgr_test, configmgr_register_watch_dir) {
std::cout << "Test case: register_dir_key()..." << std::endl;
config_mgr_t *config_mgr_client = get_config_mgr_client((char*)"etcd");
if (config_mgr_client == NULL){
FAIL() << "Failed to create config manager client";
}
char* key = get_app_key((char*)"watch_dir_test");
char* put_value_cmd = (char*)malloc((strlen(key) + strlen(command) + PUT_VAL_CMD + 20) * sizeof(char));
char* test_put_cmd = (char*)malloc((strlen(key) + strlen(command) + TEST_PUT_VAL_CMD + 20)* sizeof(char));
sprintf(put_value_cmd, "./etcdctl put %s test123", key);
sprintf(test_put_cmd, "./etcdctl put %s test123456", key);
if(dev_mode == 0){
strcat(put_value_cmd, command);
strcat(test_put_cmd, command);
}
system(put_value_cmd);
char* watch_dir = get_app_key((char*)"watch_dir");
config_mgr_client->register_watch_dir(watch_dir, watch_dir_callback);
std::cout << "register_watch_dir() API on prefix:" << watch_dir << std::endl;
sleep(2);
system(test_put_cmd);
config_mgr_config_destroy(config_mgr_client);
free(key);
free(watch_dir);
free(put_value_cmd);
free(test_put_cmd);
ASSERT_EQ(1, watch_dir_cb);
}
TEST(configmgr_test, configmgr_init_fail) {
std::cout << "Test case: fail to create configmanager instance..." << std::endl;
config_mgr_t *config_mgr_client = get_config_mgr_client((char*)"test");
ASSERT_EQ(nullptr, config_mgr_client);
config_mgr_config_destroy(config_mgr_client);
}
TEST(configmgr_test, configmgr_get_config_fail) {
std::cout << "Test case: fail to get_config()..." << std::endl;
config_mgr_t* config_mgr_client = get_config_mgr_client((char*)"etcd");
if (config_mgr_client == NULL){
FAIL() << "Failed to create config manager client";
}
char* put_cmd = (char*)malloc((strlen(command) + COMMAND_LENGTH) * sizeof(char));
char* key = "/TestApp/test";
sprintf(put_cmd, "./etcdctl put %s test12", key);
if(dev_mode == 0){
strcat(put_cmd, command);
}
system(put_cmd);
std::cout << "get_config() API to Fail on key:" << key << std::endl;
char* value = config_mgr_client->get_config(key);
free(put_cmd);
config_mgr_config_destroy(config_mgr_client);
if(dev_mode == 0){
ASSERT_STREQ(nullptr, value);
}
}
TEST(configmgr_test, configmgr_put_config_fail) {
std::cout << "Test case: fail to put_config()..." << std::endl;
config_mgr_t *config_mgr_client = get_config_mgr_client((char*)"etcd");
if (config_mgr_client == NULL){
FAIL() << "Failed to create config manager client";
}
char* key = get_app_key((char*)"datasto");
std::cout << "put_config() API to Fail on key:" << key << std::endl;
int err_status = config_mgr_client->put_config(key, (char*)"UnitTesting put_config api fail");
free(key);
config_mgr_config_destroy(config_mgr_client);
if(dev_mode == 0){
ASSERT_EQ(-1, err_status);
}else{
ASSERT_EQ(0, err_status);
}
}
int main(int argc, char **argv) {
if(argc == 7){
app_name = argv[1];
cert_file = argv[2];
key_file = argv[3];
ca_file = argv[4];
root_cert = argv[5];
root_key = argv[6];
printf("Unit tests are running in Prod mode....\n");
}else if(argc == 2){
if(!strcmp(argv[1], "-h")){
printf("Usage In Dev mode: <program> <app_name>(Optional)\n");
printf("Usage In Prod mode: <program> <app_name> <app_cert_file> <app_key_file> <ca_file> <root_cert> <root_key>\napp_name: service name \napp_cert_file(In Prod mode): config manager client certificate in pem format \napp_key_file(In Prod mode): config manager private key in pem format \nca_file(In Prod mode): ca certificate in pem format \nroot_cert(In prod mode):config manager root certificate in pem format\nroot_key(In Prod mode): config manager root key in pem format\n");
return 0;
}
app_name = argv[1];
printf("Unit tests are running in Dev mode....\n");
}else if(argc == 1){
printf("Unit tests are running in Dev mode....\n");
}else{
printf("Wrong number of args are passed, Check the usuage: <program> -h\n");
}
init();
::testing::InitGoogleTest(&argc, argv);
int test_run_status = RUN_ALL_TESTS();
if(strcmp(command, "")){
free(command);
}
return test_run_status;
}
| 35.006734 | 493 | 0.665 | emmanueltech1 |
e6112822a4a125b3bf17a44ecc3084b3f678223d | 4,381 | hpp | C++ | include/propane_literals.hpp | AggroBird/propane | 83134d11f6a90798db8937761ab707d95c520f1b | [
"MIT"
] | 3 | 2021-02-28T12:52:43.000Z | 2021-12-31T00:12:48.000Z | include/propane_literals.hpp | AggroBird/propane | 83134d11f6a90798db8937761ab707d95c520f1b | [
"MIT"
] | null | null | null | include/propane_literals.hpp | AggroBird/propane | 83134d11f6a90798db8937761ab707d95c520f1b | [
"MIT"
] | null | null | null | #ifndef _HEADER_PROPANE_LITERALS
#define _HEADER_PROPANE_LITERALS
#include "propane_common.hpp"
namespace propane
{
union literal_t
{
constexpr literal_t() : as_u64(0) {}
constexpr literal_t(int8_t i8) : as_i8(i8) {}
constexpr literal_t(uint8_t u8) : as_u8(u8) {}
constexpr literal_t(int16_t i16) : as_i16(i16) {}
constexpr literal_t(uint16_t u16) : as_u16(u16) {}
constexpr literal_t(int32_t i32) : as_i32(i32) {}
constexpr literal_t(uint32_t u32) : as_u32(u32) {}
constexpr literal_t(int64_t i64) : as_i64(i64) {}
constexpr literal_t(uint64_t u64) : as_u64(u64) {}
constexpr literal_t(float f32) : as_f32(f32) {}
constexpr literal_t(double f64) : as_f64(f64) {}
constexpr literal_t(void* vptr) : as_vptr(vptr) {}
int8_t as_i8;
uint8_t as_u8;
int16_t as_i16;
uint16_t as_u16;
int32_t as_i32;
uint32_t as_u32;
int64_t as_i64;
uint64_t as_u64;
float as_f32;
double as_f64;
void* as_vptr;
};
static_assert(sizeof(literal_t) == sizeof(uint64_t), "Literal size invalid");
template<typename value_t> struct parse_result
{
parse_result() = default;
parse_result(type_idx type, value_t value) :
type(type),
value(value) {}
type_idx type = type_idx::invalid;
value_t value = value_t(0ull);
inline bool is_valid() const noexcept
{
return type != type_idx::invalid;
}
inline operator bool() const noexcept
{
return is_valid();
}
};
// Parse unsigned longs, which is the largest number representable in the current
// environment. From ulong, it can be range-checked with anything smaller
parse_result<uint64_t> parse_ulong(const char*& beg, const char* end, int32_t base);
parse_result<uint64_t> parse_ulong(const char*& beg, const char* end);
parse_result<uint64_t> parse_ulong(std::string_view str);
// Parse the largest integer readable (ulong), and then determine integer type and negate if provided
// Return value is an union with all possible data types
parse_result<literal_t> parse_int_literal(const char*& beg, const char* end);
parse_result<literal_t> parse_int_literal(std::string_view str);
// Parse any literal (including floating point)
parse_result<literal_t> parse_literal(const char*& beg, const char* end);
parse_result<literal_t> parse_literal(std::string_view str);
// Parse the largest number readable (ulong), and then apply integer type and negate if provided
// Cast the result to the specified type
template<typename value_t> concept literal_int = std::is_integral_v<value_t> || std::is_enum_v<value_t>;
template<literal_int value_t> parse_result<value_t> parse_int_literal_cast(const char*& beg, const char* end)
{
parse_result<value_t> result;
if (auto literal = parse_int_literal(beg, end))
{
switch (literal.type)
{
// First, cast to the encountered constant, then negate if applicable, then cast to the destination number type
case type_idx::i8: { result.value = value_t(literal.value.as_i8); break; }
case type_idx::u8: { result.value = value_t(literal.value.as_u8); break; }
case type_idx::i16: { result.value = value_t(literal.value.as_i16); break; }
case type_idx::u16: { result.value = value_t(literal.value.as_u16); break; }
case type_idx::i32: { result.value = value_t(literal.value.as_i32); break; }
case type_idx::u32: { result.value = value_t(literal.value.as_u32); break; }
case type_idx::i64: { result.value = value_t(literal.value.as_i64); break; }
case type_idx::u64: { result.value = value_t(literal.value.as_u64); break; }
default: return result;
}
result.type = derive_type_index_v<value_t>;
}
return result;
}
template<literal_int value_t> parse_result<value_t> parse_int_literal_cast(std::string_view str)
{
const char* beg = str.data();
const char* end = beg + str.size();
return parse_int_literal_cast<value_t>(beg, end);
}
}
#endif | 41.72381 | 127 | 0.642091 | AggroBird |
e611bcfcfc4c01f24dfade65f71ddfc63663f6b9 | 303 | cpp | C++ | 53-maximum-subarray/53-maximum-subarray.cpp | Ananyaas/LeetCodeDaily | e134e20ac02f26dc40881c376656d3294be0df2c | [
"MIT"
] | 2 | 2022-01-02T19:15:00.000Z | 2022-01-05T21:12:24.000Z | 53-maximum-subarray/53-maximum-subarray.cpp | Ananyaas/LeetCodeDaily | e134e20ac02f26dc40881c376656d3294be0df2c | [
"MIT"
] | null | null | null | 53-maximum-subarray/53-maximum-subarray.cpp | Ananyaas/LeetCodeDaily | e134e20ac02f26dc40881c376656d3294be0df2c | [
"MIT"
] | 1 | 2022-03-11T17:11:07.000Z | 2022-03-11T17:11:07.000Z | class Solution {
public:
int maxSubArray(vector<int>& nums) {
int currmax=nums[0];
int finmax=nums[0];
for(int i=1;i<nums.size();i++){
currmax=max(nums[i],nums[i]+currmax);
finmax=max(currmax,finmax);
}
return finmax;
}
}; | 23.307692 | 49 | 0.508251 | Ananyaas |
e615a38c81405eb59bcf0ca3526a29d44bbe194f | 12,002 | cpp | C++ | src/particle_system/ParticleSystem.cpp | SirKoto/particle_sim | 76c8a89dd5bc8d52ebccfeb2ef6c4d604a343660 | [
"MIT"
] | 2 | 2022-01-10T18:22:34.000Z | 2022-02-23T23:18:36.000Z | src/particle_system/ParticleSystem.cpp | SirKoto/particle_sim | 76c8a89dd5bc8d52ebccfeb2ef6c4d604a343660 | [
"MIT"
] | null | null | null | src/particle_system/ParticleSystem.cpp | SirKoto/particle_sim | 76c8a89dd5bc8d52ebccfeb2ef6c4d604a343660 | [
"MIT"
] | null | null | null | #include "ParticleSystem.hpp"
#include <array>
#include <glad/glad.h>
#include <imgui.h>
#include <numeric>
#include "graphics/my_gl_header.hpp"
using namespace particle;
ParticleSystem::ParticleSystem()
{
const std::filesystem::path proj_dir(PROJECT_DIR);
const std::filesystem::path shad_dir = proj_dir / "resources/shaders";
m_ico_mesh = TriangleMesh(proj_dir / "resources/ply/icosahedron.ply");
m_ico_mesh.upload_to_gpu();
m_advect_compute_program = ShaderProgram(
&Shader(shad_dir / "advect_particles.comp", Shader::Type::Compute),
1
);
m_simple_spawner_program = ShaderProgram(
&Shader(shad_dir / "simple_spawner.comp", Shader::Type::Compute),
1
);
glGenVertexArrays(1, &m_ico_draw_vao);
// Generate particle buffers
glGenBuffers(2, m_vbo_particle_buffers);
glGenBuffers(2, m_draw_indirect_buffers);
glGenBuffers(2, m_alive_particle_indices);
glGenBuffers(1, &m_dead_particle_indices);
glGenBuffers(1, &m_dead_particle_count);
glGenBuffers(1, &m_sphere_ssb);
for (uint32_t i = 0; i < 2; ++i) {
// Initialise indirect draw buffer, and bind in 3
glBindBuffer(GL_DRAW_INDIRECT_BUFFER, m_draw_indirect_buffers[i]);
DrawElementsIndirectCommand command{
(uint32_t)m_ico_mesh.get_faces().size() * 3, // num elements
0, // instance count
0, // first index
0, // basevertex
0 // baseinstance
};
glBufferData(GL_DRAW_INDIRECT_BUFFER,
sizeof(DrawElementsIndirectCommand),
&command, GL_DYNAMIC_DRAW);
}
// Setup configuration
m_system_config.max_particles = 500;
m_system_config.gravity = 9.8f;
m_system_config.particle_size = 1.0e-1f;
m_system_config.simulation_space_size = 10.0f;
m_system_config.k_v = 0.9999f;
m_system_config.bounce = 0.5f;
m_system_config.friction = 0.01f;
m_spawner_config.pos = glm::vec3(5.0f);
m_spawner_config.mean_lifetime = 2.0f;
m_spawner_config.var_lifetime = 1.0f;
m_spawner_config.particle_speed = 5.f;
// Generate buffer config
glGenBuffers(1, &m_system_config_bo);
glBindBuffer(GL_SHADER_STORAGE_BUFFER, m_system_config_bo);
glBufferData(GL_SHADER_STORAGE_BUFFER,
sizeof(ParticleSystemConfig) + sizeof(ParticleSpawnerConfig),
nullptr, GL_STATIC_DRAW);
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, BINDING_SYSTEM_CONFIG, m_system_config_bo);
glBindBuffer(GL_SHADER_STORAGE_BUFFER, 0);
update_sytem_config();
// Initialize shapes
glBindBuffer(GL_SHADER_STORAGE_BUFFER, m_sphere_ssb);
glBufferData(GL_SHADER_STORAGE_BUFFER,
sizeof(Sphere),
nullptr, GL_STATIC_DRAW);
glBindBuffer(GL_SHADER_STORAGE_BUFFER, 0);
initialize_system();
update_intersection_sphere();
update_intersection_mesh();
}
void ParticleSystem::update(float time, float dt)
{
// Bind in compute shader as bindings 1 and 2
// 1 is previous frame, and 2 is the next
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, BINDING_PARTICLES_IN, m_vbo_particle_buffers[m_flipflop_state]);
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, BINDING_PARTICLES_OUT, m_vbo_particle_buffers[1 - (uint32_t)m_flipflop_state]);
glBindBufferBase(GL_ATOMIC_COUNTER_BUFFER, BINDING_ATOMIC_ALIVE_IN, m_draw_indirect_buffers[m_flipflop_state]);
glBindBufferBase(GL_ATOMIC_COUNTER_BUFFER, BINDING_ATOMIC_ALIVE_OUT, m_draw_indirect_buffers[1 - (uint32_t)m_flipflop_state]);
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, BINDING_ALIVE_LIST_IN, m_alive_particle_indices[m_flipflop_state]);
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, BINDING_ALIVE_LIST_OUT, m_alive_particle_indices[1 - (uint32_t)m_flipflop_state]);
// Clear the atomic counter of alive particles
glClearNamedBufferSubData(m_draw_indirect_buffers[1 - m_flipflop_state], GL_R32F,
offsetof(DrawElementsIndirectCommand, primCount),
sizeof(uint32_t), GL_RED, GL_FLOAT, nullptr);
uint32_t num_particles_to_instantiate;
{
m_accum_particles_emmited += m_emmit_particles_per_second * dt;
float floor_part = std::floor(m_accum_particles_emmited);
m_accum_particles_emmited -= floor_part;
num_particles_to_instantiate = static_cast<uint32_t>(floor_part);
}
if (num_particles_to_instantiate != 0) {
m_simple_spawner_program.use_program();
glUniform1f(0, time);
glUniform1f(1, dt);
glUniform1ui(2, num_particles_to_instantiate);
glDispatchCompute(num_particles_to_instantiate / 32
+ (num_particles_to_instantiate % 32 == 0 ? 0 : 1), 1, 1);
glMemoryBarrier(GL_ALL_BARRIER_BITS);
}
// Start compute shader
m_advect_compute_program.use_program();
glUniform1f(0, dt);
glDispatchCompute(m_system_config.max_particles / 32
+ (m_system_config.max_particles % 32 == 0 ? 0 : 1)
, 1, 1);
// flip state
m_flipflop_state = !m_flipflop_state;
}
void ParticleSystem::gl_render_particles() const
{
glMemoryBarrier(GL_ALL_BARRIER_BITS);
glBindVertexArray(m_ico_draw_vao);
glBindBuffer(GL_DRAW_INDIRECT_BUFFER, m_draw_indirect_buffers[m_flipflop_state]);
glDrawElementsIndirect(GL_TRIANGLES,
GL_UNSIGNED_INT,
(void*)0);
glBindBuffer(GL_DRAW_INDIRECT_BUFFER, 0);
glBindVertexArray(0);
}
void ParticleSystem::imgui_draw()
{
bool update = false;
ImGui::PushID("Particlesystem");
ImGui::Text("Particle System Config");
update |= ImGui::DragFloat("Gravity", &m_system_config.gravity, 0.01f);
update |= ImGui::DragFloat("Particle size", &m_system_config.particle_size, 0.01f, 0.0f, 2.0f);
update |= ImGui::InputFloat("Simulation space size", &m_system_config.simulation_space_size, 0.1f);
update |= ImGui::InputFloat("Verlet damping", &m_system_config.k_v, 0.0001f, 0.0f, "%.5f");
update |= ImGui::InputFloat("Bounciness", &m_system_config.bounce, 0.1f);
update |= ImGui::InputFloat("Friction", &m_system_config.friction, 0.01f);
ImGui::Separator();
if (ImGui::TreeNode("Spawner Config")) {
ImGui::DragFloat("Particles/Second", &m_emmit_particles_per_second, 1.0f, 10.0f);
update |= ImGui::DragFloat3("Position", &m_spawner_config.pos.x, 0.01f);
update |= ImGui::DragFloat("Initial Velocity", &m_spawner_config.particle_speed, 0.02f, 0.0f, FLT_MAX);
update |= ImGui::DragFloat("Mean lifetime", &m_spawner_config.mean_lifetime, 0.2f, 0.0f, FLT_MAX);
update |= ImGui::DragFloat("Var lifetime", &m_spawner_config.var_lifetime, 0.2f, 0.0f, FLT_MAX);
ImGui::TreePop();
}
ImGui::Separator();
ImGui::TextDisabled("Config system limit. Needs to reset simulation");
bool reset = ImGui::InputScalar("Max particles", ImGuiDataType_U32, &m_system_config.max_particles);
if (reset || ImGui::Button("Reset simulation")) {
update_sytem_config();
initialize_system();
} else if (update) {
update_sytem_config();
}
ImGui::Separator();
if (ImGui::Checkbox("Sphere collisions", &m_intersect_sphere_enabled)) {
update_intersection_sphere();
}
ImGui::Separator();
if (ImGui::Checkbox("Mesh collisions", &m_intersect_mesh_enabled)) {
update_intersection_mesh();
}
ImGui::PopID();
}
void ParticleSystem::set_sphere(const glm::vec3& pos, float radius)
{
m_sphere.pos = pos;
m_sphere.radius = radius;
glBindBuffer(GL_SHADER_STORAGE_BUFFER, m_sphere_ssb);
glBufferSubData(GL_SHADER_STORAGE_BUFFER, 0, sizeof(Sphere), &m_sphere);
glBindBuffer(GL_SHADER_STORAGE_BUFFER, 0);
}
void ParticleSystem::remove_sphere()
{
m_intersect_sphere_enabled = false;
update_intersection_sphere();
}
void ParticleSystem::set_mesh(const TriangleMesh& mesh, const glm::mat4& transform)
{
m_intersect_mesh = TriangleMesh(mesh);
m_intersect_mesh.apply_transform(transform);
m_intersect_mesh.upload_to_gpu();
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, BINDING_MESH_VERTICES, m_intersect_mesh.get_vbo_vertices());
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, BINDING_MESH_INDICES, m_intersect_mesh.get_vbo_indices());
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, BINDING_MESH_NORMALS, m_intersect_mesh.get_vbo_normals());
}
void ParticleSystem::reset_bindings() const
{
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, BINDING_SYSTEM_CONFIG, m_system_config_bo);
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, BINDING_MESH_VERTICES, m_intersect_mesh.get_vbo_vertices());
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, BINDING_MESH_INDICES, m_intersect_mesh.get_vbo_indices());
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, BINDING_MESH_NORMALS, m_intersect_mesh.get_vbo_normals());
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, BINDING_SHAPE_SPHERE, m_sphere_ssb);
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, BINDING_DEAD_LIST, m_dead_particle_indices);
glBindBufferBase(GL_ATOMIC_COUNTER_BUFFER, BINDING_ATOMIC_DEAD, m_dead_particle_count);
}
void ParticleSystem::initialize_system()
{
// TODO
m_accum_particles_emmited = 1.0f;
m_flipflop_state = false;
std::vector<Particle> particles(m_system_config.max_particles, { glm::vec3(5.0f) });
for (uint32_t i = 0; i < m_system_config.max_particles; ++i) {
particles[i].pos.x += (float)i;
particles[i].pos.y += (float)(i) * 0.2f;
}
if (m_max_particles_in_buffers < m_system_config.max_particles) {
for (uint32_t i = 0; i < 2; ++i) {
// Reserve particle data
glBindBuffer(GL_ARRAY_BUFFER, m_vbo_particle_buffers[i]);
glBufferData(GL_ARRAY_BUFFER, sizeof(Particle) * m_system_config.max_particles,
nullptr, GL_DYNAMIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);
// Reserve particle indices
glBindBuffer(GL_SHADER_STORAGE_BUFFER, m_alive_particle_indices[i]);
glBufferData(GL_SHADER_STORAGE_BUFFER, sizeof(uint32_t) * m_system_config.max_particles,
nullptr, GL_DYNAMIC_DRAW);
glBindBuffer(GL_SHADER_STORAGE_BUFFER, 0);
}
glBindBuffer(GL_SHADER_STORAGE_BUFFER, m_dead_particle_indices);
glBufferData(GL_SHADER_STORAGE_BUFFER, sizeof(uint32_t) * m_system_config.max_particles,
nullptr, GL_DYNAMIC_DRAW);
m_max_particles_in_buffers = m_system_config.max_particles;
}
// Initialize dead particles (all)
{
std::vector<uint32_t> dead_indices(m_system_config.max_particles);
std::iota(dead_indices.rbegin(), dead_indices.rend(), 0);
glBindBuffer(GL_SHADER_STORAGE_BUFFER, m_dead_particle_indices);
glBufferSubData(GL_SHADER_STORAGE_BUFFER,
0, // offset
sizeof(uint32_t) * m_system_config.max_particles, // size
dead_indices.data());
glBindBuffer(GL_SHADER_STORAGE_BUFFER, 0);
}
glBindBuffer(GL_ATOMIC_COUNTER_BUFFER, m_dead_particle_count);
glNamedBufferData(m_dead_particle_count, sizeof(uint32_t), &m_system_config.max_particles, GL_STATIC_DRAW);
glBindBuffer(GL_ATOMIC_COUNTER_BUFFER, 0);
// Initialise indirect draw buffer, and bind in 3, to use the atomic counter to track the particles that are alive
for (uint32_t i = 0; i < 2; ++i) {
glClearNamedBufferSubData(m_draw_indirect_buffers[i], GL_R32F,
offsetof(DrawElementsIndirectCommand, primCount),
sizeof(uint32_t), GL_RED, GL_FLOAT, nullptr);
}
glBindBuffer(GL_DRAW_INDIRECT_BUFFER, 0);
// Create VAO to draw. Only 1 to use the buffer to get the instances
glBindVertexArray(m_ico_draw_vao);
m_ico_mesh.gl_bind_to_vao();
glBindVertexArray(0);
reset_bindings();
}
void ParticleSystem::update_sytem_config()
{
glNamedBufferSubData(
m_system_config_bo, // buffer name
0, // offset
sizeof(ParticleSystemConfig), // size
&m_system_config // data
);
glNamedBufferSubData(
m_system_config_bo, // buffer name
sizeof(ParticleSystemConfig), // offset
sizeof(ParticleSpawnerConfig), // size
&m_spawner_config // data
);
}
void ParticleSystem::update_intersection_sphere()
{
m_advect_compute_program.use_program();
if (m_intersect_sphere_enabled) {
glUniform1ui(1, 1);
}
else {
glUniform1ui(1, 0);
}
glUseProgram(0);
}
void ParticleSystem::update_intersection_mesh()
{
m_advect_compute_program.use_program();
if (m_intersect_mesh_enabled) {
glUniform1ui(2, 1);
}
else {
glUniform1ui(2, 0);
}
glUseProgram(0);
}
| 32.61413 | 128 | 0.754624 | SirKoto |
e61b0d53f655011679d4b9ee5117c177cf01e432 | 2,220 | cpp | C++ | Chernyshev/03/calc.cpp | mtrempoltsev/msu_cpp_autumn_2018 | 9272511ddfaa78332cfabda071b5fa3a9aee79cf | [
"MIT"
] | 16 | 2018-09-27T13:59:59.000Z | 2019-10-01T21:33:40.000Z | Chernyshev/03/calc.cpp | mtrempoltsev/msu_cpp_autumn_2018 | 9272511ddfaa78332cfabda071b5fa3a9aee79cf | [
"MIT"
] | 2 | 2018-10-17T20:56:15.000Z | 2018-10-24T00:02:42.000Z | Chernyshev/03/calc.cpp | mtrempoltsev/msu_cpp_autumn_2018 | 9272511ddfaa78332cfabda071b5fa3a9aee79cf | [
"MIT"
] | 22 | 2018-09-27T14:00:16.000Z | 2019-12-17T19:44:33.000Z | #include <iostream>
#include <string>
#include <sstream>
#include <stdexcept>
template <class T>
class Calculator
{
private:
T unary_minus(std::istringstream &expr) const
{
char minus;
expr >> minus;
if (!expr) {
throw std::invalid_argument("");
}
if (minus == '-') {
return -1;
}
expr.putback(minus);
return 1;
}
T read_number(std::istringstream &expr) const
{
T sign = unary_minus(expr);
T number;
expr >> number;
if (!expr) {
throw std::invalid_argument("");
}
return sign * number;
}
T multiplication_and_division(std::istringstream &expr) const
{
T arg1 = read_number(expr);
char op;
while (expr >> op && (op == '*' || op == '/')) {
T arg2 = read_number(expr);
if (op == '*') {
arg1 *= arg2;
} else {
if (arg2 == 0) {
throw std::invalid_argument("");
}
arg1 /= arg2;
}
}
if (expr) {
expr.putback(op);
}
return arg1;
}
T summation_and_subtraction(std::istringstream &expr) const
{
T arg1 = multiplication_and_division(expr);
char op;
while (expr >> op && (op == '+' || op == '-')) {
T arg2 = multiplication_and_division(expr);
if (op == '+') {
arg1 += arg2;
} else {
arg1 -= arg2;
}
}
if (expr) {
throw std::invalid_argument("");
}
return arg1;
}
public:
Calculator()
{
}
T get_result(const std::string &expr) const
{
std::istringstream iss(expr);
return summation_and_subtraction(iss);
}
};
int main(int argc, char *argv[])
{
if (argc != 2) {
std::cout << "error" << std::endl;
return 1;
}
try {
std::cout << Calculator<int64_t>().get_result(argv[1]) << std::endl;
} catch(const std::invalid_argument &) {
std::cout << "error" << std::endl;
return 1;
}
}
| 20.555556 | 76 | 0.454054 | mtrempoltsev |
e62412a371c674a02c9eca53c78e7d56f0f30e64 | 2,406 | hh | C++ | menon/bits/toctrans.hh | menonfled/menon_cpp_lib | 729bb581023e7558360fd17ac0866e20b2d7ec40 | [
"BSL-1.0"
] | 1 | 2020-09-10T16:47:09.000Z | 2020-09-10T16:47:09.000Z | menon/bits/toctrans.hh | menonfled/menon_cpp_lib | 729bb581023e7558360fd17ac0866e20b2d7ec40 | [
"BSL-1.0"
] | null | null | null | menon/bits/toctrans.hh | menonfled/menon_cpp_lib | 729bb581023e7558360fd17ac0866e20b2d7ec40 | [
"BSL-1.0"
] | null | null | null | /// @file menon/bits/toctrans.hh
/// 文字種変換関数の定義
/// @author @menonfled
#ifndef MENON_BITS_TOCTRANS_HH_
#define MENON_BITS_TOCTRANS_HH_
#pragma once
#include "menon/bits/sv.hh"
#include "menon/bits/isctype.hh"
#include <string>
#include <algorithm>
#include <iterator>
namespace menon
{
/// 変換種別
using ctrans_t = char (*)(char);
/// 小文字への変換
/// @param[in] c 変換対象の文字
/// @return cが大文字の場合は対応する小文字を、それ以外はcを返す。
template <typename Char>
constexpr Char tolower(Char c)
{
if (isupper(c))
return static_cast<Char>(c | 0x20);
return c;
}
/// 大文字への変換
/// @param[in] c 変換対象の文字
/// @return cが小文字の場合は対応する大文字を、それ以外はcを返す。
template <typename Char>
constexpr Char toupper(Char c)
{
if (islower(c))
return static_cast<Char>(c & ~0x20);
return c;
}
/// 指定した種別による変換
/// @param[in] c 変換対象の文字
/// @param[in] trans 変換種別
/// @return transで指定した文字種にcを変換した結果を返す。
template <typename Char>
constexpr Char toctrans(Char c, ctrans_t trans)
{
if (trans == tolower<char>)
c = tolower(c);
else if (trans == toupper<char>)
c = toupper(c);
return c;
}
/// 文字列から変換種別への変換
/// @param[in] name 変換種別に対応する文字列
/// @return nameに対応する変換種別を返す。
constexpr ctrans_t ctrans(std::string_view name)
{
if (name == "tolower")
return tolower;
if (name == "toupper")
return toupper;
return {};
}
/// 文字列を小文字に変換する。
/// @param[in] s 変換対象の文字列
/// @return sに含まれる'A'~'Z'を'a'~'z'に変換した文字列を返す。
template <typename String>
auto strtolower(String const& s)
{
using ::menon::sv;
auto t = sv(s);
using sv_type = decltype(t);
using char_type = typename sv_type::value_type;
std::basic_string<char_type> r;
r.reserve(t.size());
std::transform(t.cbegin(), t.cend(), std::back_inserter(r), &menon::tolower<char_type>);
return r;
}
/// 文字列を大文字に変換する。
/// @param[in] s 変換対象の文字列
/// @return sに含まれる'a'~'z'を'A'~'Z'に変換した文字列を返す。
template <typename String>
auto strtoupper(String const& s)
{
using ::menon::sv;
auto t = sv(s);
using sv_type = decltype(t);
using char_type = typename sv_type::value_type;
std::basic_string<char_type> r;
r.reserve(t.size());
std::transform(t.cbegin(), t.cend(), std::back_inserter(r), &menon::toupper<char_type>);
return r;
}
}
#endif // !MENON_BITS_TOCTRANS_HH_
| 23.821782 | 92 | 0.620116 | menonfled |
e62ceac8629f543e08ca01a587f2c9f076625fe9 | 8,083 | cpp | C++ | drlvm/vm/jitrino/src/codegenerator/ia32/Ia32ComplexAddrFormLoader.cpp | sirinath/Harmony | 724deb045a85b722c961d8b5a83ac7a697319441 | [
"Apache-2.0"
] | 8 | 2015-11-04T06:06:35.000Z | 2021-07-04T13:47:36.000Z | drlvm/vm/jitrino/src/codegenerator/ia32/Ia32ComplexAddrFormLoader.cpp | sirinath/Harmony | 724deb045a85b722c961d8b5a83ac7a697319441 | [
"Apache-2.0"
] | 1 | 2021-10-17T13:07:28.000Z | 2021-10-17T13:07:28.000Z | drlvm/vm/jitrino/src/codegenerator/ia32/Ia32ComplexAddrFormLoader.cpp | sirinath/Harmony | 724deb045a85b722c961d8b5a83ac7a697319441 | [
"Apache-2.0"
] | 13 | 2015-11-27T03:14:50.000Z | 2022-02-26T15:12:20.000Z | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @author Nikolay A. Sidelnikov
*/
#include "Ia32CodeGenerator.h"
#include "Ia32CFG.h"
#include "Ia32IRManager.h"
#include "Ia32Inst.h"
#include "open/types.h"
#include "Stl.h"
#include "MemoryManager.h"
#include "Type.h"
namespace Jitrino
{
namespace Ia32 {
struct SubOpndsTable {
Opnd * baseOp;
Opnd * indexOp;
Opnd * scaleOp;
Opnd * dispOp;
Opnd * baseCand1;
Opnd * baseCand2;
Opnd * suspOp;
SubOpndsTable(Opnd * s, Opnd * disp) : baseOp(NULL), indexOp(NULL), scaleOp(NULL), dispOp(disp), baseCand1(NULL), baseCand2(NULL), suspOp(s) {}
};
class ComplexAddrFormLoader : public SessionAction {
void runImpl();
protected:
//fill complex address form
bool findAddressComputation(Opnd * memOp);
bool checkIsScale(Inst * inst);
void walkThroughOpnds(SubOpndsTable& table);
private:
U_32 refCountThreshold;
};
static ActionFactory<ComplexAddrFormLoader> _cafl("cafl");
void
ComplexAddrFormLoader::runImpl() {
refCountThreshold = getIntArg("threshold", 4);
if(refCountThreshold < 2) {
refCountThreshold = 2;
assert(0);
}
StlMap<Opnd *, bool> memOpnds(irManager->getMemoryManager());
U_32 opndCount = irManager->getOpndCount();
irManager->calculateOpndStatistics();
for (U_32 i = 0; i < opndCount; i++) {
Opnd * opnd = irManager->getOpnd(i);
if(opnd->isPlacedIn(OpndKind_Mem)) {
Opnd * baseOp = opnd->getMemOpndSubOpnd(MemOpndSubOpndKind_Base);
Opnd * indexOp = opnd->getMemOpndSubOpnd(MemOpndSubOpndKind_Index);
if (baseOp && (!indexOp)) {
StlMap<Opnd *, bool>::iterator it = memOpnds.find(baseOp);
if(it == memOpnds.end() || it->second) {
memOpnds[baseOp]=findAddressComputation(opnd);
}
}
}
}
}
bool
ComplexAddrFormLoader::findAddressComputation(Opnd * memOp) {
Opnd * disp = memOp->getMemOpndSubOpnd(MemOpndSubOpndKind_Displacement);
Opnd * base = memOp->getMemOpndSubOpnd(MemOpndSubOpndKind_Base);
Inst * inst = base->getDefiningInst();
if (!inst)
return true;
SubOpndsTable table(base, disp);
walkThroughOpnds(table);
if(!table.baseOp)
table.baseOp = table.suspOp;
if(base->getRefCount() > refCountThreshold) {
if (table.indexOp) {
Inst* newIns = irManager->newInst(Mnemonic_LEA, base, irManager->newMemOpnd(irManager->getTypeManager().getUnmanagedPtrType(memOp->getType()), table.baseOp, table.indexOp, table.scaleOp, table.dispOp));
newIns->insertAfter(inst);
return false;
}
} else {
if (table.baseOp) {
Opnd* origOp = memOp->getMemOpndSubOpnd(MemOpndSubOpndKind_Base);
Opnd* replacementOp = table.baseOp;
if (origOp->getType()->isUnmanagedPtr() && replacementOp->getType()->isInteger()) {
replacementOp->setType(origOp->getType());
}
memOp->setMemOpndSubOpnd(MemOpndSubOpndKind_Base, replacementOp);
}
if (table.indexOp) {
memOp->setMemOpndSubOpnd(MemOpndSubOpndKind_Index, table.indexOp);
if (table.scaleOp) {
memOp->setMemOpndSubOpnd(MemOpndSubOpndKind_Scale, table.scaleOp);
} else {
assert(0);
}
}
if (table.dispOp) {
memOp->setMemOpndSubOpnd(MemOpndSubOpndKind_Displacement, table.dispOp);
}
}
return true;
}//end ComplexAddrFormLoader::findAddressComputation
bool
ComplexAddrFormLoader::checkIsScale(Inst * inst) {
Opnd * opnd = inst->getOpnd(3);
if(opnd->isPlacedIn(OpndKind_Imm)) {
switch(opnd->getImmValue()) {
case 1:
case 2:
case 4:
case 8:
return true;
default:
return false;
}
}
return false;
}
void
ComplexAddrFormLoader::walkThroughOpnds(SubOpndsTable& table) {
Opnd * opnd;
if (table.baseCand1)
opnd = table.baseCand1;
else if(table.baseCand2)
opnd = table.baseCand2;
else
opnd = table.suspOp;
Inst * instUp = opnd->getDefiningInst();
for(;instUp!=NULL && instUp->getMnemonic() == Mnemonic_MOV;instUp = instUp->getOpnd(1)->getDefiningInst());
if(!instUp) {
if(!table.baseOp && !opnd->isPlacedIn(OpndKind_Mem)) {
table.baseOp = opnd;
if (table.baseCand1) {
table.baseCand1 = NULL;
walkThroughOpnds(table);
}
} else if (table.baseOp) {
table.baseOp = table.suspOp;
table.baseCand1 = NULL;
table.baseCand2 = NULL;
// table.dispOp = NULL;
}
return;
}
U_32 defCount = instUp->getOpndCount(Inst::OpndRole_InstLevel|Inst::OpndRole_Def);
if(instUp->getMnemonic()==Mnemonic_ADD) {
Opnd * src1 = instUp->getOpnd(defCount);
Opnd * src2 = instUp->getOpnd(defCount+1);
if(src1->isPlacedIn(OpndKind_Mem) || (src2->isPlacedIn(OpndKind_Mem))) {
table.baseOp = table.suspOp;
return;
} else if(src2->isPlacedIn(OpndKind_Imm)) {
irManager->resolveRuntimeInfo(src2);
#ifdef _EM64T_
if((src2->getImmValue() > (int64)0x7FFFFFFF) || (src2->getImmValue() < -((int64)0x10000000))) {
table.baseOp = table.suspOp;
return;
}
#endif
if (table.baseCand1) {
table.baseCand1 = NULL;
table.baseOp = src1;
} else if (table.baseCand2) {
if(!table.baseOp)
table.baseOp = src1;
else {
table.baseOp = table.suspOp;
return;
}
} else {
table.suspOp = src1;
}
if(table.dispOp) {
irManager->resolveRuntimeInfo(table.dispOp);
table.dispOp = irManager->newImmOpnd(table.dispOp->getType(), table.dispOp->getImmValue() + src2->getImmValue());
return;
} else {
table.dispOp = src2;
}
walkThroughOpnds(table);
}else if(table.baseCand1) {
assert(!table.baseOp);
table.baseOp = table.baseCand1;
table.baseCand1 = NULL;
walkThroughOpnds(table);
}else if(table.baseCand2) {
assert(table.baseOp);
table.baseOp = table.suspOp;
}else if(!table.baseOp) {
table.baseCand1 = src1;
table.baseCand2 = src2;
walkThroughOpnds(table);
} else {
table.baseOp = table.suspOp;
}
} else if(instUp->getMnemonic()==Mnemonic_IMUL && checkIsScale(instUp)) {
table.indexOp = instUp->getOpnd(defCount);
table.scaleOp = instUp->getOpnd(defCount+1);
if(table.baseCand1) {
table.baseCand1 = NULL;
table.suspOp = table.baseCand2;
table.baseCand2 = NULL;
walkThroughOpnds(table);
}
} else {
table.baseOp = table.suspOp;
}
}
} //end namespace Ia32
}
| 32.724696 | 214 | 0.590127 | sirinath |
e63072a5d3a0e0744932ff7bb0938786ca0d2037 | 301 | hpp | C++ | include/timsort.hpp | Algorithms-and-Data-Structures-2021/semester-work-merge-and-insertion-sort-prod-OF | a97d75a2352d50dd99108d9ccbfd0a3cf04c1635 | [
"MIT"
] | null | null | null | include/timsort.hpp | Algorithms-and-Data-Structures-2021/semester-work-merge-and-insertion-sort-prod-OF | a97d75a2352d50dd99108d9ccbfd0a3cf04c1635 | [
"MIT"
] | null | null | null | include/timsort.hpp | Algorithms-and-Data-Structures-2021/semester-work-merge-and-insertion-sort-prod-OF | a97d75a2352d50dd99108d9ccbfd0a3cf04c1635 | [
"MIT"
] | null | null | null | #pragma once
namespace itis {
struct TimSort {
static const int RUN = 32;
static void insertionSort(int arr[], int left, int right);
static void merge(int arr[], int l, int m, int r);
static void timSort(int arr[], int n);
static void printArray(int arr[], int n);
};
} | 16.722222 | 62 | 0.627907 | Algorithms-and-Data-Structures-2021 |
e6320df0947ee3ac02fffc5347ee4dc9e9f86578 | 354 | hpp | C++ | include/xigua/symbol.hpp | LiquidHelium/Xigua | bd7d1153d483f9c07607ffd7c6b292c264793f2f | [
"MIT"
] | 2 | 2015-06-26T04:32:19.000Z | 2016-02-02T11:36:41.000Z | include/xigua/symbol.hpp | LiquidHelium/Xigua | bd7d1153d483f9c07607ffd7c6b292c264793f2f | [
"MIT"
] | null | null | null | include/xigua/symbol.hpp | LiquidHelium/Xigua | bd7d1153d483f9c07607ffd7c6b292c264793f2f | [
"MIT"
] | null | null | null | #pragma once
#include <memory>
#include "xigua/data.hpp"
#include "xigua/string.hpp"
namespace xig {
class symbol : public base_string {
public:
symbol(std::string value) : base_string(value) {}
virtual ~symbol() {}
virtual data_type type() const;
virtual const symbol &as_symbol() const;
};
extern data_ptr make_symbol(std::string str);
}
| 16.857143 | 51 | 0.711864 | LiquidHelium |
e63417cdc7cc8c0163219865231516a018739167 | 3,520 | hpp | C++ | include/ast/nodes/node_base.hpp | momikey/rhea | 6aadc65eefbb40d9dddf585c33b3225da3929abd | [
"MIT"
] | 1 | 2020-08-31T08:39:05.000Z | 2020-08-31T08:39:05.000Z | include/ast/nodes/node_base.hpp | momikey/rhea | 6aadc65eefbb40d9dddf585c33b3225da3929abd | [
"MIT"
] | null | null | null | include/ast/nodes/node_base.hpp | momikey/rhea | 6aadc65eefbb40d9dddf585c33b3225da3929abd | [
"MIT"
] | null | null | null | #ifndef RHEA_AST_NODE_BASE_HPP
#define RHEA_AST_NODE_BASE_HPP
#include <string>
#include <vector>
#include <memory>
#include <utility>
#include <tao/pegtl.hpp>
#include "../parse_tree_node.hpp"
#include "../../types/types.hpp"
#include "../../util/compat.hpp"
#include "../../visitor/visitor_fwd.hpp"
/*
* The base node for the annotated AST. This is different from
* the AST skeleton generated by the parser, but it follows the
* structure of that tree, and each node in the annotated AST
* will contain an observing pointer to the corresponding node
* in the generated AST.
*
* Note that this node and its children are *classes* rather than
* structs. This, IMO, better communicates their status as a
* polymorphic hierarchy, since the generated AST will store pointers
* to this base class and access the children through its interface.
*
* Although I haven't decided on code style guidelines for Rhea,
* I feel that the annotated AST classes should be capitalized. Again,
* this is for clarity's sake: they're not the same as, e.g., grammar
* rules.
*/
namespace rhea { namespace ast {
// The base type for all AST nodes
class ASTNode
{
public:
ASTNode(): position({}, "") {}
virtual ~ASTNode() {}
virtual std::string to_string() = 0;
virtual util::any visit(visitor::Visitor* v);
tao::pegtl::position position;
};
// "Top-level" node types
class Expression : public ASTNode
{
public:
// All expressions have a type. This may be fixed or calculated,
// so we make it a method.
virtual types::TypeInfo expression_type() { return types::UnknownType{}; }
util::any visit(visitor::Visitor* v) override;
};
class Statement : public ASTNode
{
public:
util::any visit(visitor::Visitor* v) override;
// TODO: Some statements can declare symbols. If we make a quick
// pass through some levels of the AST, we can pick these out,
// which saves us from having to forward declare as in C/C++.
// (We can implement this as a second visitor pass, done before
// the "main" one.)
};
// A lot of nodes need to store lists of children. These will
// always be unique_ptrs to AST nodes, but we may want to restrict
// that to a specific subtype, so we use a template alias here.
template <typename T>
using child_vector = std::vector<std::unique_ptr<T>>;
// std::unique_ptrs to the main node types. We use these a lot,
// so it helps to have aliases.
using node_ptr = std::unique_ptr<ASTNode>;
using expression_ptr = std::unique_ptr<Expression>;
using statement_ptr = std::unique_ptr<Statement>;
// Maker functions, in the vein of make_unique.
template <typename Expr, typename... Args>
inline expression_ptr make_expression(Args&&... args)
{ return std::make_unique<Expr>(std::forward<Args>(args)...); }
template <typename Stmt, typename... Args>
inline statement_ptr make_statement(Args&&... args)
{ return std::make_unique<Stmt>(std::forward<Args>(args)...); }
// Functions can be of different types. This enum allows us
// to choose which type.
enum class FunctionType
{
Basic, // i.e., not special
Predicate, // implied boolean return type
Operator, // operators are always called implicitly
Unchecked // can't take conditions
};
}}
#endif /* RHEA_AST_NODE_BASE_HPP */ | 34.509804 | 82 | 0.663068 | momikey |
e637ca6c7bb4b91dc04c81efdba86baa4e826227 | 2,891 | cpp | C++ | tools/CoronaBuilder/Rtt_AppPackagerLinuxFactory.cpp | joehinkle11/corona | 530320beaa518a2b82fa8beb2a92f3be6b56a00e | [
"MIT"
] | 1,968 | 2018-12-30T21:14:22.000Z | 2022-03-31T23:48:16.000Z | tools/CoronaBuilder/Rtt_AppPackagerLinuxFactory.cpp | joehinkle11/corona | 530320beaa518a2b82fa8beb2a92f3be6b56a00e | [
"MIT"
] | 303 | 2019-01-02T19:36:43.000Z | 2022-03-31T23:52:45.000Z | tools/CoronaBuilder/Rtt_AppPackagerLinuxFactory.cpp | joehinkle11/corona | 530320beaa518a2b82fa8beb2a92f3be6b56a00e | [
"MIT"
] | 254 | 2019-01-02T19:05:52.000Z | 2022-03-30T06:32:28.000Z | //////////////////////////////////////////////////////////////////////////////
//
// This file is part of the Corona game engine.
// For overview and more information on licensing please refer to README.md
// Home page: https://github.com/coronalabs/corona
// Contact: support@coronalabs.com
//
//////////////////////////////////////////////////////////////////////////////
#include "Core/Rtt_Build.h"
#include "Rtt_AppPackagerFactory.h"
#include "Rtt_LinuxAppPackager.h"
#include <string>
// ----------------------------------------------------------------------------
namespace Rtt
{
// ----------------------------------------------------------------------------
#if defined(CORONABUILDER_LINUX)
AppPackagerParams*
AppPackagerFactory::CreatePackagerParamsLinux(
lua_State *L,
int index,
TargetDevice::Platform targetPlatform,
TargetDevice::Version targetPlatformVersion,
const char *appName,
const char *version,
const char *certificatePath,
const char *projectPath,
const char *dstPath,
const char *sdkPath,
const char *customBuildId,
const char *templateType ) const
{
AppPackagerParams *result = NULL;
if(targetPlatform != TargetDevice::kLinuxPlatform)
{
Rtt_ASSERT_NOT_REACHED();
return NULL;
}
bool includeStandardResources = true;
lua_getfield(L, index, "includeWidgetResources");
if(lua_type(L, -1) == LUA_TBOOLEAN)
{
includeStandardResources = lua_toboolean(L, -1);
}
lua_pop(L, 1);
String linuxtemplate;
lua_getfield(L, index, "linuxtemplate");
if(lua_type(L, -1) == LUA_TSTRING)
{
linuxtemplate.Set(lua_tostring(L, -1));
}
lua_pop(L, 1);
result = new LinuxAppPackagerParams(appName,
version,
NULL,
NULL,
projectPath,
dstPath,
NULL,
targetPlatform,
targetPlatformVersion,
TargetDevice::kLinuxPlatform,
customBuildId,
NULL,
"bundleId",
true,
linuxtemplate.GetString(),
includeStandardResources, false, false);
if ( ! result )
{
fprintf( stderr, "ERROR: Unsupported platform: %s\n", TargetDevice::StringForPlatform( targetPlatform ) );
}
return result;
}
#endif // defined(CORONABUILDER_LINUX)
// ----------------------------------------------------------------------------
} // namespace Rtt
// ----------------------------------------------------------------------------
| 30.114583 | 109 | 0.457973 | joehinkle11 |
e63f3938979647ce2b55bf1bbc754db53ab5bbe7 | 1,760 | cpp | C++ | The_Eye/src/PID.cpp | michprev/drone | 51c659cdd4e1d50446a563bb11e800defda9a298 | [
"MIT"
] | 2 | 2017-06-03T01:07:16.000Z | 2017-07-14T17:49:16.000Z | The_Eye/src/PID.cpp | michprev/drone | 51c659cdd4e1d50446a563bb11e800defda9a298 | [
"MIT"
] | 5 | 2017-04-24T20:29:04.000Z | 2017-06-26T17:40:53.000Z | The_Eye/src/PID.cpp | michprev/drone | 51c659cdd4e1d50446a563bb11e800defda9a298 | [
"MIT"
] | null | null | null | /*
* PID.cpp
*
* Created on: 14. 7. 2017
* Author: michp
*/
#include <PID.h>
namespace flyhero {
// assume that PID will be computed at 1 kHz
PID::PID(float i_max, float Kp, float Ki, float Kd)
: d_term_lpf(Biquad_Filter::FILTER_LOW_PASS, 1000, 20)
{
this->last_t = 0;
this->integrator = 0;
this->Kp = Kp;
this->Ki = Ki;
this->Kd = Kd;
this->i_max = i_max;
this->last_d = NAN;
this->last_error = NAN;
}
float PID::Get_PID(float error) {
// ticks in us
float dt = (Timer::Get_Tick_Count() - this->last_t) * 0.000001;
float output = 0;
if (this->last_t == 0 || dt > 1000) {
this->integrator = 0;
dt = 0;
}
this->last_t = Timer::Get_Tick_Count();
// proportional component
output += error * this->Kp;
// integral component
if (this->Ki != 0 && dt > 0) {
this->integrator += error * this->Ki * dt;
if (this->integrator < -this->i_max)
this->integrator = -this->i_max;
if (this->integrator > this->i_max)
this->integrator = this->i_max;
output += this->integrator;
}
// derivative component
if (this->Kd != 0 && dt > 0) {
float derivative;
if (std::isnan(this->last_d)) {
derivative = 0;
this->last_d = 0;
}
else
derivative = (error - this->last_error) / dt;
// apply 20 Hz biquad LPF
derivative = this->d_term_lpf.Apply_Filter(derivative);
this->last_error = error;
this->last_d = derivative;
output += derivative * this->Kd;
}
return output;
}
void PID::Set_Kp(float Kp) {
this->Kp = Kp;
}
void PID::Set_Ki(float Ki) {
this->Ki = Ki;
}
void PID::Set_Kd(float Kd) {
this->Kd = Kd;
}
void PID::Set_I_Max(float i_max) {
this->i_max = i_max;
}
} /* namespace flyhero */
| 18.924731 | 65 | 0.586932 | michprev |
e645edf799785e82b1db9cdb60ec5f2b15a9d2f2 | 3,796 | cpp | C++ | sources/libcpp55iip_scan/tw_win_l2_dss_cap_get_ctnr_onev.cpp | Savraska2/GTS | 78c8b4d634f1379eb3e33642716717f53bf7e1ad | [
"BSD-3-Clause"
] | 61 | 2016-03-26T03:04:43.000Z | 2021-09-17T02:11:18.000Z | sources/libcpp55iip_scan/tw_win_l2_dss_cap_get_ctnr_onev.cpp | sahwar/GTS | b25734116ea81eb0d7e2eabc8ce16cdd1c8b22dd | [
"BSD-3-Clause"
] | 92 | 2016-04-10T23:40:22.000Z | 2022-03-11T21:49:12.000Z | sources/libcpp55iip_scan/tw_win_l2_dss_cap_get_ctnr_onev.cpp | sahwar/GTS | b25734116ea81eb0d7e2eabc8ce16cdd1c8b22dd | [
"BSD-3-Clause"
] | 18 | 2016-03-26T11:19:14.000Z | 2021-08-07T00:26:02.000Z | #include "pri.h"
#include "tw_win_l2_dss.h"
/* get onevalue(container) */
int tw_win_l2_dss::_cap_get_ctnr_onevalue( TW_UINT16 ui16_cap, TW_ONEVALUE *p_tw_onevalue )
{
TW_CAPABILITY tw_capability;
TW_ONEVALUE *p_tw_ov;
/* TWAIN機器からデータを取ってくる */
if (OK != this->_cap_get_ctnr( ui16_cap, &tw_capability ) ) {
pri_funct_err_bttvr(
"Error : this->_cap_get_ctnr() returns NG." );
return NG;
}
/* データのコンテナタイプが違う */
if (TWON_ONEVALUE != tw_capability.ConType) {
pri_funct_err_bttvr(
"Error : tw_capability.ConType is not TWON_ONEVALUE." );
/* Windows 特有のおまじない1/3 */
GlobalFree( (HANDLE)tw_capability.hContainer );
return NG;
}
/* Windows 特有のおまじない2/3 */
p_tw_ov = (pTW_ONEVALUE)GlobalLock(
(HANDLE)tw_capability.hContainer
);
/* データをコピーする */
(*p_tw_onevalue) = (*p_tw_ov);
/* Windows 特有のおまじない3/3 */
GlobalUnlock( (HANDLE)tw_capability.hContainer );
GlobalFree( (HANDLE)tw_capability.hContainer );
return OK;
}
/*--------------------------------------------------------*/
/* get_current onevalue(container) */
int tw_win_l2_dss::_cap_getcrnt_ctnr_onevalue( TW_UINT16 ui16_cap, TW_ONEVALUE *p_tw_onevalue )
{
TW_CAPABILITY tw_capability;
TW_ONEVALUE *p_tw_ov;
/* TWAIN機器からデータを取ってくる */
if (OK != this->_cap_getcrnt_ctnr(ui16_cap,&tw_capability)) {
pri_funct_err_bttvr(
"Error : this->_cap_getcrnt_ctnr() returns NG." );
return NG;
}
/* データのコンテナタイプが違う */
if (TWON_ONEVALUE != tw_capability.ConType) {
pri_funct_err_bttvr(
"Error : tw_capability.ConType is not TWON_ONEVALUE." );
/* Windows 特有のおまじない1/3 */
GlobalFree( (HANDLE)tw_capability.hContainer );
return NG;
}
/* Windows 特有のおまじない2/3 */
p_tw_ov = (pTW_ONEVALUE)GlobalLock(
(HANDLE)tw_capability.hContainer
);
/* データをコピーする */
(*p_tw_onevalue) = (*p_tw_ov);
/* Windows 特有のおまじない3/3 */
GlobalUnlock( (HANDLE)tw_capability.hContainer );
GlobalFree( (HANDLE)tw_capability.hContainer );
return OK;
}
/*--------------------------------------------------------*/
int tw_win_l2_dss::_cap_get_ctnr_onevalue_bool( TW_UINT32 *ui32p_val, TW_UINT16 ui16_cap, char *cp_cap_name )
{
TW_ONEVALUE tw_onevalue;
if (OK != this->_cap_get_ctnr_onevalue(
ui16_cap, &tw_onevalue )) {
pri_funct_err_bttvr(
"Error : this->_cap_get_ctnr_onevalue(%s<%u>,) returns NG.",
cp_cap_name,
ui16_cap
);
return NG;
}
if (TWTY_BOOL != tw_onevalue.ItemType) {
pri_funct_err_bttvr(
"Error : %s tw_onevalue.ItemType is not TWTY_BOOL.",
cp_cap_name );
return NG;
}
*ui32p_val = tw_onevalue.Item;
return OK;
}
int tw_win_l2_dss::_cap_get_ctnr_onevalue_fix32( double *dp_val, TW_UINT16 ui16_cap, char *cp_cap_name )
{
TW_ONEVALUE tw_onevalue;
if (OK != this->_cap_get_ctnr_onevalue(
ui16_cap, &tw_onevalue )) {
pri_funct_err_bttvr(
"Error : this->_cap_get_ctnr_onevalue(%s<%u>,) returns NG.",
cp_cap_name,
ui16_cap
);
return NG;
}
if (TWTY_FIX32 != tw_onevalue.ItemType) {
pri_funct_err_bttvr(
"Error : %s tw_onevalue.ItemType is not TWTY_FIX32.",
cp_cap_name );
return NG;
}
this->_fix32_to_double(
(TW_FIX32 *)&(tw_onevalue.Item), dp_val );
return OK;
}
/*--------------------------------------------------------*/
int tw_win_l2_dss::_cap_getcrnt_ctnr_onevalue_ui16( TW_UINT16 *ui16p_val, TW_UINT16 ui16_cap, char *cp_cap_name )
{
TW_ONEVALUE tw_onevalue;
if (OK != this->_cap_getcrnt_ctnr_onevalue(
ui16_cap, &tw_onevalue )) {
pri_funct_err_bttvr(
"Error : this->_cap_getcrnt_ctnr_onevalue(%s<%u>,) returns NG.",
cp_cap_name,
ui16_cap
);
return NG;
}
if (TWTY_UINT16 != tw_onevalue.ItemType) {
pri_funct_err_bttvr(
"Error : %s tw_onevalue.ItemType is not TWTY_UINT16.",
cp_cap_name );
return NG;
}
/* ui32-->ui16だがオーバーフローの問題が起こる可能性は低い */
*ui16p_val = (unsigned short)(tw_onevalue.Item);
return OK;
}
| 23.288344 | 113 | 0.683878 | Savraska2 |
e645fba834ebd867bce675d92fdaa987a003b6e0 | 195 | cpp | C++ | test/unit-tests/cli/array_info_command_test.cpp | YongJin-Cho/poseidonos | c07a0240316d4536aa09f22d7977604f3650d752 | [
"BSD-3-Clause"
] | null | null | null | test/unit-tests/cli/array_info_command_test.cpp | YongJin-Cho/poseidonos | c07a0240316d4536aa09f22d7977604f3650d752 | [
"BSD-3-Clause"
] | null | null | null | test/unit-tests/cli/array_info_command_test.cpp | YongJin-Cho/poseidonos | c07a0240316d4536aa09f22d7977604f3650d752 | [
"BSD-3-Clause"
] | null | null | null | #include "src/cli/array_info_command.h"
#include <gtest/gtest.h>
namespace pos_cli
{
TEST(ArrayInfoCommand, ArrayInfoCommand_)
{
}
TEST(ArrayInfoCommand, Execute_)
{
}
} // namespace pos_cli
| 12.1875 | 41 | 0.753846 | YongJin-Cho |
e647699d6383da70228636b92a12954a852576e0 | 5,309 | cpp | C++ | src/bsa.cpp | Guekka/libbsarch-cpp | ad435d488e9a816e0109a6f464961d177d3b61f4 | [
"MIT"
] | 1 | 2021-06-16T15:49:07.000Z | 2021-06-16T15:49:07.000Z | src/bsa.cpp | Guekka/libbsarch-cpp | ad435d488e9a816e0109a6f464961d177d3b61f4 | [
"MIT"
] | null | null | null | src/bsa.cpp | Guekka/libbsarch-cpp | ad435d488e9a816e0109a6f464961d177d3b61f4 | [
"MIT"
] | null | null | null | #include "bsa.hpp"
#include "for_each.hpp"
#include <fstream>
#include <numeric>
namespace libbsarch {
/* Properties */
fs::path bsa::get_filename() const
{
wchar_t name[max_string_buffer_size];
bsa_filename_get(archive_.get(), max_string_buffer_size, name);
return name;
}
bsa_archive_type_t bsa::get_type() const
{
return bsa_archive_type_get(archive_.get());
}
uint32_t bsa::get_version() const
{
return bsa_version_get(archive_.get());
}
fs::path bsa::get_format_name() const
{
wchar_t format_name[max_string_buffer_size];
bsa_format_name_get(archive_.get(), max_string_buffer_size, format_name);
return format_name;
}
uint32_t bsa::get_file_count() const
{
return bsa_file_count_get(archive_.get());
}
uint32_t bsa::get_archive_flags() const
{
return bsa_archive_flags_get(archive_.get());
}
void bsa::set_archive_flags(uint32_t flags)
{
bsa_archive_flags_set(archive_.get(), flags);
}
uint32_t bsa::get_file_flags() const
{
return bsa_file_flags_get(archive_.get());
}
void bsa::set_file_flags(uint32_t flags)
{
bsa_file_flags_set(archive_.get(), flags);
}
void bsa::set_compressed(bool value)
{
bsa_compress_set(archive_.get(), value);
}
void bsa::set_share_data(bool value)
{
bsa_share_data_set(archive_.get(), value);
}
bool bsa::get_compressed() const
{
return bsa_compress_get(archive_.get());
}
bool bsa::get_share_data() const
{
return bsa_share_data_get(archive_.get());
}
void bsa::load(const fs::path &archive_path)
{
const auto &result = bsa_load_from_file(archive_.get(), archive_path.wstring().c_str());
checkResult(result);
}
void bsa::close()
{
bsa_close(archive_.get());
}
extracted_data bsa::extract_to_memory(file_record record) const
{
const auto &result = bsa_extract_file_data_by_record(archive_.get(), record.value);
checkResult(result);
return extracted_data(result.buffer, archive_.get());
}
extracted_data bsa::extract_to_memory(const fs::path &relative_path) const
{
const auto &result = bsa_extract_file_data_by_filename(archive_.get(), relative_path.wstring().c_str());
checkResult(result);
return extracted_data(result.buffer, archive_.get());
}
void bsa::extract_to_disk(const fs::path &relative_path,
const fs::path &absolute_path,
bool overwrite_existing) const
{
auto record = find_file_record(relative_path);
extract_to_disk(record, absolute_path, overwrite_existing);
}
void bsa::extract_to_disk(file_record record,
const std::filesystem::path &absolute_path,
bool overwrite_existing) const
{
{
static std::mutex mut;
std::lock_guard g(mut);
const bool exist = fs::exists(absolute_path);
if (exist && !overwrite_existing)
return;
if (exist)
fs::remove(absolute_path);
}
auto data = extract_to_memory(record);
std::fstream file(absolute_path, std::ios::out | std::ios::binary);
file.write(static_cast<const char *>(data.get_buffer()), data.get_size());
}
void bsa::extract_all_to_disk(const fs::path &directory, bool overwrite_current_files) const
{
std::vector<uint32_t> indexes(get_file_count());
std::iota(indexes.begin(), indexes.end(), 0);
for_each(indexes.cbegin(), indexes.cend(), [this, overwrite_current_files, directory](auto &&idx) {
auto record = get_file_record(idx);
auto relative_path = get_relative_path(idx);
fs::path absolute_path = directory / relative_path;
fs::path absolute_directory = fs::path(absolute_path).remove_filename();
{
static std::mutex mut;
std::lock_guard g(mut);
fs::create_directories(absolute_directory);
}
try
{
extract_to_disk(record, absolute_path, overwrite_current_files);
}
catch (const std::exception &e)
{
std::cerr << e.what() << std::endl;
}
});
}
void bsa::iterate_files(bsa_file_iteration_proc_t file_iteration_proc, void *context) const
{
bsa_iterate_files(archive_.get(), file_iteration_proc, context);
}
file_record bsa::get_file_record(uint32_t index) const
{
return {bsa_get_file_record(archive_.get(), index)};
}
file_record bsa::find_file_record(const fs::path &filename) const
{
return {bsa_find_file_record(archive_.get(), filename.wstring().c_str())};
}
std::filesystem::path bsa::get_relative_path(uint32_t index) const
{
bsa_entry_list list;
const auto &result = bsa_get_resource_list(archive_.get(), list.get_unchecked().get(), L"");
checkResult(result);
return list.get(index);
}
std::vector<fs::path> bsa::list_files() const
{
bsa_entry_list list;
const auto &result = bsa_get_resource_list(archive_.get(), list.get_unchecked().get(), L"");
checkResult(result);
return list.list();
}
const detail::bsa_wrapper &bsa::get_unchecked() const
{
return archive_;
}
detail::bsa_wrapper &bsa::get_unchecked()
{
return archive_;
}
} // namespace libbsarch
| 25.524038 | 109 | 0.661141 | Guekka |
e64a948846ce357c12da9d69298cc8eb2ba85662 | 1,677 | cpp | C++ | leetcode-cpp/GoatLatin_824.cpp | emacslisp/cpp | 8230f81117d6f64adaa1696b0943cdb47505335a | [
"Apache-2.0"
] | null | null | null | leetcode-cpp/GoatLatin_824.cpp | emacslisp/cpp | 8230f81117d6f64adaa1696b0943cdb47505335a | [
"Apache-2.0"
] | null | null | null | leetcode-cpp/GoatLatin_824.cpp | emacslisp/cpp | 8230f81117d6f64adaa1696b0943cdb47505335a | [
"Apache-2.0"
] | null | null | null | #include <vector>
#include <iostream>
#include <climits>
#include <algorithm>
#include <queue>
#include <stack>
#include <map>
#define Max(a, b) a > b ? a : b
#define Min(a, b) a < b ? a : b
using namespace std;
class Solution {
public:
vector<string> splitByChar(string s, char c) {
vector<string> result;
string t;
for(int i=0;i<s.size();i++) {
if(s[i] != c)
t.push_back(s[i]);
else {
result.push_back(t);
t = "";
}
}
if(t.size() > 0)
result.push_back(t);
return result;
}
char toLower(char c) {
if (c >= 'A' && c<='Z') {
c = c - ('Z' - 'z');
}
return c;
}
string toGoatLatin(string S) {
vector<string> t = splitByChar(S, ' ');
map<char, int> c = { {'a', 1}, {'o',1}, {'e',1}, {'i',1}, {'u', 1}};
string result;
for(int i=0;i<t.size();i++) {
string x = t[i];
if(x.size() >= 1) {
if (c.count(toLower(x[0])) > 0) {
x+="ma";
} else {
x.push_back(x[0]);
x+="ma";
x = x.substr(1);
}
for(int m=0;m<=i;m++) {
x.push_back('a');
}
result += (x + " ");
}
}
return result.substr(0, result.size() - 1);
}
};
int main() {
Solution s;
vector<int> c
{
4,5,6,7,0,2,1,3
};
string str = "I speak Goat Latin";
string result = s.toGoatLatin(str);
cout<<result<<endl;
} | 22.662162 | 76 | 0.394156 | emacslisp |
e64bece9fc801f3f8e96ca46aa7fcf92b6f95146 | 2,101 | cpp | C++ | src/gpio_reader.cpp | botamochi6277/ros2_pigpio | 9f0a78ffd9092f628fae66897f96bdf0bfae8aca | [
"MIT"
] | 2 | 2021-06-10T21:17:17.000Z | 2022-02-22T04:39:16.000Z | src/gpio_reader.cpp | botamochi6277/ros2_pigpio | 9f0a78ffd9092f628fae66897f96bdf0bfae8aca | [
"MIT"
] | null | null | null | src/gpio_reader.cpp | botamochi6277/ros2_pigpio | 9f0a78ffd9092f628fae66897f96bdf0bfae8aca | [
"MIT"
] | 1 | 2021-02-19T13:35:55.000Z | 2021-02-19T13:35:55.000Z | /**
* @file gpio_reader.cpp
*
* @brief ROS2 Talker to read inputted digital signals.
*
**/
#include <chrono>
#include <memory>
#include <thread>
#include <sstream>
#include <iomanip>
#include <pigpiod_if2.h>
#include "rclcpp/rclcpp.hpp"
#include "std_msgs/msg/bool.hpp"
using namespace std::chrono_literals;
class DigitalReader : public rclcpp::Node
{
private:
int pi_;
int pin_;
bool is_pull_up_;
rclcpp::TimerBase::SharedPtr timer_;
rclcpp::Publisher<std_msgs::msg::Bool>::SharedPtr publisher_;
size_t count_;
void timer_callback()
{
auto message = std_msgs::msg::Bool();
message.data = gpio_read(pi_, pin_);
RCLCPP_INFO(this->get_logger(), "Publishing: '%d'", message.data);
publisher_->publish(message);
}
public:
DigitalReader()
: Node("gpio_publisher"), count_(0)
{
this->declare_parameter<int>("pin", 23);
this->declare_parameter<bool>("is_pull_up", true);
this->get_parameter("pin", pin_);
this->get_parameter("is_pull_up", is_pull_up_);
if (is_pull_up_)
{
RCLCPP_INFO(this->get_logger(), "Read GPIO-%02d (PULL_UP)", pin_);
}
else
{
RCLCPP_INFO(this->get_logger(), "Read GPIO-%02d (PULL_DOWN)", pin_);
}
pi_ = pigpio_start(NULL, NULL); /* Connect to Pi. */
if (pi_ < 0)
{
RCLCPP_ERROR(this->get_logger(), "cannot connect pigpiod");
rclcpp::shutdown();
exit(1);
}
else
{
set_mode(pi_, pin_, PI_INPUT);
if (is_pull_up_)
{
set_pull_up_down(pi_, pin_, PI_PUD_UP);
}
else
{
set_pull_up_down(pi_, pin_, PI_PUD_OFF);
}
std::stringstream ss;
ss << "gpio_input_" << std::setw(2) << pin_;
publisher_ = this->create_publisher<std_msgs::msg::Bool>(ss.str(), 10);
timer_ = this->create_wall_timer(
500ms, std::bind(&DigitalReader::timer_callback, this));
}
}
~DigitalReader()
{
pigpio_stop(pi_);
}
};
int main(int argc, char **argv)
{
rclcpp::init(argc, argv);
rclcpp::spin(std::make_shared<DigitalReader>());
rclcpp::shutdown();
return 0;
} | 23.087912 | 77 | 0.62732 | botamochi6277 |
e64dbd67c636d253f0b1b6b36fd59d69f0acf940 | 6,651 | cpp | C++ | src/EnterpriseStateClassify/enterprisestateclassify.cpp | microsoft/EnterpriseStateClassify | e7749641c308d8554f2a886cbe2a78282d9aab7d | [
"MIT"
] | 1 | 2020-05-09T09:32:54.000Z | 2020-05-09T09:32:54.000Z | src/EnterpriseStateClassify/enterprisestateclassify.cpp | microsoft/EnterpriseStateClassify | e7749641c308d8554f2a886cbe2a78282d9aab7d | [
"MIT"
] | null | null | null | src/EnterpriseStateClassify/enterprisestateclassify.cpp | microsoft/EnterpriseStateClassify | e7749641c308d8554f2a886cbe2a78282d9aab7d | [
"MIT"
] | 3 | 2020-07-31T10:12:15.000Z | 2021-11-10T08:25:02.000Z | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
//
// EnterpriseStateClassify Usage:
// EnterpriseStateClassify Connect <FLAGS> <TARGET> - Get enterprise state of target
// EnterpriseStateClassify ConnectLoop <FLAGS> <TARGET> - Get enterprise state of target 20 times every 1.5 seconds
// EnterpriseStateClassify ConnectLoopFast <FLAGS> <TARGET> - Get enterprise state of target 20 times
//
#include <netfw.h>
#include <stdio.h>
#include <sddl.h>
//ERROR Handling
#define FAIL_IF_DWERR(X) \
if (X != NO_ERROR) goto CLEAN;
typedef enum _OP_TYPE
{
OP_TYPE_INVALID = 0,
OP_TYPE_CONNECT,
OP_TYPE_LISTEN,
OP_TYPE_SOCKETCREATION,
OP_TYPE_CONNECTLOOP,
OP_TYPE_CONNECTLOOPFAST
} OP_TYPE;
typedef enum _ARG_TYPE
{
ARG_TYPE_OPERATION = 1,
ARG_TYPE_FLAGS,
ARG_TYPE_TARGET,
ARG_TYPE_MAX,
ARG_TYPE_HELP = 1
} ARG_TYPE;
//
// Function pointer definition for NetworkIsolationGetEnterpriseIdAsync
//
typedef DWORD(NTAPI *PNetworkIsolationGetEnterpriseIdAsync) (
_In_z_ LPCWSTR,
_In_ DWORD dwFlags,
_In_opt_ void * context,
_In_ PNETISO_EDP_ID_CALLBACK_FN callback,
_Out_ HANDLE *hOperation
);
//
// Function pointer definition for NetworkIsolationGetEnterpriseIdClose
//
typedef DWORD(NTAPI *PNetworkIsolationGetEnterpriseIdClose) (
_In_ HANDLE hOperation,
BOOL bWaitForOperation
);
void CALLBACK
NetworkIsolationGetEnterpriseIdSyncCallback(
_Inout_opt_ void *context,
_In_opt_z_ const LPCWSTR wszEnterpriseId,
_In_ DWORD dwErr
)
{
size_t copyLength = 0;
if (context == NULL)
{
return;
}
if (wszEnterpriseId == NULL)
{
return;
}
*((LPWSTR *)context) = NULL;
copyLength = wcslen(wszEnterpriseId) + 1;
(*(LPWSTR *)context) = new wchar_t[copyLength];
dwErr = wcscpy_s((*(LPWSTR *)context), copyLength, wszEnterpriseId);
if (dwErr != NO_ERROR)
{
printf("ERROR occured in callback %d - %X\n", dwErr, dwErr);
}
}
DWORD
FwDiagnoseConnectTarget(
_In_ LPWSTR wszTarget,
_In_ DWORD dwFlags
)
{
DWORD dwErr = NO_ERROR;
LPWSTR wszEnterpriseId = NULL;
HANDLE hOperation = NULL;
HMODULE hModule = NULL;
PNetworkIsolationGetEnterpriseIdAsync pFuncNetworkIsolationGetEnterpriseIdAsync = NULL;
PNetworkIsolationGetEnterpriseIdClose pFuncNetworkIsolationGetEnterpriseIdClose = NULL;
hModule = LoadLibrary(L"firewallapi.dll");
if (hModule != NULL)
{
pFuncNetworkIsolationGetEnterpriseIdAsync = (PNetworkIsolationGetEnterpriseIdAsync) GetProcAddress(
hModule,
"NetworkIsolationGetEnterpriseIdAsync"
);
pFuncNetworkIsolationGetEnterpriseIdClose = (PNetworkIsolationGetEnterpriseIdClose) GetProcAddress(
hModule,
"NetworkIsolationGetEnterpriseIdClose"
);
}
if (pFuncNetworkIsolationGetEnterpriseIdAsync != NULL &&
pFuncNetworkIsolationGetEnterpriseIdClose != NULL)
{
dwErr = pFuncNetworkIsolationGetEnterpriseIdAsync(
wszTarget,
dwFlags,
&wszEnterpriseId,
(PNETISO_EDP_ID_CALLBACK_FN)
NetworkIsolationGetEnterpriseIdSyncCallback,
&hOperation
);
FAIL_IF_DWERR(dwErr);
dwErr = pFuncNetworkIsolationGetEnterpriseIdClose(
hOperation,
TRUE
);
FAIL_IF_DWERR(dwErr);
}
if (wszEnterpriseId != NULL)
{
wprintf(L"\
\nThe target: %s\n Enterprise state: EnterpriseId=%s\n", wszTarget, wszEnterpriseId );
}
else
{
wprintf(L"\
\nThe target %s\n Enterprise state: PERSONAL \n", wszTarget );
}
CLEAN:
if (hModule != NULL)
{
FreeLibrary(hModule);
}
if (dwErr != NO_ERROR)
{
wprintf(L"\
\nERROR %s couldn't be diagnosed\n", wszTarget );
}
return dwErr;
}
//+----------------------------------------------------
//
// Main Function of our tool.
// This function parses the input, preparse the data, and performs the
// instructed management operation on the specified target.
//
//+---------------------------------------------------
int __cdecl wmain(int argc, wchar_t **argv)
{
DWORD dwStatus = NO_ERROR;
OP_TYPE OpType = OP_TYPE_INVALID;
WCHAR *wszTarget = NULL;
DWORD dwFlags = 0;
DWORD i = 0;
if (lstrcmpiW( L"/?", argv[ARG_TYPE_HELP]) == 0)
{
wprintf(L"\
\nUsage:\
\n EnterpriseStateClassify <OPERATION> <FLAGS> <TARGET>\
\n <OPERATION> .- Connect/ConnectLoop/ConnectLoopFast \
\n <FLAGS> .- flags to pass \
\n <TARGET> .- Target to verify as a http proxy\n" );
return 0;
}
if (argc < ARG_TYPE_MAX-1)
{
wprintf(L"\
\nUsage:\
\n EnterpriseStateClassify <OPERATION> <FLAGS> <TARGET>\
\n <OPERATION> .- Connect/ConnectLoop/ConnectLoopFast \
\n <FLAGS> .- flags to pass \
\n <TARGET> .- Target to verify as a http proxy\n" );
dwStatus = ERROR_INVALID_PARAMETER;
}
FAIL_IF_DWERR(dwStatus);
if (lstrcmpiW( L"Connect", argv[ARG_TYPE_OPERATION] ) == 0)
{
OpType = OP_TYPE_CONNECT;
}
else if (lstrcmpiW( L"ConnectLoop", argv[ARG_TYPE_OPERATION] ) == 0)
{
OpType = OP_TYPE_CONNECTLOOP;
}
else if (lstrcmpiW( L"ConnectLoopFast", argv[ARG_TYPE_OPERATION] ) == 0)
{
OpType = OP_TYPE_CONNECTLOOPFAST;
}
else
{
dwStatus = ERROR_INVALID_PARAMETER;
FAIL_IF_DWERR(dwStatus);
}
//
// Read the flags
//
swscanf_s(argv[ARG_TYPE_FLAGS], L"%d", &dwFlags);
//
// Prepare data for doing the work
//
if (OpType == OP_TYPE_CONNECT ||
OpType == OP_TYPE_CONNECTLOOP ||
OpType == OP_TYPE_CONNECTLOOPFAST)
{
wszTarget = argv[ARG_TYPE_TARGET];
}
//
// Perform the requested work
//
if (OpType == OP_TYPE_CONNECT)
{
dwStatus = FwDiagnoseConnectTarget(wszTarget, dwFlags);
FAIL_IF_DWERR(dwStatus);
}
else if (OpType == OP_TYPE_CONNECTLOOP ||
OpType == OP_TYPE_CONNECTLOOPFAST)
{
for (i = 0; i < 20; i++)
{
dwStatus = FwDiagnoseConnectTarget(wszTarget, dwFlags);
if (OpType == OP_TYPE_CONNECTLOOP)
{
Sleep(1500);
}
}
}
CLEAN:
//
// Handle Errors
//
if (dwStatus != NO_ERROR)
{
printf("ERROR occured %d - %X\n", dwStatus, dwStatus);
}
return 0;
}
| 25.288973 | 117 | 0.616298 | microsoft |
e65354b81f42d1761eba0f59ee2aa38135a6c8a0 | 8,797 | hpp | C++ | csf_workspace/csf/include/core/module/device/connect/csf_connect_buffer.hpp | Kitty-Kitty/csf_library | 011e56fb8b687818d20b9998a0cdb72332375534 | [
"BSD-2-Clause"
] | 2 | 2019-12-17T13:16:48.000Z | 2019-12-17T13:16:51.000Z | csf_workspace/csf/include/core/module/device/connect/csf_connect_buffer.hpp | Kitty-Kitty/csf_library | 011e56fb8b687818d20b9998a0cdb72332375534 | [
"BSD-2-Clause"
] | null | null | null | csf_workspace/csf/include/core/module/device/connect/csf_connect_buffer.hpp | Kitty-Kitty/csf_library | 011e56fb8b687818d20b9998a0cdb72332375534 | [
"BSD-2-Clause"
] | null | null | null | /*******************************************************************************
*
*Copyright: armuxinxian@aliyun.com
*
*Author: f
*
*File name: csf_connect_buffer.hpp
*
*Version: 1.0
*
*Date: 20-10月-2018 21:30:24
*
*Description: Class(csf_connect_buffer) 为方便实现各种网络操作而定义的该结构,主要为网络连接发送接收而使用buffer信息。
该数据结构主要是对unsigned char*、csf_buffer、csf_csfstring、csf_chain等原来类型,针对网络发送需求的特殊封闭。
*
*Others:
*
*History:
*
*******************************************************************************/
#if !defined(CSF_CONNECT_BUFFER_H_INCLUDED_)
#define CSF_CONNECT_BUFFER_H_INCLUDED_
#include "csf_typedef.h"
namespace csf
{
namespace core
{
namespace module
{
namespace connect
{
/**
* 为方便实现各种网络操作而定义的该结构,主要为网络连接发送接收而使用buffer信息。
* 该数据结构主要是对unsigned char*、csf_buffer、csf_csfstring、csf_chain等原来类型,针对网络发送需求的特殊封闭。
* @author f
* @version 1.0
* @created 20-10月-2018 21:30:24
*/
template<typename ValueType = csf_buffer>
class csf_connect_buffer
{
public:
inline explicit csf_connect_buffer()
: m_container(csf_nullptr)
, m_length(0)
, m_is_sync(csf_false)
, m_is_free(csf_false)
, m_is_filled(csf_false) {
}
/**
* 主要功能是:根据对应长度创建csf_connect_buffer
* 返回:无
*
* @param len 表示需要发送的缓存长度
*/
inline explicit csf_connect_buffer(const csf_uint32 len)
: csf_connect_buffer(new ValueType(len), len) {
m_is_free = csf_true;
}
/**
* 主要功能是:根据buufer对象和对应长度创建csf_connect_buffer
* 返回:无
*
* @param buffer 表示csf_connect_buffer的宿主对象地址
* @param len 表示需要发送的缓存长度
*/
inline explicit csf_connect_buffer(ValueType* buffer, const csf_uint32 len)
: m_container(buffer)
, m_length(len)
, m_is_sync(csf_false)
, m_is_free(csf_false)
, m_is_filled(csf_false) {
}
virtual ~csf_connect_buffer() {
destroy();
}
/**
* 表示csf_connect_buffer所包含的实际需要被操作的宿主容器对象,例如:csf_buffer、csf_csfstring对象等
*
* @param new_value
*/
inline void set_container(ValueType* new_value) {
if (csf_nullptr != new_value) {
set_container(new_value, new_value->length());
}
}
/**
* 表示csf_connect_buffer所包含的实际需要被操作的宿主容器对象,例如:csf_buffer、csf_csfstring对象等
*
* @param new_value 表示csf_connect_buffer的宿主对象地址
* @param len 表示需要发送的缓存长度
*/
inline void set_container(ValueType* new_value, const csf_uint32 len) {
m_container = new_value;
set_is_free(csf_false);
set_length(len);
}
/**
* 表示csf_connect_buffer所包含的实际需要被操作的宿主容器对象,例如:csf_buffer、csf_csfstring对象等
*/
inline ValueType* get_container() {
return m_container;
}
/**
* 表示当前的缓存数据内容
*/
inline csf_uchar* get_buffer() {
if (csf_nullptr != get_container()) {
return get_container()->get_buffer();
}
return csf_nullptr;
}
/**
* 表示是否采用同步的方式发送,false表示异步;true表示同步;默认为异步方式
*
* @param new_value 表示是否采用同步的方式发送,false表示异步;true表示同步;
*/
inline void set_is_sync(const csf_bool new_value) {
m_is_sync = new_value;
}
/**
* 表示是否采用同步的方式发送,false表示异步;true表示同步;默认为异步方式
*/
inline csf_bool get_is_sync() {
return m_is_sync;
}
/**
* 表示发送或接收的内容长度
*
* @param new_value 表示需要发送的数据长度
*/
inline void set_length(const csf_uint32 new_value) {
m_length = new_value;
}
/**
* 表示发送或接收的内容长度
*/
inline csf_uint32 get_length() {
return m_length;
}
/**
* 主要功能是:根据数据长度创建一个宿主对象
* 返回:无
*
* @param len 表示需要发送的缓存长度
*/
inline csf_int32 create(const csf_uint32 len) {
if (get_buffer()) {
return csf_failure;
}
set_container(new ValueType(len));
set_is_free(csf_true);
set_length(len);
return csf_succeed;
}
/**
* 表示是否在对象销毁时,释放内存。true表示需要释放;false表示不需要释放;默认为true,当为false时注意在其他地方显示释放,避免内存泄露。
*/
inline csf_bool get_is_free() {
return m_is_free;
}
/**
* 表示是否在对象销毁时,释放内存。true表示需要释放;false表示不需要释放;默认为true,当为false时注意在其他地方显示释放,避免内存泄露。
*
* @param new_value
* 表示是否在对象销毁时,释放内存。true表示需要释放;false表示不需要释放;默认为true,当为false时注意在其他地方显示释放,避免内存泄露。
*
*/
inline void set_is_free(const csf_bool new_value) {
m_is_free = new_value;
}
/**
* 主要功能是:清空所有缓存空间数据;
* 返回:无
*/
inline csf_void clear() {
set_length(0);
set_is_sync(csf_false);
set_is_free(csf_false);
set_is_filled(csf_false);
if (csf_nullptr != get_container()) {
return get_container()->clear();
}
}
/**
* 主要功能是:根据对象是否为空,长度是否为空,判断当前的csf_connect_buffer是否合法;
* 返回:对象不为空,长度不为0则返回true;其他情况返回false
*/
inline csf_bool is_valid() {
if (csf_nullptr == get_container()
|| csf_nullptr == get_buffer()
|| size() <= 0) {
return csf_false;
}
return csf_true;
}
/**
* 表示填满标志位,设备该标识位来强制接收数据时是否填充满后返回。当sync=true表示接收数据时,需要收取足够多的数据后才返回。这是一种收发性能的优化处理机制,
* 可以提高部分网络应用的性能。
*/
inline csf_bool get_is_filled() {
return m_is_filled;
}
/**
* 表示填满标志位,设备该标识位来强制接收数据时是否填充满后返回。当sync=true表示接收数据时,需要收取足够多的数据后才返回。这是一种收发性能的优化处理机制,
* 可以提高部分网络应用的性能。
*
* @param new_value
*/
inline void set_is_filled(csf_bool new_value) {
m_is_filled = new_value;
}
/**
* 表示获取buffer总缓存长度
*/
inline csf_uint32 size() {
if (csf_nullptr != get_container()) {
return get_container()->size();
}
return 0;
}
/**
* 表示获取buffer未使用的空间长度
*/
inline csf_uint32 avail() {
if (csf_nullptr != get_container()) {
return get_container()->avail();
}
return 0;
}
/**
* 表示当前实际已经使用的缓存的长度
*/
inline csf_uint32 length() {
if (csf_nullptr != get_container()) {
return get_container()->length();
}
return 0;
}
/**
* 将内存数据添加到buffer中。 返回:>=0表示实际添加的字符数量;<0表示错误码;
*
* @param buf 表示数据内存的起始地址
* @param len 表示内存数据的长度
*/
inline csf_int32 cat(const csf_uchar* buf, const csf_uint32 len) {
if (csf_nullptr != get_container()) {
return get_container()->cat(buf, len);
}
return 0;
}
/**
* 表示buffer是否为空,为空返回true,否则返回false。长度为0或null都为空,返回true。
*/
inline csf_bool empty() {
if (csf_nullptr != get_container()) {
return get_container()->empty();
}
return csf_true;
}
/**
* 表示将csf_string插入到csf_buffer中。 返回:>=0表示实际添加的字符数量;<0表示错误码;
*
* @param str 表示标准字符内容
*/
inline csf_int32 cat(const csf_string& str) {
if (csf_nullptr != get_container()) {
return get_container()->cat(str);
}
return 0;
}
/**
* 表示将一个char*字符串插入到buffer中。 返回:>=0表示实际添加的字符数量;<0表示错误码;
*
* @param buf 表示插入char*内容
*/
inline csf_int32 cat(const csf_char* buf) {
if (csf_nullptr != get_container()) {
return get_container()->cat(buf);
}
return 0;
}
/**
* 表示将csf_buffer插入到csf_buffer中。 返回:>=0表示实际添加的字符数量;<0表示错误码;
*
* @param buffer 表示需要添加的buffer内容
*/
inline csf_int32 cat(csf_buffer& buffer) {
if (csf_nullptr != get_container()) {
return get_container()->cat(buffer);
}
return 0;
}
// protected:
/**
* 表示释放buffer中的start指定的内存,并将buffer清空为null
*/
inline csf_void destroy() {
if (get_is_free() && get_container()) {
delete get_container();
set_is_free(csf_false);
set_container(csf_nullptr);
}
}
private:
/**
* 表示实际用于接收和发送的缓存长度
*
* @param new_value
*/
inline void set_size(csf_uint32 new_value) {
m_size = new_value;
}
/**
* 表示实际用于接收和发送的缓存长度
*/
inline csf_uint32 get_size() {
return m_size;
}
private:
/**
* 表示是否采用同步的方式发送,false表示异步;true表示同步;默认为异步方式
*/
csf_bool m_is_sync = csf_false;
/**
* 表示csf_connect_buffer所包含的实际需要被操作的宿主容器对象,例如:csf_buffer、csf_csfstring对象等
*/
ValueType* m_container;
/**
* 表示发送或接收的内容长度
*/
csf_uint32 m_length = 0;
/**
* 表示实际用于接收和发送的缓存长度
*/
csf_uint32 m_size = 0;
/**
* 表示是否在对象销毁时,释放内存。true表示需要释放;false表示不需要释放;默认为true,当为false时注意在其他地方显示释放,避免内存泄露。
*/
csf_bool m_is_free = csf_false;
/**
* 表示填满标志位,设备该标识位来强制接收数据时是否填充满后返回。当sync=true表示接收数据时,需要收取足够多的数据后才返回。这是一种收发性能的优化处理机制,
* 可以提高部分网络应用的性能。
*/
csf_bool m_is_filled = csf_false;
};
}
}
}
}
#endif // !defined(CSF_CONNECT_BUFFER_H_INCLUDED_)
| 22.384224 | 87 | 0.585995 | Kitty-Kitty |