hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
109
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
48.5k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
50530369d56e2ea877b3ea89418a2e4191b5090d
3,357
cpp
C++
src/tts/ttsServices.cpp
3rang/TTS
5a84b49ea08af599ad553ae27efb36b2682f3f76
[ "MIT" ]
null
null
null
src/tts/ttsServices.cpp
3rang/TTS
5a84b49ea08af599ad553ae27efb36b2682f3f76
[ "MIT" ]
null
null
null
src/tts/ttsServices.cpp
3rang/TTS
5a84b49ea08af599ad553ae27efb36b2682f3f76
[ "MIT" ]
null
null
null
// SPDX-FileCopyrightText: 2021 MBition GmbH // // SPDX-License-Identifier: Closed software #include"include/ttsService.hpp" MelGenData ttsBaseMel::interpreterBuildMel(std::vector<int32_t> &localbuf) { model = tflite::FlatBufferModel::BuildFromFile(melgenPath); TFLITE_MINIMAL_CHECK(model != nullptr); tflite::InterpreterBuilder builder(*model, resolver); builder(&interpreter); TFLITE_MINIMAL_CHECK(interpreter != nullptr); int32_t ouptIndex; std::vector<int32_t> inputIndexs; MelGenData output; std::vector<int32_t> _speakerId{0}; std::vector<float> _speedRatio{1.0}; std::vector<float> _f0Ratio{1.0}; std::vector<float> _enegyRatio{1.0}; inputIndexs = (interpreter->inputs()); ouptIndex = (interpreter->outputs()[0]); int idsLen = localbuf.size(); std::vector<std::vector<int32_t>> inputIndexsShape{ {1, idsLen}, {1}, {1}, {1}, {1} }; int32_t shapeI = 0; for (auto index : inputIndexs) { interpreter->ResizeInputTensor(index, inputIndexsShape[shapeI]); shapeI++; } TFLITE_MINIMAL_CHECK(interpreter->AllocateTensors() == kTfLiteOk); // 0 milli sec...... int32_t* input_ids_ptr = interpreter->typed_tensor<int32_t>(inputIndexs[0]); memcpy(input_ids_ptr, localbuf.data(), sizeof(int) * idsLen); int32_t* speaker_ids_ptr = interpreter->typed_tensor<int32_t>(inputIndexs[1]); memcpy(speaker_ids_ptr, _speakerId.data(), sizeof(int)); float* speed_ratios_ptr = interpreter->typed_tensor<float>(inputIndexs[2]); memcpy(speed_ratios_ptr, _speedRatio.data(), sizeof(float)); float* speed_ratios2_ptr = interpreter->typed_tensor<float>(inputIndexs[3]); memcpy(speed_ratios2_ptr, _f0Ratio.data(), sizeof(float)); float* speed_ratios3_ptr = interpreter->typed_tensor<float>(inputIndexs[4]); memcpy(speed_ratios3_ptr, _enegyRatio.data(), sizeof(float)); // Run inference TFLITE_MINIMAL_CHECK(interpreter->Invoke() == kTfLiteOk); // 4000 milli sec. to 2600 milli TfLiteTensor* melGenTensor = interpreter->tensor(ouptIndex); for (int i=0; i<melGenTensor->dims->size; i++) { output.mel_Shape.push_back(melGenTensor->dims->data[i]); } output.mel_bytes = melGenTensor->bytes; output.mel_Data = interpreter->typed_tensor<float>(ouptIndex); return output; } std::vector<float> ttsBasevocodoer::interpreterBuildvocoder(MelGenData &localbufV) { model = tflite::FlatBufferModel::BuildFromFile(vocoderPath); TFLITE_MINIMAL_CHECK(model != nullptr); tflite::InterpreterBuilder builder1(*model, resolver); builder1(&interpreter); TFLITE_MINIMAL_CHECK(interpreter != nullptr); const int32_t inputIndexV = (interpreter->inputs()[0]);; const int32_t outputIndexV = (interpreter->outputs()[0]);; std::vector<float> audio; interpreter->ResizeInputTensor(inputIndexV, localbufV.mel_Shape); TFLITE_MINIMAL_CHECK(interpreter->AllocateTensors() == kTfLiteOk); // 3 milli float* melDataPtr = interpreter->typed_input_tensor<float>(inputIndexV); memcpy(melDataPtr, localbufV.mel_Data, localbufV.mel_bytes); TFLITE_MINIMAL_CHECK(interpreter->Invoke() == kTfLiteOk); // 3485 milli lowest 1450 milli TfLiteTensor* audioTensor = interpreter->tensor(outputIndexV); float* outputPtr = interpreter->typed_output_tensor<float>(0); int32_t audio_len = audioTensor->bytes / sizeof(float); for (int i=0; i<audio_len; ++i) { audio.push_back(outputPtr[i]); } return audio; }
25.625954
93
0.744117
3rang
505caa149e40fd4322cc25588e3349fa9cd83c1a
904
hpp
C++
src/util/cloneable.hpp
pepng-CU/pepng
6030798b6936a6f85655d5e5d1ca638be282de92
[ "MIT" ]
2
2021-04-28T20:51:25.000Z
2021-04-28T20:51:38.000Z
src/util/cloneable.hpp
pepng-CU/pepng
6030798b6936a6f85655d5e5d1ca638be282de92
[ "MIT" ]
null
null
null
src/util/cloneable.hpp
pepng-CU/pepng
6030798b6936a6f85655d5e5d1ca638be282de92
[ "MIT" ]
null
null
null
#pragma once #include <memory> /** * Utility for creating shared_ptr clones of objects. */ template<typename T> class Cloneable { public: /** * Clones this object as type T. */ std::shared_ptr<T> clone() { return std::shared_ptr<T>(this->clone_implementation()); } protected: /** * Implementation of clone using raw pointers. */ virtual T* clone_implementation() = 0; }; /** * Utility for creating 2nd layer clone. */ template<typename T> class Cloneable2 { public: /** * Clones this object as type T. */ std::shared_ptr<T> clone2() { return std::shared_ptr<T>(this->clone_implementation()); } protected: /** * Implementation of clone using raw pointers. */ virtual T* clone_implementation() = 0; };
21.023256
68
0.547566
pepng-CU
505eb32be06853a94a8a97961410b3a78a4776d6
344
cpp
C++
src/HudRenderable.cpp
bernhardmgruber/hlbsp
a2144818fb6e747409dcd93cab97cea7f055dbfd
[ "BSL-1.0" ]
5
2020-04-16T19:00:09.000Z
2022-03-06T04:12:20.000Z
src/HudRenderable.cpp
bernhardmgruber/hlbsp
a2144818fb6e747409dcd93cab97cea7f055dbfd
[ "BSL-1.0" ]
null
null
null
src/HudRenderable.cpp
bernhardmgruber/hlbsp
a2144818fb6e747409dcd93cab97cea7f055dbfd
[ "BSL-1.0" ]
null
null
null
#include "HudRenderable.h" #include "Hud.h" #include "IRenderer.h" #include "global.h" HudRenderable::HudRenderable(render::IRenderer& renderer, const Hud& hud) : m_renderer(renderer), m_hud(hud) { } void HudRenderable::render(const RenderSettings& settings) { if (!global::renderHUD) return; m_renderer.renderImgui(m_hud.drawData()); }
22.933333
73
0.744186
bernhardmgruber
5063a05c7686d2d41bef51e6784055e54aecbf91
10,575
cpp
C++
src/theory/arith/linear_equality.cpp
bobot/CVC4
63811bc87a07c487c25a566fcabd38cc6d29a61c
[ "BSL-1.0" ]
null
null
null
src/theory/arith/linear_equality.cpp
bobot/CVC4
63811bc87a07c487c25a566fcabd38cc6d29a61c
[ "BSL-1.0" ]
null
null
null
src/theory/arith/linear_equality.cpp
bobot/CVC4
63811bc87a07c487c25a566fcabd38cc6d29a61c
[ "BSL-1.0" ]
null
null
null
/********************* */ /*! \file linear_equality.cpp ** \verbatim ** Original author: taking ** Major contributors: none ** Minor contributors (to current version): mdeters ** This file is part of the CVC4 prototype. ** Copyright (c) 2009-2012 New York University and The University of Iowa ** See the file COPYING in the top-level source directory for licensing ** information.\endverbatim ** ** \brief This implements the LinearEqualityModule. ** ** This implements the LinearEqualityModule. **/ #include "theory/arith/linear_equality.h" using namespace std; namespace CVC4 { namespace theory { namespace arith { /* Explicitly instatiate this function. */ template void LinearEqualityModule::propagateNonbasics<true>(ArithVar basic, Constraint c); template void LinearEqualityModule::propagateNonbasics<false>(ArithVar basic, Constraint c); LinearEqualityModule::Statistics::Statistics(): d_statPivots("theory::arith::pivots",0), d_statUpdates("theory::arith::updates",0), d_pivotTime("theory::arith::pivotTime") { StatisticsRegistry::registerStat(&d_statPivots); StatisticsRegistry::registerStat(&d_statUpdates); StatisticsRegistry::registerStat(&d_pivotTime); } LinearEqualityModule::Statistics::~Statistics(){ StatisticsRegistry::unregisterStat(&d_statPivots); StatisticsRegistry::unregisterStat(&d_statUpdates); StatisticsRegistry::unregisterStat(&d_pivotTime); } void LinearEqualityModule::update(ArithVar x_i, const DeltaRational& v){ Assert(!d_tableau.isBasic(x_i)); DeltaRational assignment_x_i = d_partialModel.getAssignment(x_i); ++(d_statistics.d_statUpdates); Debug("arith") <<"update " << x_i << ": " << assignment_x_i << "|-> " << v << endl; DeltaRational diff = v - assignment_x_i; //Assert(matchingSets(d_tableau, x_i)); Tableau::ColIterator basicIter = d_tableau.colIterator(x_i); for(; !basicIter.atEnd(); ++basicIter){ const Tableau::Entry& entry = *basicIter; Assert(entry.getColVar() == x_i); ArithVar x_j = d_tableau.rowIndexToBasic(entry.getRowIndex()); //ReducedRowVector& row_j = d_tableau.lookup(x_j); //const Rational& a_ji = row_j.lookup(x_i); const Rational& a_ji = entry.getCoefficient(); const DeltaRational& assignment = d_partialModel.getAssignment(x_j); DeltaRational nAssignment = assignment+(diff * a_ji); d_partialModel.setAssignment(x_j, nAssignment); d_basicVariableUpdates(x_j); } d_partialModel.setAssignment(x_i, v); //double difference = ((double)d_tableau.getNumRows()) - ((double) d_tableau.getRowLength(x_i)); //(d_statistics.d_avgNumRowsNotContainingOnUpdate).addEntry(difference); if(Debug.isOn("paranoid:check_tableau")){ debugCheckTableau(); } } void LinearEqualityModule::pivotAndUpdate(ArithVar x_i, ArithVar x_j, const DeltaRational& v){ Assert(x_i != x_j); TimerStat::CodeTimer codeTimer(d_statistics.d_pivotTime); if(Debug.isOn("arith::simplex:row")){ debugPivot(x_i, x_j); } RowIndex ridx = d_tableau.basicToRowIndex(x_i); const Tableau::Entry& entry_ij = d_tableau.findEntry(ridx, x_j); Assert(!entry_ij.blank()); const Rational& a_ij = entry_ij.getCoefficient(); const DeltaRational& betaX_i = d_partialModel.getAssignment(x_i); Rational inv_aij = a_ij.inverse(); DeltaRational theta = (v - betaX_i)*inv_aij; d_partialModel.setAssignment(x_i, v); DeltaRational tmp = d_partialModel.getAssignment(x_j) + theta; d_partialModel.setAssignment(x_j, tmp); //Assert(matchingSets(d_tableau, x_j)); for(Tableau::ColIterator iter = d_tableau.colIterator(x_j); !iter.atEnd(); ++iter){ const Tableau::Entry& entry = *iter; Assert(entry.getColVar() == x_j); RowIndex currRow = entry.getRowIndex(); if(ridx != currRow ){ ArithVar x_k = d_tableau.rowIndexToBasic(currRow); const Rational& a_kj = entry.getCoefficient(); DeltaRational nextAssignment = d_partialModel.getAssignment(x_k) + (theta * a_kj); d_partialModel.setAssignment(x_k, nextAssignment); d_basicVariableUpdates(x_k); } } // Pivots ++(d_statistics.d_statPivots); d_tableau.pivot(x_i, x_j); d_basicVariableUpdates(x_j); if(Debug.isOn("matrix")){ d_tableau.printMatrix(); } } void LinearEqualityModule::debugPivot(ArithVar x_i, ArithVar x_j){ Debug("arith::pivot") << "debugPivot("<< x_i <<"|->"<< x_j << ")" << endl; for(Tableau::RowIterator iter = d_tableau.basicRowIterator(x_i); !iter.atEnd(); ++iter){ const Tableau::Entry& entry = *iter; ArithVar var = entry.getColVar(); const Rational& coeff = entry.getCoefficient(); DeltaRational beta = d_partialModel.getAssignment(var); Debug("arith::pivot") << var << beta << coeff; if(d_partialModel.hasLowerBound(var)){ Debug("arith::pivot") << "(lb " << d_partialModel.getLowerBound(var) << ")"; } if(d_partialModel.hasUpperBound(var)){ Debug("arith::pivot") << "(up " << d_partialModel.getUpperBound(var) << ")"; } Debug("arith::pivot") << endl; } Debug("arith::pivot") << "end row"<< endl; } /** * This check is quite expensive. * It should be wrapped in a Debug.isOn() guard. * if(Debug.isOn("paranoid:check_tableau")){ * checkTableau(); * } */ void LinearEqualityModule::debugCheckTableau(){ Tableau::BasicIterator basicIter = d_tableau.beginBasic(), endIter = d_tableau.endBasic(); for(; basicIter != endIter; ++basicIter){ ArithVar basic = *basicIter; DeltaRational sum; Debug("paranoid:check_tableau") << "starting row" << basic << endl; Tableau::RowIterator nonbasicIter = d_tableau.basicRowIterator(basic); for(; !nonbasicIter.atEnd(); ++nonbasicIter){ const Tableau::Entry& entry = *nonbasicIter; ArithVar nonbasic = entry.getColVar(); if(basic == nonbasic) continue; const Rational& coeff = entry.getCoefficient(); DeltaRational beta = d_partialModel.getAssignment(nonbasic); Debug("paranoid:check_tableau") << nonbasic << beta << coeff<<endl; sum = sum + (beta*coeff); } DeltaRational shouldBe = d_partialModel.getAssignment(basic); Debug("paranoid:check_tableau") << "ending row" << sum << "," << shouldBe << endl; Assert(sum == shouldBe); } } bool LinearEqualityModule::debugEntireLinEqIsConsistent(const string& s){ bool result = true; for(ArithVar var = 0, end = d_tableau.getNumColumns(); var != end; ++var){ // for(VarIter i = d_variables.begin(), end = d_variables.end(); i != end; ++i){ //ArithVar var = d_arithvarNodeMap.asArithVar(*i); if(!d_partialModel.assignmentIsConsistent(var)){ d_partialModel.printModel(var); Warning() << s << ":" << "Assignment is not consistent for " << var ; if(d_tableau.isBasic(var)){ Warning() << " (basic)"; } Warning() << endl; result = false; } } return result; } DeltaRational LinearEqualityModule::computeBound(ArithVar basic, bool upperBound){ DeltaRational sum(0,0); for(Tableau::RowIterator i = d_tableau.basicRowIterator(basic); !i.atEnd(); ++i){ const Tableau::Entry& entry = (*i); ArithVar nonbasic = entry.getColVar(); if(nonbasic == basic) continue; const Rational& coeff = entry.getCoefficient(); int sgn = coeff.sgn(); bool ub = upperBound ? (sgn > 0) : (sgn < 0); const DeltaRational& bound = ub ? d_partialModel.getUpperBound(nonbasic): d_partialModel.getLowerBound(nonbasic); DeltaRational diff = bound * coeff; sum = sum + diff; } return sum; } /** * Computes the value of a basic variable using the current assignment. */ DeltaRational LinearEqualityModule::computeRowValue(ArithVar x, bool useSafe){ Assert(d_tableau.isBasic(x)); DeltaRational sum(0); for(Tableau::RowIterator i = d_tableau.basicRowIterator(x); !i.atEnd(); ++i){ const Tableau::Entry& entry = (*i); ArithVar nonbasic = entry.getColVar(); if(nonbasic == x) continue; const Rational& coeff = entry.getCoefficient(); const DeltaRational& assignment = d_partialModel.getAssignment(nonbasic, useSafe); sum = sum + (assignment * coeff); } return sum; } bool LinearEqualityModule::hasBounds(ArithVar basic, bool upperBound){ for(Tableau::RowIterator iter = d_tableau.basicRowIterator(basic); !iter.atEnd(); ++iter){ const Tableau::Entry& entry = *iter; ArithVar var = entry.getColVar(); if(var == basic) continue; int sgn = entry.getCoefficient().sgn(); if(upperBound){ if( (sgn < 0 && !d_partialModel.hasLowerBound(var)) || (sgn > 0 && !d_partialModel.hasUpperBound(var))){ return false; } }else{ if( (sgn < 0 && !d_partialModel.hasUpperBound(var)) || (sgn > 0 && !d_partialModel.hasLowerBound(var))){ return false; } } } return true; } template <bool upperBound> void LinearEqualityModule::propagateNonbasics(ArithVar basic, Constraint c){ Assert(d_tableau.isBasic(basic)); Assert(c->getVariable() == basic); Assert(!c->assertedToTheTheory()); //Assert(c->canBePropagated()); Assert(!c->hasProof()); Debug("arith::explainNonbasics") << "LinearEqualityModule::explainNonbasics(" << basic <<") start" << endl; vector<Constraint> bounds; Tableau::RowIterator iter = d_tableau.basicRowIterator(basic); for(; !iter.atEnd(); ++iter){ const Tableau::Entry& entry = *iter; ArithVar nonbasic = entry.getColVar(); if(nonbasic == basic) continue; const Rational& a_ij = entry.getCoefficient(); int sgn = a_ij.sgn(); Assert(sgn != 0); Constraint bound = NullConstraint; if(upperBound){ if(sgn < 0){ bound = d_partialModel.getLowerBoundConstraint(nonbasic); }else{ Assert(sgn > 0); bound = d_partialModel.getUpperBoundConstraint(nonbasic); } }else{ if(sgn < 0){ bound = d_partialModel.getUpperBoundConstraint(nonbasic); }else{ Assert(sgn > 0); bound = d_partialModel.getLowerBoundConstraint(nonbasic); } } Assert(bound != NullConstraint); Debug("arith::explainNonbasics") << "explainNonbasics" << bound << " for " << c << endl; bounds.push_back(bound); } c->impliedBy(bounds); Debug("arith::explainNonbasics") << "LinearEqualityModule::explainNonbasics(" << basic << ") done" << endl; } }/* CVC4::theory::arith namespace */ }/* CVC4::theory namespace */ }/* CVC4 namespace */
32.943925
98
0.669598
bobot
50648c7667c4361232b77a092b49823d68c1f5df
10,522
cpp
C++
tests/Camera3D.cpp
Defalt8/axl.gl
0028bcad1a86b048831e5fd61a436663fd38a763
[ "MIT" ]
6
2020-11-20T08:29:33.000Z
2021-12-13T14:41:52.000Z
tests/Camera3D.cpp
Defalt8/axl.gl
0028bcad1a86b048831e5fd61a436663fd38a763
[ "MIT" ]
null
null
null
tests/Camera3D.cpp
Defalt8/axl.gl
0028bcad1a86b048831e5fd61a436663fd38a763
[ "MIT" ]
null
null
null
#include "common/stdafx.hpp" #include "common/MainView.hpp" #include "common/Quad.hpp" namespace GL { using namespace axl::glfl; using namespace axl::glfl::core::GL; } void onExit(int exit_code) { if (axl::Assert::NUM_FAILED_ASSERTIONS) puts("----------------------------------------"); printf("%c> %d/%d Passed!\n", (axl::Assert::NUM_FAILED_ASSERTIONS ? '*' : '\r'), (axl::Assert::NUM_TOTAL_ASSERTIONS - axl::Assert::NUM_FAILED_ASSERTIONS), axl::Assert::NUM_TOTAL_ASSERTIONS); printf("-- exiting with code %d --\n", exit_code); } class MainView : public Test::MainView { public: MainView(const axl::util::WString& _title, const axl::math::Vec2i& _position, const axl::math::Vec2i& _size, const axl::gl::Cursor& _cursor = axl::gl::DefaultCursor) : Test::MainView(_title, _position, _size, _cursor), title_update_clock(500), update_clock(15) {} ~MainView() { this->destroy(); } public: bool initialize() { Test::MainView::initialize(); axl::media::image::DIB bitmap; if(bitmap.loadFromFile(AXLGL_TEST_RES_DIR"/image/Alien.bmp")) image_alien = bitmap.toImage2D(); return true; } bool update() { Test::MainView::update(); if(title_update_clock.checkAndSet(false)) { axl::util::WString new_title(96); new_title.format(L"axl.gl.Camera3D test | FPS: %.0f", this->FPS); this->setTitle(new_title); } if(update_clock.checkAndSet(true)) { float delta_time = dtime.deltaTimef(), elapsed_time = etime.deltaTimef(); dtime.set(); quad.transform.setRotation(axl::math::Vec3f(0.f, elapsed_time * axl::math::Angle::degToRad(69.f), 0.f)); } return true; } bool render() { if(!context.isValid() || !(context.isCurrent() || context.makeCurrent())) return false; using namespace GL; glEnable(GL_SCISSOR_TEST); // camera 1 camera1.makeCurrent(&context, true); if(selected_camera == &camera1) glClearColor(1.f, .8f, .8f, 1.f); else glClearColor(1.f, .1f, .5f, 1.f); glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT); quad.render(&camera1); // camera 2 camera2.makeCurrent(&context, true); if(selected_camera == &camera2) glClearColor(.8f, 1.f, .8f, 1.f); else glClearColor(.5f, 1.f, .1f, 1.f); glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT); quad.render(&camera2); // camera 3 camera3.makeCurrent(&context, true); if(selected_camera == &camera3) glClearColor(.8f, .8f, 1.f, 1.f); else glClearColor(.1f, .5f, 1.f, 1.f); glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT); quad.render(&camera3); glDisable(GL_SCISSOR_TEST); this->onRender(); return true; } protected: void printPoints(int x, int y) { if(!selected_camera) return; axl::math::Vec2i screen_space(x, size.y-y); axl::math::Vec4f viewport_space(selected_camera->screenToViewport(screen_space), 1.f); axl::math::Vec4f world_space = selected_camera->viewportToWorld(viewport_space); axl::math::Vec4f viewport_space1 = selected_camera->worldToViewport(world_space); axl::math::Vec2i screen_space1 = selected_camera->viewportToScreen(viewport_space1.toVec3(axl::math::Vec4f::XYZ)); printf("ScreenSpace[%3d, %3d] -> ViewportSpace[%6.2f, %6.2f, %6.2f] -> WorldSpace[%6.2f, %6.2f, %6.2f] | ScreenSpace[%3d, %3d] -> ViewportSpace[%6.2f, %6.2f, %6.2f] \r", screen_space.x, screen_space.y, viewport_space.x, viewport_space.y, viewport_space.z, world_space.x, world_space.y, world_space.z, screen_space1.x, screen_space1.y, viewport_space1.x, viewport_space1.y, viewport_space1.z ); } bool onCreate(bool recreating) { if(!Test::MainView::onCreate(recreating)) return false; using namespace GL; // context.setVSync(true); dtime.set(); etime.set(); // projections projection1 = &orthographic_projection1; projection2 = &orthographic_projection2; projection3 = &orthographic_projection3; // quad_texture quad_texture.setContext(&context); quad_texture.create(); if(image_alien.isValid()) { quad_texture.allocate(0, image_alien.width(), image_alien.height(), GL_RGB8); quad_texture.setImage(0, 0, 0, image_alien.width(), image_alien.height(), GL_RGB, GL_UNSIGNED_BYTE, image_alien.cimage(), 1); quad_texture.setParami(GL_TEXTURE_MIN_FILTER, GL_LINEAR); quad_texture.setParami(GL_TEXTURE_MAG_FILTER, GL_LINEAR); } // quad_program quad_program.setContext(&context); quad_program.create(); // quad quad.setContext(&context); quad.setQuadProgram(&quad_program); quad.setSize(axl::math::Vec2f(1.f, 1.f)); quad.transform.setTransformOrder(axl::math::Orders::Transform::STR); quad.transform.setRotationOrder(axl::math::Orders::Rotation::Y); quad.transform.setPosition(axl::math::Vec3f(-quad.size.x / 2.f, -quad.size.y / 2.f, 0.f)); quad.color.set(.1f, .1f, 0.2f, 1.f); quad.texture = &quad_texture; quad.create(); return true; } void onPointer(int index, int x, int y, bool down) { Test::MainView::onPointer(index, x, y, down); if(index == PI_LEFT_BUTTON) { if(down) { this->printPoints(x, y); this->capturePointer(true); } else this->capturePointer(false); } } void onPointerMove(int index, int x, int y) { Test::MainView::onPointerMove(index, x, y); if(pointers[index]) { if(index == PI_LEFT_BUTTON) { this->printPoints(x, y); } } } bool onKey(axl::gl::input::KeyCode key, bool down) { if(down) { switch(key) { case axl::gl::input::KeyCode::KEY_O: if(projection1 != &orthographic_projection1) { camera1.projection = projection1 = &orthographic_projection1; camera2.projection = projection2 = &orthographic_projection2; camera3.projection = projection3 = &orthographic_projection3; puts("\n> Projection method switched to Orthographic."); } return true; case axl::gl::input::KeyCode::KEY_P: if(projection1 != &perspective_projection1) { camera1.projection = projection1 = &perspective_projection1; camera2.projection = projection2 = &perspective_projection2; camera3.projection = projection3 = &perspective_projection3; puts("\n> Projection method switched to Perspective."); } return true; case axl::gl::input::KeyCode::KEY_1: if(selected_camera != &camera1) { selected_camera = &camera1; printf("\n> Camera 1 selected.\n"); } return true; case axl::gl::input::KeyCode::KEY_2: if(selected_camera != &camera2) { selected_camera = &camera2; printf("\n> Camera 2 selected.\n"); } return true; case axl::gl::input::KeyCode::KEY_3: if(selected_camera != &camera3) { selected_camera = &camera3; printf("\n> Camera 3 selected.\n"); } return true; } } return Test::MainView::onKey(key, down); } void onSize(int w, int h) { Test::MainView::onSize(w, h); camera1.set( axl::math::Vec3f(0.f, 0.f, 2.5f), axl::math::Vec3f(0.f, 0.f, 0.f), 0.f, axl::math::Vec3f::filled(1.f), axl::math::Vec2i(0,0), axl::math::Vec2i(w/2,h), projection1 ); float ratio1 = (float)camera1.viewport_size.x / camera1.viewport_size.y; perspective_projection1.set(.001f, 100.f, ratio1, 70.f); orthographic_projection1.set( -ratio1, ratio1, //(float)camera1.viewport_size.x, -1.f, 1.f, // (float)camera1.viewport_size.y, -100.f, 100.f); camera2.set( axl::math::Vec3f(0.f, 0.f, 2.5f), axl::math::Vec3f(0.f, 0.f, 0.f), 0.f, axl::math::Vec3f::filled(1.f), axl::math::Vec2i(w/2,0), axl::math::Vec2i(w/2,h/2), projection2 ); float ratio2 = (float)camera2.viewport_size.x / camera2.viewport_size.y; perspective_projection2.set(.001f, 100.f, ratio2, 54.4f); orthographic_projection2.set( -ratio2, ratio2, //(float)camera2.viewport_size.x, -1.f, 1.f, //(float)camera2.viewport_size.y, -100.f, 100.f); camera3.set( axl::math::Vec3f(0.f, 0.f, 2.5f), axl::math::Vec3f(0.f, 0.f, 0.f), 0.f, axl::math::Vec3f::filled(1.f), axl::math::Vec2i(w/2,h/2), axl::math::Vec2i(w/2,h/2), projection3 ); float ratio3 = (float)camera3.viewport_size.x / camera3.viewport_size.y; perspective_projection3.set(.001f, 100.f, ratio3, 30.f); orthographic_projection3.set( -ratio3, ratio3, //(float)camera3.viewport_size.x, -1.f, 1.f, //(float)camera3.viewport_size.y, -100.f, 100.f); this->update(); if(this->render()) this->swap(); } private: axl::util::uc::Clock title_update_clock, update_clock; axl::util::uc::Time dtime, etime; axl::gl::projection::Orthographicf orthographic_projection1, orthographic_projection2, orthographic_projection3; axl::gl::projection::Perspectivef perspective_projection1, perspective_projection2, perspective_projection3; axl::gl::projection::Projectionf *projection1, *projection2, *projection3; axl::gl::camera::Camera3Df camera1, camera2, camera3; axl::gl::camera::Camera3Df *selected_camera = &camera1; Test::Quad::Program quad_program; Test::Quad quad; axl::gl::gfx::Texture2D quad_texture; axl::media::image::Image2D image_alien; }; int main(int argc, char *argv[]) { bool verbose = argc > 1 && (0 == strcmp(argv[1], "-v") || 0 == strcmp(argv[1], "--verbose")); printf(">> axl.gl Viewports test -- axl.gl %s library %u.%u.%u\n", (axl::gl::lib::BUILD == axl::gl::lib::Build::SHARED ? "SHARED" : "STATIC"), axl::gl::lib::VERSION.major, axl::gl::lib::VERSION.minor, axl::gl::lib::VERSION.patch); puts("----------------------------------------"); puts(" Press Keys '1','2' or '3' to select the corresponding camera."); puts(" Press Key 'P' and 'O' keys to switch to perspective and orthogographic camera respectively."); puts("----------------------------------------"); { axl::gl::Display display; MainView main_view(L"axl.gl.Camera3D test", axl::math::Vec2i(0,0), axl::math::Vec2i(640,480)); Assertve(display.isOpen(), verbose); Assertve(axl::gl::Application::init(), verbose); Assertve(axl::glfl::core::load(), verbose); Assertve(main_view.initialize(), verbose); Assertve(main_view.create(display, false, MainView::VF_RESIZABLE), verbose); Assertve(main_view.show(MainView::SM_SHOW), verbose); while(!axl::gl::Application::IS_QUITTING) { axl::gl::Application::pollEvents(display); main_view.update(); if(main_view.render()) main_view.swap(); } } return axl::Assert::NUM_FAILED_ASSERTIONS; }
34.956811
231
0.656244
Defalt8
506ce9a3b3e070dd23dada727e5806c0b98b11c4
15,101
cpp
C++
core/PRU.cpp
amilo/soundcoreA
30b14ce3d34f74c2385126fc244a0c252c3aa4c4
[ "MIT" ]
null
null
null
core/PRU.cpp
amilo/soundcoreA
30b14ce3d34f74c2385126fc244a0c252c3aa4c4
[ "MIT" ]
null
null
null
core/PRU.cpp
amilo/soundcoreA
30b14ce3d34f74c2385126fc244a0c252c3aa4c4
[ "MIT" ]
null
null
null
/* * PRU.cpp * * Code for communicating with the Programmable Realtime Unit (PRU) * on the BeagleBone AM335x series processors. The PRU loads and runs * a separate code image compiled from an assembly file. Here it is * used to handle audio and SPI ADC/DAC data. * * This code is specific to the PRU code in the assembly file; for example, * it uses certain GPIO resources that correspond to that image. * * Created on: May 27, 2014 * Author: andrewm */ #include "../include/PRU.h" #include "../include/prussdrv.h" #include "../include/pruss_intc_mapping.h" #include "../include/GPIOcontrol.h" #include "../include/render.h" #include "../include/pru_rtaudio_bin.h" #include <iostream> #include <stdlib.h> #include <cstdio> #include <cerrno> #include <fcntl.h> #include <sys/mman.h> // Xenomai-specific includes #include <sys/mman.h> #include <native/task.h> #include <native/timer.h> #include <rtdk.h> using namespace std; #define PRU_MEM_MCASP_OFFSET 0x2000 // Offset within PRU-SHARED RAM #define PRU_MEM_MCASP_LENGTH 0x2000 // Length of McASP memory, in bytes #define PRU_MEM_DAC_OFFSET 0x0 // Offset within PRU0 RAM #define PRU_MEM_DAC_LENGTH 0x2000 // Length of ADC+DAC memory, in bytes #define PRU_MEM_COMM_OFFSET 0x0 // Offset within PRU-SHARED RAM #define PRU_SHOULD_STOP 0 #define PRU_CURRENT_BUFFER 1 #define PRU_BUFFER_FRAMES 2 #define PRU_SHOULD_SYNC 3 #define PRU_SYNC_ADDRESS 4 #define PRU_SYNC_PIN_MASK 5 #define PRU_LED_ADDRESS 6 #define PRU_LED_PIN_MASK 7 #define PRU_FRAME_COUNT 8 #define PRU_USE_SPI 9 #define PRU_SPI_NUM_CHANNELS 10 #define PRU_SAMPLE_INTERVAL_NS 11338 // 88200Hz per SPI sample = 11.338us #define GPIO0_ADDRESS 0x44E07000 #define GPIO1_ADDRESS 0x4804C000 #define GPIO_SIZE 0x198 #define GPIO_CLEARDATAOUT (0x190 / 4) #define GPIO_SETDATAOUT (0x194 / 4) #define TEST_PIN_GPIO_BASE GPIO0_ADDRESS // Use GPIO0(31) for debugging #define TEST_PIN_MASK (1 << 31) #define TEST_PIN2_MASK (1 << 26) #define USERLED3_GPIO_BASE GPIO1_ADDRESS // GPIO1(24) is user LED 3 #define USERLED3_PIN_MASK (1 << 24) const unsigned int PRU::kPruGPIODACSyncPin = 5; // GPIO0(5); P9-17 const unsigned int PRU::kPruGPIOADCSyncPin = 48; // GPIO1(16); P9-15 const unsigned int PRU::kPruGPIOTestPin = 60; // GPIO1(28); P9-12 const unsigned int PRU::kPruGPIOTestPin2 = 31; // GPIO0(31); P9-13 const unsigned int PRU::kPruGPIOTestPin3 = 26; // GPIO0(26); P8-14 extern int gShouldStop; extern int gRTAudioVerbose; // Constructor: specify a PRU number (0 or 1) PRU::PRU() : pru_number(0), running(false), spi_enabled(false), gpio_enabled(false), led_enabled(false), gpio_test_pin_enabled(false), spi_num_channels(0), xenomai_gpio_fd(-1), xenomai_gpio(0) { } // Destructor PRU::~PRU() { if(running) disable(); if(gpio_enabled) cleanupGPIO(); if(xenomai_gpio_fd >= 0) close(xenomai_gpio_fd); } // Prepare the GPIO pins needed for the PRU // If include_test_pin is set, the GPIO output // is also prepared for an output which can be // viewed on a scope. If include_led is set, // user LED 3 on the BBB is taken over by the PRU // to indicate activity int PRU::prepareGPIO(int use_spi, int include_test_pin, int include_led) { if(use_spi) { // Prepare DAC CS/ pin: output, high to begin if(gpio_export(kPruGPIODACSyncPin)) { if(gRTAudioVerbose) cout << "Warning: couldn't export DAC sync pin\n"; } if(gpio_set_dir(kPruGPIODACSyncPin, OUTPUT_PIN)) { if(gRTAudioVerbose) cout << "Couldn't set direction on DAC sync pin\n"; return -1; } if(gpio_set_value(kPruGPIODACSyncPin, HIGH)) { if(gRTAudioVerbose) cout << "Couldn't set value on DAC sync pin\n"; return -1; } // Prepare ADC CS/ pin: output, high to begin if(gpio_export(kPruGPIOADCSyncPin)) { if(gRTAudioVerbose) cout << "Warning: couldn't export ADC sync pin\n"; } if(gpio_set_dir(kPruGPIOADCSyncPin, OUTPUT_PIN)) { if(gRTAudioVerbose) cout << "Couldn't set direction on ADC sync pin\n"; return -1; } if(gpio_set_value(kPruGPIOADCSyncPin, HIGH)) { if(gRTAudioVerbose) cout << "Couldn't set value on ADC sync pin\n"; return -1; } spi_enabled = true; } if(include_test_pin) { // Prepare GPIO test output (for debugging), low to begin if(gpio_export(kPruGPIOTestPin)) { if(gRTAudioVerbose) cout << "Warning: couldn't export GPIO test pin\n"; } if(gpio_set_dir(kPruGPIOTestPin, OUTPUT_PIN)) { if(gRTAudioVerbose) cout << "Couldn't set direction on GPIO test pin\n"; return -1; } if(gpio_set_value(kPruGPIOTestPin, LOW)) { if(gRTAudioVerbose) cout << "Couldn't set value on GPIO test pin\n"; return -1; } if(gpio_export(kPruGPIOTestPin2)) { if(gRTAudioVerbose) cout << "Warning: couldn't export GPIO test pin 2\n"; } if(gpio_set_dir(kPruGPIOTestPin2, OUTPUT_PIN)) { if(gRTAudioVerbose) cout << "Couldn't set direction on GPIO test pin 2\n"; return -1; } if(gpio_set_value(kPruGPIOTestPin2, LOW)) { if(gRTAudioVerbose) cout << "Couldn't set value on GPIO test pin 2\n"; return -1; } if(gpio_export(kPruGPIOTestPin3)) { if(gRTAudioVerbose) cout << "Warning: couldn't export GPIO test pin 3\n"; } if(gpio_set_dir(kPruGPIOTestPin3, OUTPUT_PIN)) { if(gRTAudioVerbose) cout << "Couldn't set direction on GPIO test pin 3\n"; return -1; } if(gpio_set_value(kPruGPIOTestPin3, LOW)) { if(gRTAudioVerbose) cout << "Couldn't set value on GPIO test pin 3\n"; return -1; } gpio_test_pin_enabled = true; } if(include_led) { // Turn off system function for LED3 so it can be reused by PRU led_set_trigger(3, "none"); led_enabled = true; } gpio_enabled = true; return 0; } // Clean up the GPIO at the end void PRU::cleanupGPIO() { if(!gpio_enabled) return; if(spi_enabled) { gpio_unexport(kPruGPIODACSyncPin); gpio_unexport(kPruGPIOADCSyncPin); } if(gpio_test_pin_enabled) { gpio_unexport(kPruGPIOTestPin); gpio_unexport(kPruGPIOTestPin2); gpio_unexport(kPruGPIOTestPin3); } if(led_enabled) { // Set LED back to default eMMC status // TODO: make it go back to its actual value before this program, // rather than the system default led_set_trigger(3, "mmc1"); } gpio_enabled = gpio_test_pin_enabled = false; } // Initialise and open the PRU int PRU::initialise(int pru_num, int frames_per_buffer, int spi_channels, bool xenomai_test_pin) { uint32_t *pruMem = 0; if(!gpio_enabled) { rt_printf("initialise() called before GPIO enabled\n"); return 1; } pru_number = pru_num; /* Set number of SPI ADC / DAC channels to use. This implicitly * also determines the sample rate relative to the audio clock * (half audio clock for 8 channels, full audio clock for 4, * double audio clock for 2) */ spi_num_channels = spi_channels; /* Initialize structure used by prussdrv_pruintc_intc */ /* PRUSS_INTC_INITDATA is found in pruss_intc_mapping.h */ tpruss_intc_initdata pruss_intc_initdata = PRUSS_INTC_INITDATA; /* Allocate and initialize memory */ prussdrv_init(); if(prussdrv_open(pru_number == 0 ? PRU_EVTOUT_0 : PRU_EVTOUT_1)) { rt_printf("Failed to open PRU driver\n"); return 1; } /* Map PRU's INTC */ prussdrv_pruintc_init(&pruss_intc_initdata); spi_buffer_frames = frames_per_buffer; audio_buffer_frames = spi_buffer_frames * spi_num_channels / 4; /* Map PRU memory to pointers */ prussdrv_map_prumem (PRUSS0_SHARED_DATARAM, (void **)&pruMem); pru_buffer_comm = (uint32_t *)&pruMem[PRU_MEM_COMM_OFFSET/sizeof(uint32_t)]; pru_buffer_audio_dac = (int16_t *)&pruMem[PRU_MEM_MCASP_OFFSET/sizeof(uint32_t)]; /* ADC memory starts 2(ch)*2(buffers)*bufsize samples later */ pru_buffer_audio_adc = &pru_buffer_audio_dac[4 * audio_buffer_frames]; if(spi_enabled) { prussdrv_map_prumem (pru_number == 0 ? PRUSS0_PRU0_DATARAM : PRUSS0_PRU1_DATARAM, (void **)&pruMem); pru_buffer_spi_dac = (uint16_t *)&pruMem[PRU_MEM_DAC_OFFSET/sizeof(uint32_t)]; /* ADC memory starts after N(ch)*2(buffers)*bufsize samples */ pru_buffer_spi_adc = &pru_buffer_spi_dac[2 * spi_num_channels * spi_buffer_frames]; } else { pru_buffer_spi_dac = pru_buffer_spi_adc = 0; } /* Set up flags */ pru_buffer_comm[PRU_SHOULD_STOP] = 0; pru_buffer_comm[PRU_CURRENT_BUFFER] = 0; pru_buffer_comm[PRU_BUFFER_FRAMES] = spi_buffer_frames; pru_buffer_comm[PRU_SHOULD_SYNC] = 0; pru_buffer_comm[PRU_SYNC_ADDRESS] = 0; pru_buffer_comm[PRU_SYNC_PIN_MASK] = 0; if(led_enabled) { pru_buffer_comm[PRU_LED_ADDRESS] = USERLED3_GPIO_BASE; pru_buffer_comm[PRU_LED_PIN_MASK] = USERLED3_PIN_MASK; } else { pru_buffer_comm[PRU_LED_ADDRESS] = 0; pru_buffer_comm[PRU_LED_PIN_MASK] = 0; } if(spi_enabled) { pru_buffer_comm[PRU_USE_SPI] = 1; pru_buffer_comm[PRU_SPI_NUM_CHANNELS] = spi_num_channels; } else { pru_buffer_comm[PRU_USE_SPI] = 0; pru_buffer_comm[PRU_SPI_NUM_CHANNELS] = 0; } /* Clear ADC and DAC memory */ if(spi_enabled) { for(int i = 0; i < PRU_MEM_DAC_LENGTH / 2; i++) pru_buffer_spi_dac[i] = 0; } for(int i = 0; i < PRU_MEM_MCASP_LENGTH / 2; i++) pru_buffer_audio_dac[i] = 0; /* If using GPIO test pin for Xenomai (for debugging), initialise the pointer now */ if(xenomai_test_pin && xenomai_gpio_fd < 0) { xenomai_gpio_fd = open("/dev/mem", O_RDWR); if(xenomai_gpio_fd < 0) rt_printf("Unable to open /dev/mem for GPIO test pin\n"); else { xenomai_gpio = (uint32_t *)mmap(0, GPIO_SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, xenomai_gpio_fd, TEST_PIN_GPIO_BASE); if(xenomai_gpio == MAP_FAILED) { rt_printf("Unable to map GPIO address for test pin\n"); xenomai_gpio = 0; close(xenomai_gpio_fd); xenomai_gpio_fd = -1; } } } return 0; } // Run the code image in the specified file int PRU::start() { /* Clear any old interrupt */ if(pru_number == 0) prussdrv_pru_clear_event(PRU_EVTOUT_0, PRU0_ARM_INTERRUPT); else prussdrv_pru_clear_event(PRU_EVTOUT_1, PRU1_ARM_INTERRUPT); /* Load and execute binary on PRU */ if(prussdrv_exec_code(pru_number, PRUcode, sizeof(PRUcode))) { rt_printf("Failed to execute PRU code\n"); return 1; } running = true; return 0; } // Main loop to read and write data from/to PRU void PRU::loop() { // Polling interval is 1/4 of the period RTIME sleepTime = PRU_SAMPLE_INTERVAL_NS * (spi_num_channels / 2) * spi_buffer_frames / 4; float *audioInBuffer, *audioOutBuffer; float *matrixInBuffer, *matrixOutBuffer; audioInBuffer = (float *)malloc(2 * audio_buffer_frames * sizeof(float)); audioOutBuffer = (float *)malloc(2 * audio_buffer_frames * sizeof(float)); matrixInBuffer = (float *)malloc(spi_num_channels * spi_buffer_frames * sizeof(float)); matrixOutBuffer = (float *)malloc(spi_num_channels * spi_buffer_frames * sizeof(float)); if(audioInBuffer == 0 || audioOutBuffer == 0) { rt_printf("Error: couldn't allocate audio buffers\n"); return; } if(matrixInBuffer == 0 || matrixOutBuffer == 0) { rt_printf("Error: couldn't allocate matrix buffers\n"); return; } while(!gShouldStop) { // Wait for PRU to move to buffer 1 while(pru_buffer_comm[PRU_CURRENT_BUFFER] == 0 && !gShouldStop) { rt_task_sleep(sleepTime); } if(gShouldStop) break; if(xenomai_gpio != 0) { // Set the test pin high xenomai_gpio[GPIO_SETDATAOUT] = TEST_PIN_MASK; } // Render from/to buffer 0 // Convert short (16-bit) samples to float for(unsigned int n = 0; n < 2 * audio_buffer_frames; n++) audioInBuffer[n] = (float)pru_buffer_audio_adc[n] / 32768.0; if(spi_enabled) { for(unsigned int n = 0; n < spi_num_channels * spi_buffer_frames; n++) matrixInBuffer[n] = (float)pru_buffer_spi_adc[n] / 65536.0; render(spi_buffer_frames, audio_buffer_frames, audioInBuffer, audioOutBuffer, matrixInBuffer, matrixOutBuffer); for(unsigned int n = 0; n < spi_num_channels * spi_buffer_frames; n++) { int out = matrixOutBuffer[n] * 65536.0; if(out < 0) out = 0; else if(out > 65535) out = 65535; pru_buffer_spi_dac[n] = (uint16_t)out; } } else render(0, audio_buffer_frames, audioInBuffer, audioOutBuffer, 0, 0); // Convert float back to short for(unsigned int n = 0; n < 2 * audio_buffer_frames; n++) { int out = audioOutBuffer[n] * 32768.0; if(out < -32768) out = -32768; else if(out > 32767) out = 32767; pru_buffer_audio_dac[n] = (int16_t)out; } if(xenomai_gpio != 0) { // Set the test pin high xenomai_gpio[GPIO_CLEARDATAOUT] = TEST_PIN_MASK; } // Wait for PRU to move to buffer 0 while(pru_buffer_comm[PRU_CURRENT_BUFFER] != 0 && !gShouldStop) { rt_task_sleep(sleepTime); } if(gShouldStop) break; if(xenomai_gpio != 0) { // Set the test pin high xenomai_gpio[GPIO_SETDATAOUT] = TEST_PIN_MASK; } // Render from/to buffer 1 // Convert short (16-bit) samples to float for(unsigned int n = 0; n < 2 * audio_buffer_frames; n++) audioInBuffer[n] = (float)pru_buffer_audio_adc[n + audio_buffer_frames * 2] / 32768.0; if(spi_enabled) { for(unsigned int n = 0; n < spi_num_channels * spi_buffer_frames; n++) matrixInBuffer[n] = (float)pru_buffer_spi_adc[n + spi_buffer_frames * spi_num_channels] / 65536.0; render(spi_buffer_frames, audio_buffer_frames, audioInBuffer, audioOutBuffer, matrixInBuffer, matrixOutBuffer); for(unsigned int n = 0; n < spi_num_channels * spi_buffer_frames; n++) { int out = matrixOutBuffer[n] * 65536.0; if(out < 0) out = 0; else if(out > 65535) out = 65535; pru_buffer_spi_dac[n + spi_buffer_frames * spi_num_channels] = (uint16_t)out; } } else render(0, audio_buffer_frames, audioInBuffer, audioOutBuffer, 0, 0); // Convert float back to short for(unsigned int n = 0; n < 2 * audio_buffer_frames; n++) { int out = audioOutBuffer[n] * 32768.0; if(out < -32768) out = -32768; else if(out > 32767) out = 32767; pru_buffer_audio_dac[n + audio_buffer_frames * 2] = (int16_t)out; } if(xenomai_gpio != 0) { // Set the test pin high xenomai_gpio[GPIO_CLEARDATAOUT] = TEST_PIN_MASK; } } // Tell PRU to stop pru_buffer_comm[PRU_SHOULD_STOP] = 1; free(audioInBuffer); free(audioOutBuffer); free(matrixInBuffer); free(matrixOutBuffer); } // Wait for an interrupt from the PRU indicate it is finished void PRU::waitForFinish() { if(!running) return; prussdrv_pru_wait_event (pru_number == 0 ? PRU_EVTOUT_0 : PRU_EVTOUT_1); if(pru_number == 0) prussdrv_pru_clear_event(PRU_EVTOUT_0, PRU0_ARM_INTERRUPT); else prussdrv_pru_clear_event(PRU_EVTOUT_1, PRU1_ARM_INTERRUPT); } // Turn off the PRU when done void PRU::disable() { /* Disable PRU and close memory mapping*/ prussdrv_pru_disable(pru_number); prussdrv_exit(); running = false; } // Debugging void PRU::setGPIOTestPin() { if(!xenomai_gpio) return; xenomai_gpio[GPIO_SETDATAOUT] = TEST_PIN2_MASK; } void PRU::clearGPIOTestPin() { if(!xenomai_gpio) return; xenomai_gpio[GPIO_CLEARDATAOUT] = TEST_PIN2_MASK; }
29.15251
122
0.706973
amilo
5070ee71783694d96984d3437a7658a0726cfb75
3,275
cpp
C++
libs/libvtrutil/test/test_expr_eval.cpp
amin1377/vtr-verilog-to-routing
700be36e479442fa41d8cb3ceb86e967f4dc078a
[ "MIT" ]
682
2015-07-10T00:39:26.000Z
2022-03-30T05:24:53.000Z
libs/libvtrutil/test/test_expr_eval.cpp
nbstrong/vtr-verilog-to-routing
c91800747378df13c008f3db92df43d6c1ebe38c
[ "MIT" ]
1,399
2015-07-24T22:09:09.000Z
2022-03-29T06:22:48.000Z
libs/libvtrutil/test/test_expr_eval.cpp
nbstrong/vtr-verilog-to-routing
c91800747378df13c008f3db92df43d6c1ebe38c
[ "MIT" ]
311
2015-07-09T13:59:48.000Z
2022-03-28T00:15:20.000Z
#include <limits> #include "catch2/catch_test_macros.hpp" #include "vtr_expr_eval.h" TEST_CASE("Simple Expressions", "[vtr_expr_eval]") { vtr::FormulaParser parser; vtr::t_formula_data vars; REQUIRE(parser.parse_formula("0", vars) == 0); REQUIRE(parser.parse_formula("42", vars) == 42); REQUIRE(parser.parse_formula("5 + 2", vars) == 7); REQUIRE(parser.parse_formula("5 + 10", vars) == 15); REQUIRE(parser.parse_formula("5 - 2", vars) == 3); REQUIRE(parser.parse_formula("5 - 10", vars) == -5); REQUIRE(parser.parse_formula("5 * 5", vars) == 25); REQUIRE(parser.parse_formula("5 / 5", vars) == 1); //Floor arithmetic REQUIRE(parser.parse_formula("5 / 10", vars) == 0); REQUIRE(parser.parse_formula("10 / 9", vars) == 1); REQUIRE(parser.parse_formula("5 % 10", vars) == 5); REQUIRE(parser.parse_formula("10 % 9", vars) == 1); REQUIRE(parser.parse_formula("5 < 10", vars) == 1); REQUIRE(parser.parse_formula("20 < 10", vars) == 0); REQUIRE(parser.parse_formula("5 > 10", vars) == 0); REQUIRE(parser.parse_formula("20 > 10", vars) == 1); } TEST_CASE("Negative Literals", "[vtr_expr_eval]") { //TODO: Currently unsupported, should support in the future... //REQUIRE(parser.parse_formula("-5 + 10", vars) == 5); //REQUIRE(parser.parse_formula("-10 + 5", vars) == -5); //REQUIRE(parser.parse_formula("-1", vars) == -1); } TEST_CASE("Bracket Expressions", "[vtr_expr_eval]") { vtr::FormulaParser parser; vtr::t_formula_data vars; REQUIRE(parser.parse_formula("20 / (4 + 1)", vars) == 4); REQUIRE(parser.parse_formula("(20 / 5) + 1", vars) == 5); REQUIRE(parser.parse_formula("20 / 5 + 1", vars) == 5); } TEST_CASE("Variable Expressions", "[vtr_expr_eval]") { vtr::FormulaParser parser; vtr::t_formula_data vars; vars.set_var_value("x", 5); vars.set_var_value("y", 10); REQUIRE(parser.parse_formula("x", vars) == 5); REQUIRE(parser.parse_formula("y", vars) == 10); REQUIRE(parser.parse_formula("x + y", vars) == 15); REQUIRE(parser.parse_formula("y + x", vars) == 15); REQUIRE(parser.parse_formula("x - y", vars) == -5); REQUIRE(parser.parse_formula("y - x", vars) == 5); REQUIRE(parser.parse_formula("x * y", vars) == 50); REQUIRE(parser.parse_formula("y * x", vars) == 50); REQUIRE(parser.parse_formula("x / y", vars) == 0); REQUIRE(parser.parse_formula("y / x", vars) == 2); } TEST_CASE("Function Expressions", "[vtr_expr_eval]") { vtr::FormulaParser parser; vtr::t_formula_data vars; REQUIRE(parser.parse_formula("min(5, 2)", vars) == 2); REQUIRE(parser.parse_formula("min(2, 5)", vars) == 2); //REQUIRE(parser.parse_formula("min(-5, 2)", vars) == -5); //Negative literals currently unsupported //REQUIRE(parser.parse_formula("min(-2, 5)", vars) == -2); REQUIRE(parser.parse_formula("max(5, 2)", vars) == 5); REQUIRE(parser.parse_formula("max(2, 5)", vars) == 5); //REQUIRE(parser.parse_formula("max(-5, 2)", vars) == 2); //Negative literals currently unsupported //REQUIRE(parser.parse_formula("max(-2, 5)", vars) == 5); REQUIRE(parser.parse_formula("gcd(20, 25)", vars) == 5); REQUIRE(parser.parse_formula("lcm(20, 25)", vars) == 100); }
35.989011
104
0.628397
amin1377
507148f5733bd6fa6ad7bcddc9a072175abe1c65
5,600
cpp
C++
win10/edge/test/typed_array.cpp
panopticoncentral/jsrt-wrappers
9e6352240a00ff622bbf0726f1fba363977313b9
[ "Apache-2.0" ]
12
2015-08-17T12:59:12.000Z
2021-10-10T02:54:40.000Z
win10/edge/test/typed_array.cpp
panopticoncentral/jsrt-wrappers
9e6352240a00ff622bbf0726f1fba363977313b9
[ "Apache-2.0" ]
null
null
null
win10/edge/test/typed_array.cpp
panopticoncentral/jsrt-wrappers
9e6352240a00ff622bbf0726f1fba363977313b9
[ "Apache-2.0" ]
5
2019-03-08T04:13:44.000Z
2019-12-17T09:51:09.000Z
// Copyright 2015 Paul Vick // // 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 "stdafx.h" #include "CppUnitTest.h" using namespace Microsoft::VisualStudio::CppUnitTestFramework; namespace jsrtwrapperstest { TEST_CLASS(typed_array) { public: MY_TEST_METHOD(empty_handle, "Test an empty typed_array handle.") { jsrt::typed_array<int> handle; Assert::AreEqual(handle.handle(), JS_INVALID_REFERENCE); Assert::IsFalse(handle.is_valid()); } MY_TEST_METHOD(no_context, "Test calls with no context.") { jsrt::runtime runtime = jsrt::runtime::create(); jsrt::context context = runtime.create_context(); jsrt::typed_array<short> array; TEST_NO_CONTEXT_CALL(jsrt::typed_array<short>::create(0)); { jsrt::context::scope scope(context); array = jsrt::typed_array<short>::create(0); } array.data(); array.data_size(); array.element_size(); array.type(); runtime.dispose(); } MY_TEST_METHOD(invalid_handle, "Test calls with an invalid handle.") { jsrt::runtime runtime = jsrt::runtime::create(); jsrt::context context = runtime.create_context(); { jsrt::context::scope scope(context); jsrt::typed_array<int> array; TEST_INVALID_ARG_CALL(array.data_size()); TEST_INVALID_ARG_CALL(array.element_size()); TEST_INVALID_ARG_CALL(array.data()); TEST_INVALID_ARG_CALL(array.type()); } runtime.dispose(); } MY_TEST_METHOD(create, "Test ::create method.") { jsrt::runtime runtime = jsrt::runtime::create(); jsrt::context context = runtime.create_context(); { jsrt::context::scope scope(context); jsrt::value value = jsrt::typed_array<short>::create(5); static_cast<jsrt::typed_array<short>>(value); jsrt::array_buffer buffer = jsrt::array_buffer::create(8); jsrt::typed_array<short> array = jsrt::typed_array<short>::create(buffer, 2, 3); jsrt::typed_array<int>::create(array); jsrt::array<int> base_array = jsrt::array<int>::create(5); jsrt::typed_array<int>::create(base_array); jsrt::typed_array<int>::create({ 1, 2, 3, 4 }); } runtime.dispose(); } MY_TEST_METHOD(types, "Test types.") { jsrt::runtime runtime = jsrt::runtime::create(); jsrt::context context = runtime.create_context(); { jsrt::context::scope scope(context); jsrt::typed_array<char>::create(1); jsrt::typed_array<unsigned char>::create(1); jsrt::typed_array<unsigned char, true>::create(1); jsrt::typed_array<short>::create(1); jsrt::typed_array<unsigned short>::create(1); jsrt::typed_array<int>::create(1); jsrt::typed_array<unsigned int>::create(1); jsrt::typed_array<float>::create(1); jsrt::typed_array<double>::create(1); } runtime.dispose(); } MY_TEST_METHOD(data, "Test data and size.") { jsrt::runtime runtime = jsrt::runtime::create(); jsrt::context context = runtime.create_context(); { jsrt::context::scope scope(context); jsrt::array_buffer buffer = jsrt::array_buffer::create(8); jsrt::typed_array<short> array = jsrt::typed_array<short>::create(buffer, 2, 3); Assert::AreEqual(array.type(), JsArrayTypeInt16); Assert::AreEqual(array.data_size(), 6u); Assert::AreEqual(array.element_size(), 2); Assert::IsNotNull(array.data()); } runtime.dispose(); } MY_TEST_METHOD(indexing, "Test indexing.") { jsrt::runtime runtime = jsrt::runtime::create(); jsrt::context context = runtime.create_context(); { jsrt::context::scope scope(context); jsrt::array_buffer buffer = jsrt::array_buffer::create(64); jsrt::typed_array<double> darray = jsrt::typed_array<double>::create(buffer, 0, 2); darray[0] = 10; darray[1] = 20; Assert::AreEqual(static_cast<double>(darray[0]), 10.0); Assert::AreEqual(static_cast<double>(darray[1]), 20.0); jsrt::typed_array<int> iarray = jsrt::typed_array<int>::create(buffer, 0, 2); iarray[0] = 30; iarray[1] = 40; Assert::AreEqual(static_cast<int>(iarray[0]), 30); Assert::AreEqual(static_cast<int>(iarray[1]), 40); } runtime.dispose(); } }; }
38.888889
99
0.560179
panopticoncentral
50720ddc98e40e3062cc0467ea069cc0a34e35e1
2,216
cpp
C++
examples/mixed_precision.cpp
tenglongcong/amgcl
61948e1a49c1cbc9fdb68c92d532c8b70e021516
[ "MIT" ]
504
2015-03-11T13:50:39.000Z
2022-03-20T13:08:55.000Z
examples/mixed_precision.cpp
tenglongcong/amgcl
61948e1a49c1cbc9fdb68c92d532c8b70e021516
[ "MIT" ]
209
2015-01-02T19:13:22.000Z
2022-03-30T06:44:12.000Z
examples/mixed_precision.cpp
tenglongcong/amgcl
61948e1a49c1cbc9fdb68c92d532c8b70e021516
[ "MIT" ]
92
2015-01-04T06:11:22.000Z
2022-03-24T09:49:12.000Z
#include <vector> #include <tuple> #include <amgcl/adapter/crs_tuple.hpp> #include <amgcl/make_solver.hpp> #include <amgcl/amg.hpp> #include <amgcl/coarsening/smoothed_aggregation.hpp> #include <amgcl/relaxation/spai0.hpp> #include <amgcl/solver/cg.hpp> #include <amgcl/profiler.hpp> #if defined(SOLVER_BACKEND_VEXCL) # include <amgcl/backend/vexcl.hpp> typedef amgcl::backend::vexcl<float> fBackend; typedef amgcl::backend::vexcl<double> dBackend; #else # ifndef SOLVER_BACKEND_BUILTIN # define SOLVER_BACKEND_BUILTIN # endif # include <amgcl/backend/builtin.hpp> typedef amgcl::backend::builtin<float> fBackend; typedef amgcl::backend::builtin<double> dBackend; #endif #include "sample_problem.hpp" namespace amgcl { profiler<> prof; } using amgcl::prof; int main() { // Combine single-precision preconditioner with a // double-precision Krylov solver. typedef amgcl::make_solver< amgcl::amg< fBackend, amgcl::coarsening::smoothed_aggregation, amgcl::relaxation::spai0 >, amgcl::solver::cg< dBackend > > Solver; std::vector<ptrdiff_t> ptr, col; std::vector<double> val, rhs; dBackend::params bprm; #ifdef SOLVER_BACKEND_VEXCL vex::Context ctx(vex::Filter::Env); std::cout << ctx << std::endl; bprm.q = ctx; #endif prof.tic("assemble"); int n = sample_problem(128, val, col, ptr, rhs); prof.toc("assemble"); #if defined(SOLVER_BACKEND_VEXCL) dBackend::matrix A_d(ctx, n, n, ptr, col, val); vex::vector<double> f(ctx, rhs); vex::vector<double> x(ctx, n); x = 0; #elif defined(SOLVER_BACKEND_BUILTIN) auto A_d = std::tie(n, ptr, col, val); std::vector<double> &f = rhs; std::vector<double> x(n, 0.0); #endif prof.tic("setup"); Solver S(std::tie(n, ptr, col, val), Solver::params(), bprm); prof.toc("setup"); std::cout << S << std::endl; int iters; double error; prof.tic("solve"); std::tie(iters, error) = S(A_d, f, x); prof.toc("solve"); std::cout << "Iterations: " << iters << std::endl << "Error: " << error << std::endl << prof << std::endl; }
25.471264
65
0.631318
tenglongcong
5073cabdf06bd2c6b1fb058f09d86187a69e7d87
460
cpp
C++
xasm/main.cpp
kiven-li/xscrip
ed762811aaf502ee20b5d00083926f7647def57d
[ "MIT" ]
15
2018-11-10T11:30:09.000Z
2022-02-28T06:00:57.000Z
xasm/main.cpp
kiven-li/xscrip
ed762811aaf502ee20b5d00083926f7647def57d
[ "MIT" ]
null
null
null
xasm/main.cpp
kiven-li/xscrip
ed762811aaf502ee20b5d00083926f7647def57d
[ "MIT" ]
10
2019-06-19T03:33:53.000Z
2021-08-20T01:24:42.000Z
#include "xasm.hpp" void PrintUsage () { printf ( "Usage:\tXASM Source.XASM [Executable.XSE]\n" ); printf ( "\n" ); printf ( "\t- File extensions are not required.\n" ); printf ( "\t- Executable name is optional; source name is used by default.\n" ); } int main(int argc, char* argv[]) { if(argc < 2) { PrintUsage(); return 0; } string file_name = argv[1]; xscript::xasm::xasm xm; xm.complier(file_name); }
19.166667
85
0.586957
kiven-li
50764aa5d14915050391a68c52defae4c4e6bf87
762
hpp
C++
resource/scene/Topology.hpp
szk/reprize
a827aa0247f7954f9f36ae573f97db1397645bf5
[ "BSD-2-Clause" ]
null
null
null
resource/scene/Topology.hpp
szk/reprize
a827aa0247f7954f9f36ae573f97db1397645bf5
[ "BSD-2-Clause" ]
null
null
null
resource/scene/Topology.hpp
szk/reprize
a827aa0247f7954f9f36ae573f97db1397645bf5
[ "BSD-2-Clause" ]
1
2019-03-11T20:58:41.000Z
2019-03-11T20:58:41.000Z
#ifndef TOPOLOGY_HPP_ #define TOPOLOGY_HPP_ #include "Common.hpp" #include "Space.hpp" #include "Metric.hpp" namespace reprize { namespace res { class TpNode { public: TpNode(void) {} virtual ~TpNode(void) {} private: Vec3 pos; }; class TpFace { public: TpFace(void) {} virtual ~TpFace(void) {} private: Vec3 pos; }; class TpEdge { public: TpEdge(void) {} virtual ~TpEdge(void) {} private: TpNode* to_node,* from_node; TpFace* r_face,* l_face; }; class Topology : public Space { public: Topology(aud::Audio* audio_) : Space("Topology", audio_) { } virtual ~Topology(void) {} private: virtual const bool Adopt(Node* node_) { return false; } }; } } #endif
12.290323
60
0.607612
szk
507838f9c3c3187129caf0b87c0d44969b2581c1
548
cpp
C++
leetcode/1-two-sum.cpp
rise-worlds/algorithm
74fb83ee12725d868ce57f5969f072c593898215
[ "MIT" ]
1
2019-06-10T09:33:37.000Z
2019-06-10T09:33:37.000Z
leetcode/1-two-sum.cpp
rise-worlds/leetcode
74fb83ee12725d868ce57f5969f072c593898215
[ "MIT" ]
null
null
null
leetcode/1-two-sum.cpp
rise-worlds/leetcode
74fb83ee12725d868ce57f5969f072c593898215
[ "MIT" ]
null
null
null
#include <vector> using namespace std; class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { vector<int> result; size_t i, j, length = nums.size(); for (i = 0; i < length; ++i) { for (j = i + 1; j < length; ++j) { if (nums[i] + nums[j] == target) { result.push_back(i); result.push_back(j); i = j = length; break; } } } return result; } };
24.909091
55
0.410584
rise-worlds
50805f648ac56f0cb79cd6e0d877f94cc75f8b91
1,474
cc
C++
SuperReads_RNA/global-1/jellyfish/unit_tests/test_simple_circular_buffer.cc
Kuanhao-Chao/multiStringTie
be37f9b4ae72b14e7cf645f24725b7186f66a816
[ "MIT" ]
255
2015-02-18T20:27:23.000Z
2022-03-18T18:55:35.000Z
SuperReads_RNA/global-1/jellyfish/unit_tests/test_simple_circular_buffer.cc
Kuanhao-Chao/multiStringTie
be37f9b4ae72b14e7cf645f24725b7186f66a816
[ "MIT" ]
350
2015-03-11T14:24:06.000Z
2022-03-29T03:54:10.000Z
SuperReads_RNA/global-1/jellyfish/unit_tests/test_simple_circular_buffer.cc
wrf/stringtie
2e99dccd9a2e2ce51cfddcb3896984fa773697f7
[ "MIT" ]
66
2015-02-19T00:21:38.000Z
2022-03-30T09:52:23.000Z
#include <gtest/gtest.h> #include <jellyfish/simple_circular_buffer.hpp> namespace { static const int capa = 16; typedef jellyfish::simple_circular_buffer::pre_alloc<int, capa> test_simple_circular_buffer; TEST(SimpleCircularBufferTest, FillEmpty) { int ary[capa]; test_simple_circular_buffer buffer(ary); EXPECT_EQ(capa, buffer.capacity()); EXPECT_TRUE(buffer.empty()); for(int i = 0; i < buffer.capacity(); ++i) { SCOPED_TRACE(::testing::Message() << "i=" << i); EXPECT_FALSE(buffer.full()); EXPECT_EQ(i, buffer.size()); buffer.push_back(i); EXPECT_EQ(i, buffer.back()); EXPECT_FALSE(buffer.empty()); } EXPECT_TRUE(buffer.full()); for(int i = 0; i < buffer.capacity(); ++i) { SCOPED_TRACE(::testing::Message() << "i=" << i); EXPECT_FALSE(buffer.empty()); EXPECT_EQ(i, buffer.front()); EXPECT_EQ(buffer.capacity() - i, buffer.size()); buffer.pop_front(); EXPECT_FALSE(buffer.full()); } EXPECT_TRUE(buffer.empty()); EXPECT_EQ(0, buffer.size()); } TEST(SimpleCircularBufferTest, Usefull) { int ary[capa]; test_simple_circular_buffer buffer(ary); EXPECT_EQ(capa, buffer.capacity()); int i = 0; for( ; i < buffer.capacity(); ++i) { EXPECT_TRUE(buffer.push_back()); buffer.back() = i; } for( ; i < 10 * buffer.capacity(); ++i) { EXPECT_EQ(i - capa, buffer.front()); buffer.pop_front(); EXPECT_TRUE(buffer.push_back()); buffer.back() = i; } } } // namespace {
25.859649
92
0.651289
Kuanhao-Chao
5082fbf2999dfbaaab448ecb36cabb919bd7f16c
1,095
hpp
C++
solver/include/policy/pure/PurePolicy.hpp
laurimi/multiagent-prediction-reward
b89fa52f78bb49447fc0049a7314a87b2b3e903e
[ "MIT" ]
9
2020-10-24T06:14:08.000Z
2021-07-13T13:08:30.000Z
solver/include/policy/pure/PurePolicy.hpp
laurimi/multiagent-prediction-reward
b89fa52f78bb49447fc0049a7314a87b2b3e903e
[ "MIT" ]
null
null
null
solver/include/policy/pure/PurePolicy.hpp
laurimi/multiagent-prediction-reward
b89fa52f78bb49447fc0049a7314a87b2b3e903e
[ "MIT" ]
null
null
null
#ifndef PUREPOLICY_HPP #define PUREPOLICY_HPP #include "PurePolicyExecutionState.hpp" namespace npgi { namespace policy { template <typename LocalAction, typename LocalObservation> struct PurePolicy { public: PurePolicy() : m_() {} void set_action(const PurePolicyExecutionState<LocalObservation>& es, const LocalAction& a) { m_[es] = a; } const LocalAction& get_action( const PurePolicyExecutionState<LocalObservation>& es) const { return m_.at(es); } PurePolicyExecutionState<LocalObservation> initial_execution_state() const { return PurePolicyExecutionState<LocalObservation>(); } void update_execution_state(PurePolicyExecutionState<LocalObservation>& e, const LocalAction& a, const LocalObservation& o) const { (void)a; // a is not needed for the state update e.observation_history_.emplace_back(o); } private: std::map<PurePolicyExecutionState<LocalObservation>, LocalAction> m_; }; } // namespace policy } // namespace npgi #endif // PUREPOLICY_HPP
26.707317
78
0.699543
laurimi
50835860f266eb3bcd3c53b222b1f7d038497a50
7,434
cpp
C++
src/input_handler.cpp
Ybalrid/gl_framework
4cf57b63306e0d95040ee7d7b5c710be0efb59de
[ "MIT", "Zlib", "BSD-3-Clause" ]
3
2019-09-16T01:42:10.000Z
2021-11-28T02:58:42.000Z
src/input_handler.cpp
Ybalrid/gl_framework
4cf57b63306e0d95040ee7d7b5c710be0efb59de
[ "MIT", "Zlib", "BSD-3-Clause" ]
null
null
null
src/input_handler.cpp
Ybalrid/gl_framework
4cf57b63306e0d95040ee7d7b5c710be0efb59de
[ "MIT", "Zlib", "BSD-3-Clause" ]
2
2020-01-28T23:33:00.000Z
2021-11-08T06:14:41.000Z
#include "input_handler.hpp" #include <iostream> #include "nameof.hpp" input_command* input_handler::keypress(SDL_Scancode code, uint16_t modifier) { if(keypress_commands[code]) keypress_commands[code]->modifier = modifier; return keypress_commands[code]; } input_command* input_handler::keyrelease(SDL_Scancode code, uint16_t modifier) { if(keyrelease_commands[code]) keyrelease_commands[code]->modifier = modifier; return keyrelease_commands[code]; } input_command* input_handler::keyany(SDL_Scancode code, uint16_t modifier) { if(keyany_commands[code]) keyany_commands[code]->modifier = modifier; return keyany_commands[code]; } input_command* input_handler::mouse_motion(sdl::Vec2i relative_motion, sdl::Vec2i absolute_position) { if(mouse_motion_command) { mouse_motion_command->relative_motion = relative_motion; mouse_motion_command->absolute_position = absolute_position; mouse_motion_command->click = 0; } return mouse_motion_command; } input_command* input_handler::mouse_button_down(uint8_t button, sdl::Vec2i absolute_position) { const auto command = mouse_button_down_commands[button - 1]; if(command) { command->absolute_position = absolute_position; command->relative_motion = { 0, 0 }; return command; } return nullptr; } input_command* input_handler::mouse_button_up(uint8_t button, sdl::Vec2i absolute_position) { const auto command = mouse_button_up_commands[button - 1]; if(command) { command->absolute_position = absolute_position; command->relative_motion = { 0, 0 }; return command; } return nullptr; } input_command* input_handler::gamepad_button_down(uint8_t controller, SDL_GameControllerButton button) { return gamepad_button_down_commands[controller][button]; } input_command* input_handler::gamepad_button_up(uint8_t controller, SDL_GameControllerButton button) { return gamepad_button_up_commands[controller][button]; } input_command* input_handler::gamepad_axis_motion(uint8_t controller, SDL_GameControllerAxis axis, float value, axis_range range) { if(const auto command = gamepad_axis_motion_commands[controller][axis]; command) { command->range = range; command->value = value; return command; } return nullptr; } input_command* input_handler::process_input_event(const sdl::Event& e) { switch(e.type) { //Keyboard events: case SDL_KEYDOWN: if(e.key.repeat || imgui && ((imgui->WantCaptureKeyboard || imgui->WantTextInput) && e.key.keysym.scancode != SDL_SCANCODE_GRAVE)) break; if(const auto command = keypress(e.key.keysym.scancode, e.key.keysym.mod); command) return command; return keyany(e.key.keysym.scancode, e.key.keysym.mod); case SDL_KEYUP: if(e.key.repeat || imgui && (imgui->WantCaptureKeyboard || imgui->WantTextInput)) break; if(const auto command = keyrelease(e.key.keysym.scancode, e.key.keysym.mod); command) return command; return keyany(e.key.keysym.scancode, e.key.keysym.mod); //Mouse: case SDL_MOUSEMOTION: if(imgui && imgui->WantCaptureMouse) break; return mouse_motion({ e.motion.xrel, e.motion.yrel }, { e.motion.x, e.motion.y }); case SDL_MOUSEBUTTONDOWN: if(imgui && imgui->WantCaptureMouse) break; return mouse_button_down(e.button.button, { e.button.x, e.button.y }); case SDL_MOUSEBUTTONUP: if(imgui && imgui->WantCaptureMouse) break; return mouse_button_up(e.button.button, { e.button.x, e.button.y }); //TODO controllers case SDL_CONTROLLERAXISMOTION: switch((SDL_GameControllerAxis)e.caxis.axis) { case SDL_CONTROLLER_AXIS_LEFTX: case SDL_CONTROLLER_AXIS_LEFTY: case SDL_CONTROLLER_AXIS_RIGHTX: case SDL_CONTROLLER_AXIS_RIGHTY: return gamepad_axis_motion(e.caxis.which, (SDL_GameControllerAxis)e.caxis.axis, float(e.caxis.value) / std::numeric_limits<Sint16> ::max(), axis_range::minus_one_to_one); case SDL_CONTROLLER_AXIS_TRIGGERLEFT: case SDL_CONTROLLER_AXIS_TRIGGERRIGHT: return gamepad_axis_motion(e.caxis.which, (SDL_GameControllerAxis)e.caxis.axis, float(e.caxis.value) / std::numeric_limits<Sint16> ::max(), axis_range::zero_to_one); default: return nullptr; } case SDL_CONTROLLERBUTTONDOWN: return gamepad_button_down(e.cbutton.which, (SDL_GameControllerButton)e.cbutton.button); case SDL_CONTROLLERBUTTONUP: std::cout << "controller button up\n"; return gamepad_button_up(e.cbutton.which, (SDL_GameControllerButton)e.cbutton.button); default: break; } return nullptr; } input_handler::input_handler() : keypress_commands { nullptr }, keyrelease_commands { nullptr }, keyany_commands { nullptr }, mouse_button_down_commands { nullptr }, mouse_button_up_commands { nullptr }, mouse_motion_command { nullptr }, gamepad_button_down_commands { nullptr }, gamepad_button_up_commands { nullptr }, gamepad_axis_motion_commands { nullptr } { } void input_handler::register_keypress(SDL_Scancode code, keyboard_input_command* command) { assert(code < SDL_NUM_SCANCODES); keypress_commands[code] = command; } void input_handler::register_keyrelease(SDL_Scancode code, keyboard_input_command* command) { assert(code < SDL_NUM_SCANCODES); keyrelease_commands[code] = command; } void input_handler::register_keyany(SDL_Scancode code, keyboard_input_command* command) { assert(code < SDL_NUM_SCANCODES); keyany_commands[code] = command; } void input_handler::register_mouse_motion_command(mouse_input_command* command) { mouse_motion_command = command; } void input_handler::register_mouse_button_down_command(uint8_t sdl_mouse_button_name, mouse_input_command* command) { assert(sdl_mouse_button_name > 1 && sdl_mouse_button_name < 5 && "This value should be one of SDL_BUTTON_{LEFT, MIDDLE, RIGHT, X1, X2}"); mouse_button_down_commands[sdl_mouse_button_name - 1] = command; } void input_handler::register_mouse_button_up_command(uint8_t sdl_mouse_button_name, mouse_input_command* command) { assert(sdl_mouse_button_name > 1 && sdl_mouse_button_name < 5 && "This value should be one of SDL_BUTTON_{LEFT, MIDDLE, RIGHT, X1, X2}"); mouse_button_up_commands[sdl_mouse_button_name - 1] = command; } void input_handler::register_gamepad_button_down_command(SDL_GameControllerButton button, uint8_t controller_id, gamepad_button_command* command) { assert(controller_id < 4); gamepad_button_down_commands[controller_id][button] = command; } void input_handler::register_gamepad_button_up_command(SDL_GameControllerButton button, uint8_t controller_id, gamepad_button_command* command) { assert(controller_id < 4); gamepad_button_up_commands[controller_id][button] = command; } void input_handler::register_gamepad_axis_motion_command(SDL_GameControllerAxis axis, uint8_t controller_id, gamepad_axis_motion_command* command) { assert(controller_id < 4); gamepad_axis_motion_commands[controller_id][axis] = command; } void input_handler::setup_imgui() { imgui = &ImGui::GetIO(); }
37.545455
180
0.723298
Ybalrid
5083b0da307258cea057cf3faf0c97471272f1ea
691
cpp
C++
cpp/src/exercise/e0300/e0203.cpp
ajz34/LeetCodeLearn
70ff8a3c17199a100819b356735cd9b13ff166a7
[ "MIT" ]
null
null
null
cpp/src/exercise/e0300/e0203.cpp
ajz34/LeetCodeLearn
70ff8a3c17199a100819b356735cd9b13ff166a7
[ "MIT" ]
null
null
null
cpp/src/exercise/e0300/e0203.cpp
ajz34/LeetCodeLearn
70ff8a3c17199a100819b356735cd9b13ff166a7
[ "MIT" ]
null
null
null
// https://leetcode-cn.com/problems/remove-linked-list-elements/ #include "extern.h" class S0203 { public: ListNode* removeElements(ListNode* head, int val) { ListNode* pre = new ListNode(-1); pre->next = head; ListNode* node = pre; while (node && node->next) { if (node->next->val == val) node->next = node->next->next; else node = node->next; } return pre->next; } }; TEST(e0300, e0203) { ListNode* head, * ans; head = new ListNode("[1,2,6,3,4,5,6]"); ans = new ListNode("[1,2,3,4,5]"); ASSERT_THAT(S0203().removeElements(head, 6)->to_vector(), ans->to_vector()); }
26.576923
80
0.545586
ajz34
5085681b31b439ff0f94f723c9331a7ab681249f
188
cpp
C++
applications/ObjectEditor/src/Objects/OEVisitorExtension.cpp
AluminiumRat/mtt
3052f8ad0ffabead05a1033e1d714a61e77d0aa8
[ "MIT" ]
null
null
null
applications/ObjectEditor/src/Objects/OEVisitorExtension.cpp
AluminiumRat/mtt
3052f8ad0ffabead05a1033e1d714a61e77d0aa8
[ "MIT" ]
null
null
null
applications/ObjectEditor/src/Objects/OEVisitorExtension.cpp
AluminiumRat/mtt
3052f8ad0ffabead05a1033e1d714a61e77d0aa8
[ "MIT" ]
null
null
null
#include <Objects/OEVisitorExtension.h> mtt::ObjectVisitor::ExtensionID OEVisitorExtension::extensionID = mtt::ObjectVisitor::registerExtension();
37.6
80
0.648936
AluminiumRat
508c16bfdd4299bbd1753abaeb6b92ee2480d668
614
cpp
C++
absmapalgorithms/AbsMapUnit.cpp
AaronTrip/hog2
96616b40f4173959b127011c76f3e649688e1a99
[ "MIT" ]
5
2020-08-03T09:43:26.000Z
2022-01-11T08:28:30.000Z
absmapalgorithms/AbsMapUnit.cpp
AaronTrip/hog2
96616b40f4173959b127011c76f3e649688e1a99
[ "MIT" ]
null
null
null
absmapalgorithms/AbsMapUnit.cpp
AaronTrip/hog2
96616b40f4173959b127011c76f3e649688e1a99
[ "MIT" ]
7
2017-07-31T13:01:28.000Z
2021-05-16T10:15:49.000Z
/* * AbsMapUnit.cpp * hog2 * * Created by Nathan Sturtevant on 4/27/07. * Copyright 2007 Nathan Sturtevant, University of Alberta. All rights reserved. * */ #include "AbsMapUnit.h" void AbsMapUnit::OpenGLDraw(const AbsMapEnvironment *me, const AbsMapSimulationInfo *) const { Map *map = me->GetMap(); GLdouble xx, yy, zz, rad; if ((loc.x >= map->GetMapWidth()) || (loc.y >= map->GetMapHeight())) return; map->GetOpenGLCoord(loc.x, loc.y, xx, yy, zz, rad); glColor3f(r, g, b); // if (getObjectType() == kDisplayOnly) // drawTriangle(xx, yy, zz, rad); // else DrawSphere(xx, yy, zz, rad); }
24.56
92
0.656352
AaronTrip
5091c34223efcd389884af71c4f2f909947d2240
1,962
cpp
C++
quiz7/quiz7/quiz7.cpp
keithwj1/FoothillCS2C
88da66fb5f3ab65a62a1fcd29c10816c7134766a
[ "MIT" ]
null
null
null
quiz7/quiz7/quiz7.cpp
keithwj1/FoothillCS2C
88da66fb5f3ab65a62a1fcd29c10816c7134766a
[ "MIT" ]
null
null
null
quiz7/quiz7/quiz7.cpp
keithwj1/FoothillCS2C
88da66fb5f3ab65a62a1fcd29c10816c7134766a
[ "MIT" ]
null
null
null
// quiz7.cpp : This file contains the 'main' function. Program execution begins and ends there. // #include <iostream> #include <queue> #include <vector> #include <assert.h> // Given a vector of elements in any order, return the 5th smallest element // For example: // std::vector<char> chars = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i'}; // assert(fifth_smallest_element(chars) == 'e'); template <typename T> const T& fifth_smallest_element(const std::vector<T>& elements) { // Fill in this part of the function, using an std::priority_queue std::priority_queue<T> cur; for (auto& elem : elements) { cur.push(elem); } while (!cur.empty()) { std::cout << cur.top() << std::endl; if (cur.size() == 5) { //Have to return the actual element in the vector because of & operator. auto it = std::find(elements.begin(), elements.end(), cur.top()); if (it != elements.end()) { return *it; } } cur.pop(); } return *elements.end(); } void question5() { std::vector<char> chars = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i' }; auto fifth = fifth_smallest_element(chars); assert(fifth == 'e'); } int main() { //std::cout << "Hello World!\n"; question5(); return 0; } // Run program: Ctrl + F5 or Debug > Start Without Debugging menu // Debug program: F5 or Debug > Start Debugging menu // Tips for Getting Started: // 1. Use the Solution Explorer window to add/manage files // 2. Use the Team Explorer window to connect to source control // 3. Use the Output window to see build output and other messages // 4. Use the Error List window to view errors // 5. Go to Project > Add New Item to create new code files, or Project > Add Existing Item to add existing code files to the project // 6. In the future, to open this project again, go to File > Open > Project and select the .sln file
33.827586
135
0.61315
keithwj1
509574214357962c1f3f5a122c9a8e6f0be115f6
1,299
cpp
C++
WineX/Sprite.cpp
MKachi/WineX
712243b5e3819fa77c2ae7262b9a846acd9c5945
[ "MIT" ]
4
2016-01-14T06:58:32.000Z
2018-04-13T07:26:21.000Z
WineX/Sprite.cpp
MKachi/WineX
712243b5e3819fa77c2ae7262b9a846acd9c5945
[ "MIT" ]
null
null
null
WineX/Sprite.cpp
MKachi/WineX
712243b5e3819fa77c2ae7262b9a846acd9c5945
[ "MIT" ]
null
null
null
#include "Sprite.h" #include "WineObject.h" #include "Transform.h" #include "TypeHelper.h" using namespace WineX; Sprite::Sprite(const std::wstring & filename) { _filename = filename; _name = TypeHelper<Sprite>::GetType(); } Sprite::~Sprite() { SAFE_RELEASE(_texture); SAFE_RELEASE(_sprite); } void Sprite::Init() { D3DXIMAGE_INFO info; D3DXGetImageInfoFromFile(_filename.c_str(), &info); D3DXCreateSprite(_parent->GetDevice(), &_sprite); D3DXCreateTextureFromFileEx(_parent->GetDevice(), _filename.c_str(), D3DX_DEFAULT_NONPOW2, D3DX_DEFAULT_NONPOW2, 0, 1, D3DFMT_UNKNOWN, D3DPOOL_DEFAULT, D3DX_DEFAULT, D3DX_DEFAULT, NULL, NULL, NULL, &_texture); _transform = _parent->GetTransform(); } void Sprite::Update() { _sprite->Begin(D3DXSPRITE_ALPHABLEND | D3DXSPRITE_SORT_TEXTURE); _sprite->Draw(_texture, nullptr, nullptr, &D3DXVECTOR3(_transform->GetPosition().x, _transform->GetPosition().y, 0), 0xffffffff); _sprite->End(); } void Sprite::SetTexture(const std::wstring & filename) { _filename = filename; D3DXIMAGE_INFO info; D3DXGetImageInfoFromFile(_filename.c_str(), &info); D3DXCreateTextureFromFileEx(_parent->GetDevice(), _filename.c_str(), info.Width, info.Height, 0, 1, D3DFMT_UNKNOWN, D3DPOOL_DEFAULT, D3DX_DEFAULT, D3DX_DEFAULT, NULL, NULL, NULL, &_texture); }
27.638298
180
0.756736
MKachi
509fb3626e61b0e386fdef201ed76273074babd1
13,048
cpp
C++
VoiceDialog.cpp
fioresoft/NO5
0acb1fdf191e3aa1e6f082ae996c1bf2a545e6c4
[ "MIT" ]
6
2017-06-01T01:28:11.000Z
2022-01-06T13:24:42.000Z
VoiceDialog.cpp
fioresoft/NO5
0acb1fdf191e3aa1e6f082ae996c1bf2a545e6c4
[ "MIT" ]
null
null
null
VoiceDialog.cpp
fioresoft/NO5
0acb1fdf191e3aa1e6f082ae996c1bf2a545e6c4
[ "MIT" ]
2
2021-07-05T01:17:23.000Z
2022-01-06T13:24:44.000Z
// VoiceDialog.cpp: implementation of the CVoiceDialog class. // ////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "resource.h" #include "VoiceDialog.h" #include "imainframe.h" #include "no5app.h" #include "usrmsgs.h" ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// CVoiceDialog::CVoiceDialog():m_btTalk(this,1) { m_bConnected = false; } CVoiceDialog::~CVoiceDialog() { m_ImgList.Destroy(); } LRESULT CVoiceDialog::OnInitDialog(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled) { USES_CONVERSION; // center the dialog on the screen CenterWindow(); // register object for message filtering and idle updates CMessageLoop* pLoop = _Module.GetMessageLoop(); ATLASSERT(pLoop != NULL); pLoop->AddMessageFilter(this); //pLoop->AddIdleHandler(this); //UIAddChildWindowContainer(m_hWnd); m_lv.SubclassWindow(GetDlgItem(IDC_LIST1)); m_status = GetDlgItem(IDC_STATUS); m_pbIn = GetDlgItem(IDC_PROGRESS_INPUT); m_pbOut = GetDlgItem(IDC_PROGRESS_OUTPUT); m_btConn = GetDlgItem(IDC_BUTTON_CONNECT); m_btTalk.SubclassWindow(GetDlgItem(IDC_BUTTON_TALK)); CreateTheImgList(); // setup list view if(!m_ImgList.IsNull()){ m_lv.SetImageList(m_ImgList,LVSIL_SMALL); } LPCTSTR cols[] = { _T("users"),_T("muted")}; int width[] = {0,0}; const int count = sizeof(cols)/sizeof(cols[0]); int i; CRect rc; m_lv.GetClientRect(&rc); width[1] = m_lv.GetStringWidth(" muted "); width[0] = rc.Width() - width[1]; for(i=0;i<count;i++){ m_lv.InsertColumn(i,cols[i],LVCFMT_LEFT,width[i],i); } // setup progress bars m_pbIn.SetRange(0,100); m_pbOut.SetRange(0,100); m_pbIn.SetStep(1); m_pbOut.SetStep(1); m_pbIn.SetPos(0); m_pbOut.SetPos(0); // setup button m_brush.CreateSolidBrush(0x00FF00); DlgResize_Init(true,false,WS_THICKFRAME | WS_CLIPCHILDREN); CComBSTR clsid(CLSID_YAcs); LPCTSTR pclsid = OLE2CT(clsid); m_ax.Create(m_hWnd,rcDefault,pclsid,WS_CHILD); HRESULT hr = m_ax.QueryControl(&m_sp); if(SUCCEEDED(hr)){ hr = YacsSource::DispEventAdvise(m_sp); ATLASSERT(SUCCEEDED(hr)); // or use that //GetDlgControl(IDC_EXPLORER1,IID_IWebBrowser2,(void **)&m_sp); if(SUCCEEDED(hr)){ //hr = m_sp->leaveConference(); CComBSTR bs; CString s; bs = (LPCTSTR)m_name; hr = m_sp->put_userName(bs); ATLASSERT(SUCCEEDED(hr)); bs = (LPCTSTR)m_server; // hr = m_sp->put_hostName(bs); // ATLASSERT(SUCCEEDED(hr)); s.Empty(); s.Format("ch/%s::%s",(LPCTSTR)m_room,(LPCTSTR)m_rmid); bs = (LPCTSTR)s; hr = m_sp->put_confName(bs); s.Empty(); s.Format("mc(7,0,0,437)&u=%s&ia=us",(LPCTSTR)m_name); bs = (LPCTSTR)s; hr = m_sp->put_appInfo(bs); ATLASSERT(SUCCEEDED(hr)); bs = (LPCTSTR)m_cookie; hr = m_sp->put_confKey(bs); ATLASSERT(SUCCEEDED(hr)); //bs = (LPCTSTR)m_name; // hr = m_sp->loadSound(bs); // ATLASSERT(SUCCEEDED(hr)); ATLASSERT(SUCCEEDED(hr)); //m_sp->put_inputGain(100); //m_sp->put_outputGain(100); //m_sp->put_inputAGC(100); //m_sp->put_inputSource(100); Connect(); } } return TRUE; } LRESULT CVoiceDialog::OnDestroy(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled) { HRESULT hr = YacsSource::DispEventUnadvise(m_sp); ATLASSERT(SUCCEEDED(hr)); CMessageLoop* pLoop = _Module.GetMessageLoop(); ATLASSERT(pLoop != NULL); pLoop->RemoveMessageFilter(this); return 0; } LRESULT CVoiceDialog::OnNCDestroy(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled) { CWindow wnd = g_app.GetMainFrame()->GetHandle(); ATLASSERT(wnd.IsWindow()); wnd.PostMessage(NO5WM_VOICEDLGDEL,0,(LPARAM)this); bHandled = FALSE; return 0; } LRESULT CVoiceDialog::OnClose(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled) { if(m_bConnected) Disconnect(); DestroyWindow(); return 0; } LRESULT CVoiceDialog::OnButtonConnect(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/) { SwitchConnect(); return 0; } LRESULT CVoiceDialog::OnCtlColorBtn(UINT /*uMsg*/, WPARAM wParam, LPARAM lParam, BOOL& bHandled) { HWND hWnd = HWND(lParam); LRESULT res = 0; if(hWnd == m_btTalk.m_hWnd){ //CDCHandle dc((HDC)wParam); //dc.SetBkColor(0x00ff00); //dc.SelectBrush(m_brush); res = LRESULT(HBRUSH(m_brush)); } else{ bHandled = FALSE; } return res; } LRESULT CVoiceDialog::OnTalkDown(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled) { HRESULT hr = m_sp->startTransmit(); ATLASSERT(SUCCEEDED(hr)); SetCapture(); bHandled = FALSE; return 0; } LRESULT CVoiceDialog::OnTalkUp(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled) { ReleaseCapture(); bHandled = FALSE; return 0; } LRESULT CVoiceDialog::OnTalkCaptureChanged(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled) { HRESULT hr = m_sp->stopTransmit(); ATLASSERT(SUCCEEDED(hr)); return 0; } LRESULT CVoiceDialog::OnButtonFree(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/) { CButton bt = GetDlgItem(IDC_CHECK_FREE); HRESULT hr = S_OK; UINT uDebug; switch(uDebug = bt.GetCheck()){ case BST_CHECKED: hr = m_sp->startTransmit(); break; case BST_UNCHECKED: hr = m_sp->stopTransmit(); break; default: break; } ATLASSERT(SUCCEEDED(hr)); return 0; } LRESULT CVoiceDialog::OnLVItemChanged(int /*idCtrl*/, LPNMHDR pnmh, BOOL& bHandled) { LPNMLISTVIEW pnmv = (LPNMLISTVIEW)pnmh; UINT uOld = pnmv->uOldState & LVIS_STATEIMAGEMASK; if (uOld != INDEXTOSTATEIMAGEMASK(0)) { UINT uNew = pnmv->uNewState & LVIS_STATEIMAGEMASK; if(uOld != uNew){ CString s; m_lv.GetItemText(pnmv->iItem,0,s); if(!s.IsEmpty()){ HRESULT hr = S_OK; CComBSTR bname = s; LONG key = m_users.Lookup(s); if(uNew == INDEXTOSTATEIMAGEMASK(2)) { hr = m_sp->muteSource(key,bname); } else if (uNew == INDEXTOSTATEIMAGEMASK(1)) { hr = m_sp->unmuteSource(key,bname); } ATLASSERT(SUCCEEDED(hr)); } } } return 0; } HRESULT __stdcall CVoiceDialog::OnSourceEntry(LONG sourceId, BSTR sourceName) { USES_CONVERSION; CString name = OLE2CT(sourceName); m_lv.InsertItem(0,name,0); m_users.Add(name,sourceId); return S_OK; } HRESULT __stdcall CVoiceDialog::OnSourceExit(LONG sourceId, BSTR sourceName) { int idx = FindLVItem(sourceName); if(idx >= 0){ USES_CONVERSION; CString s = OLE2CT(sourceName); m_lv.DeleteItem(idx); m_users.Remove(s); } return S_OK; } HRESULT __stdcall CVoiceDialog::OnRemoteSourceOnAir(LONG sourceId, BSTR sourceName) { int idx = FindLVItem(sourceName); if(idx >= 0){ m_lv.SetItem(idx,0,LVIF_IMAGE,NULL,1,0,0,0); m_lv.EnsureVisible(idx,FALSE); USES_CONVERSION; CWindow wnd = GetDlgItem(IDC_LABEL_TALKING); CString name = sourceName; CString s; s.Format("%s is talking",(LPCTSTR)name); wnd.SetWindowText(s); } return S_OK; } HRESULT __stdcall CVoiceDialog::OnRemoteSourceOffAir(LONG sourceId, BSTR sourceName) { int idx = FindLVItem(sourceName); if(idx >= 0){ m_lv.SetItem(idx,0,LVIF_IMAGE,NULL,0,0,0,0); //USES_CONVERSION; CWindow wnd = GetDlgItem(IDC_LABEL_TALKING); //CString name = sourceName; //CString s; wnd.SetWindowText(""); } return S_OK; } HRESULT __stdcall CVoiceDialog::OnLocalOnAir() { CComBSTR name = m_name; int idx = FindLVItem(name); if(idx >= 0){ m_lv.SetItem(idx,0,LVIF_IMAGE,NULL,1,0,0,0); CWindow wnd = GetDlgItem(IDC_LABEL_TALKING); //CString s; //s.Format("%s is talking"); wnd.SetWindowText("you are talking"); } return S_OK; } HRESULT __stdcall CVoiceDialog::OnLocalOffAir() { CComBSTR name = m_name; int idx = FindLVItem(name); if(idx >= 0){ m_lv.SetItem(idx,0,LVIF_IMAGE,NULL,0,0,0,0); CWindow wnd = GetDlgItem(IDC_LABEL_TALKING); //CString s; //s.Format("%s is talking"); wnd.SetWindowText(""); wnd = GetDlgItem(IDC_LABEL_REPORT); wnd.SetWindowText(""); } return S_OK; } HRESULT __stdcall CVoiceDialog::OnInputMuteChange(LONG mute) { #ifdef _DEBUG CString s; s.Format("OnInputMuteChange: %ld",mute); m_status.SetWindowText(s); #endif return S_OK; } HRESULT __stdcall CVoiceDialog::OnMonitorGainChange(SHORT gain) { return S_OK; } HRESULT __stdcall CVoiceDialog::OnInputSourceChange(SHORT source) { #ifdef _DEBUG CString s; s.Format("input source change: %d",(int)source); m_status.SetWindowText(s); #endif return S_OK; } HRESULT __stdcall CVoiceDialog::OnMonitorMuteChange(LONG mute) { #ifdef _DEBUG CString s; s.Format("monitor mute change: %ld",mute); m_status.SetWindowText(s); #endif return S_OK; } HRESULT __stdcall CVoiceDialog::OnSystemConnectFailure(LONG code, BSTR message) { CString msg; USES_CONVERSION; msg.Format("Error: %d - %s",code,OLE2CT(message)); m_status.SetWindowText(msg); Disconnect(); return S_OK; } HRESULT __stdcall CVoiceDialog::OnAudioError(LONG code, BSTR message) { CString msg; USES_CONVERSION; msg.Format("Audio Error: %d - %s",code,OLE2CT(message)); m_status.SetWindowText(msg); return S_OK; } HRESULT __stdcall CVoiceDialog::OnSourceMuted(LONG numMuting, BSTR sourceName) { int idx = FindLVItem(sourceName); if(idx >= 0){ CString s; s.Format("%d",(int)numMuting); m_lv.SetItemText(idx,1,s); } return S_OK; } HRESULT __stdcall CVoiceDialog::OnSourceUnmuted(LONG numMuting, BSTR sourceName) { int idx = FindLVItem(sourceName); if(idx >= 0){ CString s; s.Format("%d",(int)numMuting); m_lv.SetItemText(idx,1,s); } return S_OK; } HRESULT __stdcall CVoiceDialog::OnTransmitReport(INT numReceiving, INT numTotal) { CString s; CWindow wnd = GetDlgItem(IDC_LABEL_REPORT); s.Format("%d/%d",numReceiving,numTotal); wnd.SetWindowText(s); return S_OK; } HRESULT __stdcall CVoiceDialog::OnConferenceReady() { m_status.SetWindowText("conference ready!"); return S_OK; } HRESULT __stdcall CVoiceDialog::OnConferenceNotReady() { m_status.SetWindowText("conference not ready"); return S_OK; } HRESULT __stdcall CVoiceDialog::OnInputLevelChange(SHORT level) { m_pbIn.SetPos(100 + level); return S_OK; } HRESULT __stdcall CVoiceDialog::OnOutputLevelChange(SHORT level) { m_pbOut.SetPos(100 + level); return S_OK; } HRESULT __stdcall CVoiceDialog::OnSystemConnect() { m_status.SetWindowText("connected"); return S_OK; } HRESULT __stdcall CVoiceDialog::OnSystemDisconnect() { m_status.SetWindowText("disconnected"); m_bConnected = false; m_sp->leaveConference(); m_lv.DeleteAllItems(); m_btConn.SetWindowText("connect"); return S_OK; } HRESULT __stdcall CVoiceDialog::OnOutputGainChange(SHORT gain) { return S_OK; } HRESULT __stdcall CVoiceDialog::OnOutputMuteChange(LONG mute) { #ifdef _DEBUG CString s; s.Format("output mute change %ld",mute); m_status.SetWindowText(s); #endif return S_OK; } HRESULT __stdcall CVoiceDialog::OnInputGainChange(SHORT gain) { return S_OK; } void CVoiceDialog::CreateTheImgList(void) { m_ImgList.Create(16,16,ILC_MASK | ILC_COLOR,3,0); ATLASSERT(!m_ImgList.IsNull()); if(!m_ImgList.IsNull()){ HICON hIcon; hIcon = (HICON)::LoadImage(_Module.GetResourceInstance(),MAKEINTRESOURCE(IDR_MAINFRAME),IMAGE_ICON, 16,16,LR_DEFAULTCOLOR); if(hIcon){ m_ImgList.AddIcon(hIcon); DestroyIcon(hIcon); hIcon = (HICON)::LoadImage(_Module.GetResourceInstance(),MAKEINTRESOURCE(IDI_TALKING),IMAGE_ICON, 16,16,LR_DEFAULTCOLOR); if(hIcon){ m_ImgList.AddIcon(hIcon); DestroyIcon(hIcon); hIcon = (HICON)::LoadImage(_Module.GetResourceInstance(),MAKEINTRESOURCE(IDI_BUD_OFF),IMAGE_ICON, 16,16,LR_DEFAULTCOLOR); if(hIcon){ m_ImgList.AddIcon(hIcon); DestroyIcon(hIcon); } } } ATLASSERT(m_ImgList.GetImageCount() == 3); } } void CVoiceDialog::SwitchConnect(void) { if(!m_bConnected){ Connect(); } else{ Disconnect(); } } void CVoiceDialog::Connect(void) { HRESULT hr; hr = m_sp->createAndJoinConference(); if(SUCCEEDED(hr)){ m_btConn.SetWindowText("Disconnect"); m_bConnected = true; } ATLASSERT(SUCCEEDED(hr)); } void CVoiceDialog::Disconnect(void) { HRESULT hr; hr = m_sp->leaveConference(); if(SUCCEEDED(hr)){ m_lv.DeleteAllItems(); m_btConn.SetWindowText("Connect"); m_bConnected = false; } ATLASSERT(SUCCEEDED(hr)); } int CVoiceDialog::FindLVItem(BSTR name) { USES_CONVERSION; LPCTSTR p = OLE2CT(name); LV_FINDINFO fi = {0}; fi.flags = LVFI_STRING; fi.psz = p; return m_lv.FindItem(&fi,-1); }
23.853748
112
0.664086
fioresoft
50a02a9cc221a86f0e686ab7f65508f4b3ffacc0
362
cpp
C++
Codeforces 734B.cpp
Jvillegasd/Codeforces
ffdd2d5db1dabc7ff76f8f92270c79233a77b933
[ "MIT" ]
null
null
null
Codeforces 734B.cpp
Jvillegasd/Codeforces
ffdd2d5db1dabc7ff76f8f92270c79233a77b933
[ "MIT" ]
null
null
null
Codeforces 734B.cpp
Jvillegasd/Codeforces
ffdd2d5db1dabc7ff76f8f92270c79233a77b933
[ "MIT" ]
null
null
null
#include <stdio.h> using namespace std; int main(){ int k2, k3, k5, k6, sum = 0; scanf("%d %d %d %d", &k2, &k3, &k5, &k6); while(k2 > 0 && k5 > 0 && k6 > 0){ k2--; k5--; k6--; sum += 256; } while(k2 > 0 && k3 > 0){ k2--; k3--; sum += 32; } printf("%d\n", sum); return 0; }
17.238095
45
0.367403
Jvillegasd
50a2d687807090ccf6d31a66041c36df71dc46da
2,207
hpp
C++
baseclass/headers/world.hpp
HxHexa/quang-advCG-raytracer
605f7dfcc9237f331d456646b7653ad0f26c0cc4
[ "MIT" ]
null
null
null
baseclass/headers/world.hpp
HxHexa/quang-advCG-raytracer
605f7dfcc9237f331d456646b7653ad0f26c0cc4
[ "MIT" ]
null
null
null
baseclass/headers/world.hpp
HxHexa/quang-advCG-raytracer
605f7dfcc9237f331d456646b7653ad0f26c0cc4
[ "MIT" ]
null
null
null
/* world.hpp - header for world - a collection of objects and lights in scene * Quang Tran - 10/9/19 * */ #pragma once #include "object.hpp" #include "sphere.hpp" #include "arealight.hpp" #include "ray.hpp" #include "intersection.hpp" #include "comps.hpp" #include <vector> #include <memory> class World { private: std::vector<std::shared_ptr<Object>> objectsArray; std::vector<std::shared_ptr<AreaLight>> lightsArray; public: World(); static World DefaultWorld(); //adding stuffs funcs void addLight(std::shared_ptr<AreaLight>); void addObject(std::shared_ptr<Object>); //removing stuffs funcs void removeLight(std::shared_ptr<AreaLight>); void removeObject(std::shared_ptr<Object>); //getter funcs std::shared_ptr<Object> getObject(int) const; std::shared_ptr<AreaLight> getLight(int) const; //world functions std::vector<Intersection> intersectWorld(const Ray r); bool isShadowed(const Tuple lightPos, Tuple point); Color lighting(const std::shared_ptr<Object>, const AreaLight, const Tuple, const Tuple, const Tuple); Color reflectedColor(const Comps c, const int remaining); Color refractedColor(const Comps c, int remaining); Color shadeHit(const Comps c, const int remaining); Color colorAt(const Ray r, const int remaining); }; inline World World::DefaultWorld() { World defaultWorld; std::shared_ptr<AreaLight> defaultLight = std::make_shared<AreaLight>(Tuple::Point(-10, 10, -10), Tuple::Point(-10, 10, -10), Tuple::Point(-10, 10, -10), 1, 1, Color(1, 1, 1)); defaultWorld.addLight(defaultLight); std::shared_ptr<Sphere> s1 = std::make_shared<Sphere>(); Material m; Color c(0.8, 1.0, 0.6); m.setColor(c); m.setDiffuse(0.7); m.setSpecular(0.2); s1 -> setMaterial(m); std::shared_ptr<Sphere> s2 = std::make_shared<Sphere>(); //Material m2; //Color c2(1, 0, 0); //m2.setColor(c2); //s2.setMaterial(m2); s2 -> setTransform(Matrix::Scaling(0.5, 0.5, 0.5)); defaultWorld.addObject(s1); defaultWorld.addObject(s2); return defaultWorld; }
31.084507
180
0.652469
HxHexa
50a6ec99bb741660f02ed81088141380974f29c4
669
hpp
C++
coordGraph/coordGraph.hpp
ytuza/proyecto
3ebd08518c80180063262810ed9515cb94a2b735
[ "MIT" ]
null
null
null
coordGraph/coordGraph.hpp
ytuza/proyecto
3ebd08518c80180063262810ed9515cb94a2b735
[ "MIT" ]
null
null
null
coordGraph/coordGraph.hpp
ytuza/proyecto
3ebd08518c80180063262810ed9515cb94a2b735
[ "MIT" ]
null
null
null
#pragma once #include "graph/graph.hpp" #include <QPointF> #include <deque> class CoordGraph : public Graph<QPointF, double> { private: std::deque<NodeType *> randomGenNodes(int nodesN, double limitA, double limitB); void sortNodes(); double distance(NodeType *a, NodeType *b); void randomGenEdges(unsigned int maxEdges, double distance); public: using EdgeType = Edge<Graph<QPointF, double>>; void randomGeneration(int nodesN, int edgesN, double distance, double limitA, double limitB); void removeNodeRange(QPointF first, QPointF last); std::pair<double, std::deque<EdgeType *>> TreeA(NodeType *start,NodeType *end); };
26.76
82
0.714499
ytuza
50a89231515514681dc6eb2c5b181d33c2497d8b
7,351
cpp
C++
project/driver/src/DbcEntries.cpp
mkhon/ezRETS
7040e80061da719b5a2d56a80431198962f57893
[ "ICU" ]
20
2015-07-11T15:54:42.000Z
2022-02-05T04:55:24.000Z
project/driver/src/DbcEntries.cpp
mkhon/ezRETS
7040e80061da719b5a2d56a80431198962f57893
[ "ICU" ]
5
2015-01-12T22:38:56.000Z
2021-01-16T01:08:18.000Z
project/driver/src/DbcEntries.cpp
NationalAssociationOfRealtors/ezRETS
7040e80061da719b5a2d56a80431198962f57893
[ "ICU" ]
13
2015-04-05T03:28:20.000Z
2021-01-13T16:52:52.000Z
/* * Copyright (C) 2005 National Association of REALTORS(R) * * All rights reserved. * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, copy, * modify, merge, publish, distribute, and/or sell copies of the * Software, and to permit persons to whom the Software is furnished * to do so, provided that the above copyright notice(s) and this * permission notice appear in all copies of the Software and that * both the above copyright notice(s) and this permission notice * appear in supporting documentation. */ #include "OdbcEntry.h" #include "RetsDBC.h" namespace odbcrets { class SQLAllocStmt : public DbcOdbcEntry { public: SQLAllocStmt(SQLHDBC dbc, SQLHSTMT *StatementHandlePtr) : DbcOdbcEntry(dbc), mStatementHandlePtr(StatementHandlePtr) { } protected: SQLRETURN UncaughtOdbcEntry() { return mDbc->SQLAllocStmt(mStatementHandlePtr); } private: SQLHSTMT* mStatementHandlePtr; }; class SQLConnect : public DbcOdbcEntry { public: SQLConnect(SQLHDBC ConnectionHandle, SQLCHAR *DataSource, SQLSMALLINT DataSourceLength, SQLCHAR *UserName, SQLSMALLINT UserLength, SQLCHAR *Authentication, SQLSMALLINT AuthLength) : DbcOdbcEntry(ConnectionHandle), mDataSource(DataSource), mDataSourceLength(DataSourceLength), mUserName(UserName), mUserLength(UserLength), mAuthentication(Authentication), mAuthLength(AuthLength) { } protected: SQLRETURN UncaughtOdbcEntry() { return mDbc->SQLConnect(mDataSource, mDataSourceLength, mUserName, mUserLength, mAuthentication, mAuthLength); } private: SQLCHAR* mDataSource; SQLSMALLINT mDataSourceLength; SQLCHAR* mUserName; SQLSMALLINT mUserLength; SQLCHAR* mAuthentication; SQLSMALLINT mAuthLength; }; class SQLDisconnect : public DbcOdbcEntry { public: SQLDisconnect(SQLHDBC ConnectionHandle) : DbcOdbcEntry(ConnectionHandle) { } protected: SQLRETURN UncaughtOdbcEntry() { return mDbc->SQLDisconnect(); } }; class SQLDriverConnect : public DbcOdbcEntry { public: SQLDriverConnect(SQLHDBC ConnectionHandle, SQLHWND WindowHandle, SQLCHAR* InConnectionString, SQLSMALLINT InStringLength, SQLCHAR* OutConnectionString, SQLSMALLINT BufferLength, SQLSMALLINT* OutStringLengthPtr, SQLUSMALLINT DriverCompletion) : DbcOdbcEntry(ConnectionHandle), mWindowHandle(WindowHandle), mInConnectionString(InConnectionString), mInStringLength(InStringLength), mOutConnectionString(OutConnectionString), mBufferLength(BufferLength), mOutStringLengthPtr(OutStringLengthPtr), mDriverCompletion(DriverCompletion) { } protected: SQLRETURN UncaughtOdbcEntry() { return mDbc->SQLDriverConnect(mWindowHandle, mInConnectionString, mInStringLength, mOutConnectionString, mBufferLength, mOutStringLengthPtr, mDriverCompletion); } private: SQLHWND mWindowHandle; SQLCHAR* mInConnectionString; SQLSMALLINT mInStringLength; SQLCHAR* mOutConnectionString; SQLSMALLINT mBufferLength; SQLSMALLINT* mOutStringLengthPtr; SQLUSMALLINT mDriverCompletion; }; class SQLGetInfo : public DbcOdbcEntry { public: SQLGetInfo(SQLHDBC ConnectionHandle, SQLUSMALLINT InfoType, SQLPOINTER InfoValue, SQLSMALLINT BufferLength, SQLSMALLINT *StringLength) : DbcOdbcEntry(ConnectionHandle), mInfoType(InfoType), mInfoValue(InfoValue), mBufferLength(BufferLength), mStringLength(StringLength) {} protected: SQLRETURN UncaughtOdbcEntry() { return mDbc->SQLGetInfo(mInfoType, mInfoValue, mBufferLength, mStringLength); } private: SQLUSMALLINT mInfoType; SQLPOINTER mInfoValue; SQLSMALLINT mBufferLength; SQLSMALLINT* mStringLength; }; class SQLGetConnectAttr : public DbcOdbcEntry { public: SQLGetConnectAttr(SQLHDBC ConnectionHandle, SQLINTEGER Attribute, SQLPOINTER Value, SQLINTEGER BufferLength, SQLINTEGER *StringLength) : DbcOdbcEntry(ConnectionHandle), mAttribute(Attribute), mValue(Value), mBufferLength(BufferLength), mStringLength(StringLength) { } protected: SQLRETURN UncaughtOdbcEntry() { return mDbc->SQLGetConnectAttr(mAttribute, mValue, mBufferLength, mStringLength); } private: SQLINTEGER mAttribute; SQLPOINTER mValue; SQLINTEGER mBufferLength; SQLINTEGER* mStringLength; }; } namespace o = odbcrets; SQLRETURN SQL_API SQLAllocStmt(SQLHDBC ConnectionHandle, SQLHSTMT *StatementHandlePtr) { o::SQLAllocStmt sqlAllocStmt(ConnectionHandle, StatementHandlePtr); return sqlAllocStmt(); } SQLRETURN SQL_API SQLConnect(SQLHDBC ConnectionHandle, SQLCHAR *DataSource, SQLSMALLINT DataSourceLength, SQLCHAR *UserName, SQLSMALLINT UserLength, SQLCHAR *Authentication, SQLSMALLINT AuthLength) { o::SQLConnect sqlConnect(ConnectionHandle, DataSource, DataSourceLength, UserName, UserLength, Authentication, AuthLength); return sqlConnect(); } SQLRETURN SQL_API SQLDisconnect(SQLHDBC ConnectionHandle) { o::SQLDisconnect sqlDisconnect(ConnectionHandle); return sqlDisconnect(); } SQLRETURN SQL_API SQLDriverConnect( SQLHDBC ConnectionHandle, SQLHWND WindowHandle, SQLCHAR* InConnectionString, SQLSMALLINT InStringLength, SQLCHAR* OutConnectionString, SQLSMALLINT BufferLength, SQLSMALLINT* OutStringLengthPtr, SQLUSMALLINT DriverCompletion) { o::SQLDriverConnect sqlDriverConnect(ConnectionHandle, WindowHandle, InConnectionString, InStringLength, OutConnectionString, BufferLength, OutStringLengthPtr, DriverCompletion); return sqlDriverConnect(); } SQLRETURN SQL_API SQLGetInfo(SQLHDBC ConnectionHandle, SQLUSMALLINT InfoType, SQLPOINTER InfoValue, SQLSMALLINT BufferLength, SQLSMALLINT *StringLength) { o::SQLGetInfo sqlGetInfo(ConnectionHandle, InfoType, InfoValue, BufferLength, StringLength); return sqlGetInfo(); } SQLRETURN SQL_API SQLGetConnectAttr(SQLHDBC ConnectionHandle, SQLINTEGER Attribute, SQLPOINTER Value, SQLINTEGER BufferLength, SQLINTEGER *StringLength) { o::SQLGetConnectAttr sqlGetConnectAttr( ConnectionHandle, Attribute, Value, BufferLength, StringLength); return sqlGetConnectAttr(); }
33.413636
79
0.667936
mkhon
50ab105623645fd6280008abe04b2f930db659bf
4,452
cpp
C++
src/processServer.cpp
tositeru/watagashi
d4fcfbb4a7f44fcbf68652e7d99a4b13c6e035d4
[ "MIT" ]
null
null
null
src/processServer.cpp
tositeru/watagashi
d4fcfbb4a7f44fcbf68652e7d99a4b13c6e035d4
[ "MIT" ]
null
null
null
src/processServer.cpp
tositeru/watagashi
d4fcfbb4a7f44fcbf68652e7d99a4b13c6e035d4
[ "MIT" ]
null
null
null
#include "processServer.h" #include <iostream> #include "utility.h" #include "builder.h" #include "data.h" using namespace std; namespace fs = boost::filesystem; namespace watagashi { //-------------------------------------------------------------------------------------- // // class Process_ // //-------------------------------------------------------------------------------------- Process::Process( Builder const& builder, data::Compiler const& compiler, boost::filesystem::path const& inputFilepath, boost::filesystem::path const& outputFilepath) : builder(builder) , compiler(compiler) , inputFilepath(inputFilepath) , outputFilepath(outputFilepath) {} Process::BuildResult Process::compile()const { //cout << "run " << this->inputFilepath << endl; auto& project = builder.project(); auto& taskBundle = data::getTaskBundle(compiler, project.type); auto& task = taskBundle.compileObj; createDirectory(this->outputFilepath.parent_path()); data::TaskProcess::RunData runData; runData.inputFilepath = this->inputFilepath; runData.outputFilepath = this->outputFilepath; runData.includeDirectories = project.includeDirectories; auto preprocessResult = data::runProcesses(task.preprocesses, runData); if (data::TaskProcess::Result::Success != preprocessResult) { return preprocessResult == data::TaskProcess::Result::Skip ? BuildResult::Skip : BuildResult::Failed; } // check match Filter data::FileFilter const* pFileFilter = nullptr; for (auto&& filter : project.fileFilters) { if (matchFilepath(filter.targetKeyward, inputFilepath, project.rootDirectory)) { pFileFilter = &filter; break; } } if (pFileFilter) { auto result = data::runProcesses(pFileFilter->preprocess, runData); if (data::TaskProcess::Result::Success != result) { return preprocessResult == data::TaskProcess::Result::Skip ? BuildResult::Skip : BuildResult::Failed; } } auto cmd = data::makeCompileCommand(taskBundle.compileObj, this->inputFilepath, this->outputFilepath, project, pFileFilter); cout << "running: " << cmd << endl; if (!runCommand(cmd)) { return BuildResult::Failed; } if (pFileFilter) { auto result = data::runProcesses(pFileFilter->postprocess, runData); if (data::TaskProcess::Result::Success != result) { return preprocessResult == data::TaskProcess::Result::Skip ? BuildResult::Skip : BuildResult::Failed; } } auto postprocessResult = data::runProcesses(task.postprocesses, runData); if (data::TaskProcess::Result::Success != postprocessResult) { return postprocessResult == data::TaskProcess::Result::Skip ? BuildResult::Skip : BuildResult::Failed; } return BuildResult::Success; } //-------------------------------------------------------------------------------------- // // class ProcessServer // //-------------------------------------------------------------------------------------- ProcessServer::ProcessServer() : mProcessSum(0u) , mEndProcessSum(0u) , mSuccessCount(0) , mSkipLinkCount(0) , mFailedCount(0) { } ProcessServer::~ProcessServer() { } void ProcessServer::addProcess(std::unique_ptr<Process> pProcess) { std::lock_guard<std::mutex> lock(this->mMutex); this->mpProcess_Queue.emplace(std::move(pProcess)); ++this->mProcessSum; } std::unique_ptr<Process> ProcessServer::serveProcess_() { std::lock_guard<std::mutex> lock(this->mMutex); if (!this->mpProcess_Queue.empty()) { auto process = std::move(this->mpProcess_Queue.front()); this->mpProcess_Queue.pop(); return std::move(process); } else { return nullptr; } } void ProcessServer::notifyEndOfProcess(Process::BuildResult result) { std::lock_guard<std::mutex> lock(this->mMutex); ++this->mEndProcessSum; switch (result) { case Process::BuildResult::Success: ++this->mSuccessCount; break; case Process::BuildResult::Skip: ++this->mSkipLinkCount; break; case Process::BuildResult::Failed: ++this->mFailedCount; break; } } bool ProcessServer::isFinish()const { return this->mProcessSum == this->mEndProcessSum; } }
28.722581
128
0.598607
tositeru
27051ecab1393a3d3729e511cb242f15650485dc
538
cpp
C++
complex.cpp
dkaramit/complex
b0c65feeb420472aa79b11372e8329fb7aea8b6a
[ "MIT" ]
null
null
null
complex.cpp
dkaramit/complex
b0c65feeb420472aa79b11372e8329fb7aea8b6a
[ "MIT" ]
null
null
null
complex.cpp
dkaramit/complex
b0c65feeb420472aa79b11372e8329fb7aea8b6a
[ "MIT" ]
null
null
null
// This is an example on how to use complex. #include <iostream> #include "complex.hpp" using namespace std; int main(){ cout<<"=======Begin=======\n"<<endl; complex z=0.; z=8+3.*Imag; double n=3.; cout<<n<<"^("<<z<<") = "<<pow(n,z)<<endl; cout<<"("<<z<<")^"<<n<<" = "<<pow(z,n)<<endl; cout<<"("<<z<<")^"<<"("<<z<<") = "<<pow(z,z)<<endl; cout<<"e^"<<"("<<z<<") = "<<exp(z)<<endl; cout<<"arg"<<"("<<z<<") = "<<arg(z)<<endl; cout<<"sqrt"<<"("<<z<<") = "<<pow(z,0.5)<<endl; cout<<endl<<"=======End=======\n"<<endl; return 0; }
16.30303
51
0.451673
dkaramit
270698d319bc4a493cc63dae0feb0d3f93722e94
1,585
cpp
C++
src/test_separator.cpp
caomuqing/separator
53fbf832ce784029c8bd7e1a835acbb20d311730
[ "BSD-3-Clause" ]
8
2020-09-09T16:38:53.000Z
2021-08-19T10:40:25.000Z
submodules/separator/src/test_separator.cpp
t-thanh/mader-docker
4d0baa706d85b0b808d06a670ad6c9aa2730e05b
[ "BSD-3-Clause" ]
null
null
null
submodules/separator/src/test_separator.cpp
t-thanh/mader-docker
4d0baa706d85b0b808d06a670ad6c9aa2730e05b
[ "BSD-3-Clause" ]
2
2020-12-21T03:41:33.000Z
2021-08-21T07:45:32.000Z
/* ---------------------------------------------------------------------------- * Copyright 2020, Jesus Tordesillas Torres, Aerospace Controls Laboratory * Massachusetts Institute of Technology * All Rights Reserved * Authors: Jesus Tordesillas, et al. * See LICENSE file for the license information * -------------------------------------------------------------------------- */ #include <iostream> #include <array> #include "separator.hpp" int main() { separator::Separator separator_solver; double num_points_set_A = 4; double num_points_set_B = 3; Eigen::Matrix<double, 3, -1> pointsA(3, 4); // Each column is a point of the set A Eigen::Matrix<double, 3, -1> pointsB(3, 5); // Each column is a point of the set B pointsA.col(0) = Eigen::Vector3d(-3.50, 21, 1.4); pointsA.col(1) = Eigen::Vector3d(-2.71, 2.13, 1.6); pointsA.col(2) = Eigen::Vector3d(0.53, 0.51, 1.4); pointsA.col(3) = Eigen::Vector3d(-3.50, 0.21, 0.3); pointsB.col(0) = Eigen::Vector3d(-2.3, 4.69, 6.2); pointsB.col(1) = Eigen::Vector3d(3.7, 2.13, 65.6); pointsB.col(2) = Eigen::Vector3d(6.5, 2.93, 2.8); pointsB.col(3) = Eigen::Vector3d(0.3, 4.8, 9.2); pointsB.col(4) = Eigen::Vector3d(1.5, 6.7, 2.9); std::cout << "pointsA= \n" << pointsA << std::endl; std::cout << "pointsB= \n" << pointsB << std::endl; Eigen::Vector3d n; double d; bool solved = separator_solver.solveModel(n, d, pointsA, pointsB); std::cout << "Solved= " << solved << std::endl; std::cout << "n= " << n.transpose() << std::endl; std::cout << "d= " << d << std::endl; return 0; };
34.456522
85
0.57224
caomuqing
270769a4a238f8f618b435fec9b54e7d03e3549a
3,911
cpp
C++
Wand/Source/Utils/Serializer.cpp
mariaviolaki/wand
a955e9f67c73c584d73874904ba98bebd6f15971
[ "MIT" ]
null
null
null
Wand/Source/Utils/Serializer.cpp
mariaviolaki/wand
a955e9f67c73c584d73874904ba98bebd6f15971
[ "MIT" ]
null
null
null
Wand/Source/Utils/Serializer.cpp
mariaviolaki/wand
a955e9f67c73c584d73874904ba98bebd6f15971
[ "MIT" ]
null
null
null
#include "WandPCH.h" #include "Serializer.h" namespace wand { /******************************* PUBLIC METHODS **********************************/ void Serializer::Serialize(const State& state, const std::string& path) { nlohmann::json states; nlohmann::json oldStates = GetSavedStates(path); // Add the new state to the old ones (if they exist) if (oldStates.is_null()) states[state.GetName()] = CreatePairs(state); else states = CreateStateList(oldStates, state); // Write the data to a file in the given path (using 4 spaces for indentation) std::ofstream file(path); file << std::setw(4) << states << std::endl; } std::unordered_map<std::string, std::shared_ptr<State>> Serializer::Deserialize(const std::string& path) { std::unordered_map<std::string, std::shared_ptr<State>> states; nlohmann::json savedStates = GetSavedStates(path); // Create a new state using the JSON data for each state for (auto& state : savedStates.items()) { states[state.key()] = GetState(state.key(), state.value()); } return states; } /****************************** PRIVATE METHODS *********************************/ nlohmann::json Serializer::CreateStateList(const nlohmann::json& oldStates, const State& newState) { nlohmann::json newStates; // Access each state in the old list for (auto& state : oldStates.items()) { // Copy its data to the new list newStates[state.key()] = state.value(); } // Add the new state to the list, replacing the old one with the same name (if it exists) newStates[newState.GetName()] = CreatePairs(newState); return newStates; } // Create a pair in JSON format for each name-value pair in the state nlohmann::json Serializer::CreatePairs(const wand::State& state) { nlohmann::json statePairs; for (const auto& pair : state.GetStateData()) { statePairs[pair->GetName()] = CreateValue(*pair.get()); } return statePairs; } // Store the data type and the actual value of a pair in single JSON object nlohmann::json Serializer::CreateValue(const Pair& pair) { nlohmann::json pairValue; // Save the appropriate value depending on its data type in the pair switch (pair.GetValueType()) { case DataType::DT_INT: pairValue["type"] = "int"; pairValue["value"] = pair.GetIntValue(); break; case DataType::DT_DOUBLE: pairValue["type"] = "double"; pairValue["value"] = pair.GetDoubleValue(); break; case DataType::DT_BOOL: pairValue["type"] = "bool"; pairValue["value"] = pair.GetBoolValue(); break; case DataType::DT_STRING: pairValue["type"] = "string"; pairValue["value"] = pair.GetStringValue(); break; default: pairValue["type"] = ""; pairValue["value"] = ""; } return pairValue; } // Get the states from a file (in JSON format) nlohmann::json Serializer::GetSavedStates(const std::string& path) { nlohmann::json savedStates; // Copy the JSON data if the file exists std::ifstream file(path); if (file) file >> savedStates; return savedStates; } std::shared_ptr<State> Serializer::GetState(std::string name, const nlohmann::json& state) { std::shared_ptr<State> statePtr = std::make_shared<State>(name); // Add all the name-value pairs saved in the state for (auto& pair : state.items()) { statePtr->Add(GetPair(pair.key(), pair.value())); } return statePtr; } Pair* Serializer::GetPair(std::string name, const nlohmann::json& value) { // Get the correct value based on the saved data type if (value["type"].get<std::string>() == "int") return new Pair(name, value["value"].get<int>()); else if (value["type"].get<std::string>() == "double") return new Pair(name, value["value"].get<double>()); else if (value["type"].get<std::string>() == "bool") return new Pair(name, value["value"].get<bool>()); else return new Pair(name, value["value"].get<std::string>()); } }
29.406015
105
0.653541
mariaviolaki
2707bd1332867eb7d11cd158fe8c9cc9fc1206cf
40,671
cpp
C++
src/limits/Shadows/StaticShadows.cpp
EightyVice/III.VC.SA.LimitAdjuster
b83062ae1bc154701012f2f870a49c4566d06dfa
[ "MIT" ]
120
2016-03-13T14:06:07.000Z
2022-02-20T17:57:10.000Z
src/limits/Shadows/StaticShadows.cpp
EightyVice/III.VC.SA.LimitAdjuster
b83062ae1bc154701012f2f870a49c4566d06dfa
[ "MIT" ]
33
2016-09-25T13:01:08.000Z
2022-03-23T19:43:06.000Z
src/limits/Shadows/StaticShadows.cpp
EightyVice/III.VC.SA.LimitAdjuster
b83062ae1bc154701012f2f870a49c4566d06dfa
[ "MIT" ]
25
2016-08-09T15:52:06.000Z
2022-02-14T11:11:27.000Z
/* * Static Shadows Limit Adjuster * Copyright (C) 2014 Wesser * http://gtaforums.com/topic/675664-staticshadow-limit/ */ #include "LimitAdjuster.h" #include "cpatch/hook.h" using namespace Hook; DWORD SSHADS_LIMIT; //#define SSHADS_LIFETIME 5000 //#define SSHADS_UPDATEFIX void patch_706ED0(); void patch_706FE2(); void patch_7072C0(); void patch_707391(); void patch_70990A(); void patch_70BB3C(); void patch_70BB60(); void patch_70BB67(); void patch_70BC49(); DWORD ext_706ED0 = 0x706ED0; DWORD ext_706FEB = 0x706FEB; DWORD ext_706FF8 = 0x706FF8; DWORD ext_7072CC = 0x7072CC; DWORD ext_7072D2 = 0x7072D2; DWORD ext_70739C = 0x70739C; DWORD ext_70991E = 0x70991E; DWORD ext_70BA6F = 0x70BA6F; DWORD ext_70BB41 = 0x70BB41; DWORD ext_70BB43 = 0x70BB43; DWORD ext_70BB65 = 0x70BB65; DWORD ext_70BB71 = 0x70BB71; DWORD ext_70BC53 = 0x70BC53; std::vector<char> asShadowsStored; std::vector<char> aStaticShadows; std::vector<char> aPermanentShadows; void PatchShadowsStored() { AdjustPointer(0x400000+0x3073B0, &asShadowsStored[0], 0xC40430, 0xC40DF0); AdjustPointer(0x400000+0x30A9EE, &asShadowsStored[0], 0xC40430, 0xC40DF0); AdjustPointer(0x400000+0x30AA10, &asShadowsStored[0], 0xC40430, 0xC40DF0); AdjustPointer(0x400000+0x30AA18, &asShadowsStored[0], 0xC40430, 0xC40DF0); AdjustPointer(0x400000+0x30B0EF, &asShadowsStored[0], 0xC40430, 0xC40DF0); AdjustPointer(0x400000+0x30B166, &asShadowsStored[0], 0xC40430, 0xC40DF0); AdjustPointer(0x400000+0x30B17A, &asShadowsStored[0], 0xC40430, 0xC40DF0); AdjustPointer(0x400000+0x30B18D, &asShadowsStored[0], 0xC40430, 0xC40DF0); AdjustPointer(0x400000+0x30B23A, &asShadowsStored[0], 0xC40430, 0xC40DF0); AdjustPointer(0x400000+0x30B2B1, &asShadowsStored[0], 0xC40430, 0xC40DF0); AdjustPointer(0x400000+0x30B2C2, &asShadowsStored[0], 0xC40430, 0xC40DF0); AdjustPointer(0x400000+0x30B2D1, &asShadowsStored[0], 0xC40430, 0xC40DF0); AdjustPointer(0x400000+0x30B38E, &asShadowsStored[0], 0xC40430, 0xC40DF0); AdjustPointer(0x400000+0x30B404, &asShadowsStored[0], 0xC40430, 0xC40DF0); AdjustPointer(0x400000+0x30B40F, &asShadowsStored[0], 0xC40430, 0xC40DF0); AdjustPointer(0x400000+0x30B424, &asShadowsStored[0], 0xC40430, 0xC40DF0); AdjustPointer(0x400000+0x30B4EA, &asShadowsStored[0], 0xC40430, 0xC40DF0); AdjustPointer(0x400000+0x30B569, &asShadowsStored[0], 0xC40430, 0xC40DF0); AdjustPointer(0x400000+0x30B578, &asShadowsStored[0], 0xC40430, 0xC40DF0); AdjustPointer(0x400000+0x30B594, &asShadowsStored[0], 0xC40430, 0xC40DF0); RedirectJump(0x707391, patch_707391); Nop(0x7073AA, 1); // mov eax, esi SetUChar(0x7073AB, 0x8B); Nop(0x707439, 1); // inc esi Nop(0x707441, 1); // mov ds:[0C403DCh], esi Nop(0x70A9E0, 1); // mov ecx, ds:[0C403DCh] SetUChar(0x70A9E1, 0x8B); Nop(0x70AA3F, 2); // mov eax, ds:[0C403DCh] SetUChar(0x70AA41, 0xA1); Nop(0x70ADF9, 1); // mov ecx, ds:[0C403DCh] SetUChar(0x70ADFA, 0x8B); Nop(0x70B6C1, 1); // mov ecx, ds:[0C403DCh] SetUChar(0x70B6C2, 0x8B); Nop(0x70B71A, 1); // mov ds:[0C403DCh], ebx } void PatchStaticShadows() { AdjustPointer(0x400000+0x306E7A, &aStaticShadows[0], 0xC4A030, 0xC4AC30); AdjustPointer(0x400000+0x306E88, &aStaticShadows[0], 0xC4A030, 0xC4AC70, 64*48, aStaticShadows.size()); AdjustPointer(0x400000+0x307F41, &aStaticShadows[0], 0xC4A030, 0xC4AC30); AdjustPointer(0x400000+0x307F96, &aStaticShadows[0], 0xC4A030, 0xC4AC70, 64*48, aStaticShadows.size()); AdjustPointer(0x400000+0x308361, &aStaticShadows[0], 0xC4A030, 0xC4AC30); AdjustPointer(0x400000+0x308376, &aStaticShadows[0], 0xC4A030, 0xC4AC70, 64*48, aStaticShadows.size()); AdjustPointer(0x400000+0x30837D, &aStaticShadows[0], 0xC4A030, 0xC4AC30); AdjustPointer(0x400000+0x3083BC, &aStaticShadows[0], 0xC4A030, 0xC4AC70, 64*48, aStaticShadows.size()); AdjustPointer(0x400000+0x308614, &aStaticShadows[0], 0xC4A030, 0xC4AC70, 64*48, aStaticShadows.size()); AdjustPointer(0x400000+0x30866E, &aStaticShadows[0], 0xC4A030, 0xC4AC70, 64*48, aStaticShadows.size()); AdjustPointer(0x400000+0x30B73E, &aStaticShadows[0], 0xC4A030, 0xC4AC30); AdjustPointer(0x400000+0x30B746, &aStaticShadows[0], 0xC4A030, 0xC4AC30); AdjustPointer(0x400000+0x30B751, &aStaticShadows[0], 0xC4A030, 0xC4AC30); AdjustPointer(0x400000+0x30B76B, &aStaticShadows[0], 0xC4A030, 0xC4AC30); AdjustPointer(0x400000+0x30B77A, &aStaticShadows[0], 0xC4A030, 0xC4AC30); AdjustPointer(0x400000+0x30B931, &aStaticShadows[0], 0xC4A030, 0xC4AC30); AdjustPointer(0x400000+0x30B937, &aStaticShadows[0], 0xC4A030, 0xC4AC30); AdjustPointer(0x400000+0x30B966, &aStaticShadows[0], 0xC4A030, 0xC4AC30); AdjustPointer(0x400000+0x30B974, &aStaticShadows[0], 0xC4A030, 0xC4AC30); AdjustPointer(0x400000+0x30B97B, &aStaticShadows[0], 0xC4A030, 0xC4AC30); AdjustPointer(0x400000+0x30B98A, &aStaticShadows[0], 0xC4A030, 0xC4AC30); AdjustPointer(0x400000+0x30B991, &aStaticShadows[0], 0xC4A030, 0xC4AC30); AdjustPointer(0x400000+0x30B998, &aStaticShadows[0], 0xC4A030, 0xC4AC30); AdjustPointer(0x400000+0x30BB26, &aStaticShadows[0], 0xC4A030, 0xC4AC30); AdjustPointer(0x400000+0x30BB2E, &aStaticShadows[0], 0xC4A030, 0xC4AC30); AdjustPointer(0x400000+0x30BB56, &aStaticShadows[0], 0xC4A030, 0xC4AC30); AdjustPointer(0x400000+0x30BB84, &aStaticShadows[0], 0xC4A030, 0xC4AC30); AdjustPointer(0x400000+0x30BB8E, &aStaticShadows[0], 0xC4A030, 0xC4AC30); AdjustPointer(0x400000+0x30BB98, &aStaticShadows[0], 0xC4A030, 0xC4AC30); AdjustPointer(0x400000+0x30BBA3, &aStaticShadows[0], 0xC4A030, 0xC4AC30); AdjustPointer(0x400000+0x30BBAD, &aStaticShadows[0], 0xC4A030, 0xC4AC30); AdjustPointer(0x400000+0x30BBB7, &aStaticShadows[0], 0xC4A030, 0xC4AC30); AdjustPointer(0x400000+0x30BBBD, &aStaticShadows[0], 0xC4A030, 0xC4AC30); AdjustPointer(0x400000+0x30BBC3, &aStaticShadows[0], 0xC4A030, 0xC4AC30); AdjustPointer(0x400000+0x30BBC9, &aStaticShadows[0], 0xC4A030, 0xC4AC30); AdjustPointer(0x400000+0x30BBD2, &aStaticShadows[0], 0xC4A030, 0xC4AC30); AdjustPointer(0x400000+0x30BBF2, &aStaticShadows[0], 0xC4A030, 0xC4AC30); AdjustPointer(0x400000+0x30BBFC, &aStaticShadows[0], 0xC4A030, 0xC4AC30); AdjustPointer(0x400000+0x30BC06, &aStaticShadows[0], 0xC4A030, 0xC4AC30); AdjustPointer(0x400000+0x30BC13, &aStaticShadows[0], 0xC4A030, 0xC4AC30); AdjustPointer(0x400000+0x30BC19, &aStaticShadows[0], 0xC4A030, 0xC4AC30); AdjustPointer(0x400000+0x30BC20, &aStaticShadows[0], 0xC4A030, 0xC4AC30); AdjustPointer(0x400000+0x30BC26, &aStaticShadows[0], 0xC4A030, 0xC4AC30); AdjustPointer(0x400000+0x30BC31, &aStaticShadows[0], 0xC4A030, 0xC4AC30); AdjustPointer(0x400000+0x30BC5C, &aStaticShadows[0], 0xC4A030, 0xC4AC30); AdjustPointer(0x400000+0x30BC72, &aStaticShadows[0], 0xC4A030, 0xC4AC30); AdjustPointer(0x400000+0x30BC99, &aStaticShadows[0], 0xC4A030, 0xC4AC30); AdjustPointer(0x400000+0x30BCB1, &aStaticShadows[0], 0xC4A030, 0xC4AC30); AdjustPointer(0x400000+0x30BCCA, &aStaticShadows[0], 0xC4A030, 0xC4AC30); AdjustPointer(0x400000+0x30BCDB, &aStaticShadows[0], 0xC4A030, 0xC4AC30); AdjustPointer(0x400000+0x30BCEC, &aStaticShadows[0], 0xC4A030, 0xC4AC30); AdjustPointer(0x400000+0x30BCFD, &aStaticShadows[0], 0xC4A030, 0xC4AC30); AdjustPointer(0x400000+0x30BD0A, &aStaticShadows[0], 0xC4A030, 0xC4AC30); AdjustPointer(0x400000+0x30BD24, &aStaticShadows[0], 0xC4A030, 0xC4AC30); AdjustPointer(0x400000+0x30BD2E, &aStaticShadows[0], 0xC4A030, 0xC4AC30); AdjustPointer(0x400000+0x30BD39, &aStaticShadows[0], 0xC4A030, 0xC4AC30); AdjustPointer(0x400000+0x30BD43, &aStaticShadows[0], 0xC4A030, 0xC4AC30); AdjustPointer(0x400000+0x30BD4E, &aStaticShadows[0], 0xC4A030, 0xC4AC30); AdjustPointer(0x400000+0x30BD59, &aStaticShadows[0], 0xC4A030, 0xC4AC30); AdjustPointer(0x400000+0x30BD63, &aStaticShadows[0], 0xC4A030, 0xC4AC30); AdjustPointer(0x400000+0x30BD6F, &aStaticShadows[0], 0xC4A030, 0xC4AC30); AdjustPointer(0x400000+0x30BD7A, &aStaticShadows[0], 0xC4A030, 0xC4AC30); AdjustPointer(0x400000+0x30BD80, &aStaticShadows[0], 0xC4A030, 0xC4AC30); AdjustPointer(0x400000+0x30BD87, &aStaticShadows[0], 0xC4A030, 0xC4AC30); RedirectOffset(0x53CA26, patch_706ED0); SetPointer(0x706E95, nullptr); RedirectShortJump(0x706E99, 0x706EB5); RedirectJump(0x70990A, patch_70990A); Nop(0x70B736, 1); // mov esi, [esp+3Ch] SetUChar(0x70B737, 0x8B); Nop(0x70BB20, 1); // mov eax, edi SetUChar(0x70BB21, 0x8B); RedirectJump(0x70BB3C, patch_70BB3C); Nop(0x70BB50, 1); // mov ecx, edi SetUChar(0x70BB51, 0x8B); RedirectJump(0x70BB60, patch_70BB60); RedirectJump(0x70BB67, patch_70BB67); Nop(0x70BB7E, 1); // mov esi, edi SetUChar(0x70BB7F, 0x8B); RedirectJump(0x70BC49, patch_70BC49); Nop(0x70BC56, 1); // mov ecx, edi SetUChar(0x70BC57, 0x8B); #ifdef SSHADS_LIFETIME #if !SSHADS_LIFETIME RedirectShortJump(0x707F56, 0x707F90); #elif SSHADS_LIFETIME != 5000 SetUInt(0x707F60, SSHADS_LIFETIME); #endif #endif // Always update static shadows of specific moving thingys. #ifdef SSHADS_UPDATEFIX // Low detailed vehicle shadow (default distance: 0.1f). SetPointer(0x70C2B8, 0x858B50); SetFloat(0x70C2D5, 0.0f); // Vehicle headlight/s (default distance: 0.4f). SetPointer(0x70C681, 0x858B50); SetFloat(0x70C6A9, 0.0f); #endif } void PatchPermanentShadows() { AdjustPointer(0x400000+0x306EB5, &aPermanentShadows[0], 0xC4AC30, 0xC4B6B0); AdjustPointer(0x400000+0x306EC5, &aPermanentShadows[0], 0xC4AC30, 0xC4B6E8, 56*48, aPermanentShadows.size()); AdjustPointer(0x400000+0x306F64, &aPermanentShadows[0], 0xC4AC30, 0xC4B6B0); AdjustPointer(0x400000+0x306FBA, &aPermanentShadows[0], 0xC4AC30, 0xC4B720, 56*48, aPermanentShadows.size()); AdjustPointer(0x400000+0x306FF3, &aPermanentShadows[0], 0xC4AC30, 0xC4B6B0); AdjustPointer(0x400000+0x3072DF, &aPermanentShadows[0], 0xC4AC30, 0xC4B6B0); AdjustPointer(0x400000+0x3072E5, &aPermanentShadows[0], 0xC4AC30, 0xC4B6B0); AdjustPointer(0x400000+0x3072F1, &aPermanentShadows[0], 0xC4AC30, 0xC4B6B0); AdjustPointer(0x400000+0x30730D, &aPermanentShadows[0], 0xC4AC30, 0xC4B6B0); AdjustPointer(0x400000+0x307317, &aPermanentShadows[0], 0xC4AC30, 0xC4B6B0); AdjustPointer(0x400000+0x307321, &aPermanentShadows[0], 0xC4AC30, 0xC4B6B0); AdjustPointer(0x400000+0x30732C, &aPermanentShadows[0], 0xC4AC30, 0xC4B6B0); AdjustPointer(0x400000+0x307336, &aPermanentShadows[0], 0xC4AC30, 0xC4B6B0); AdjustPointer(0x400000+0x307341, &aPermanentShadows[0], 0xC4AC30, 0xC4B6B0); AdjustPointer(0x400000+0x30734B, &aPermanentShadows[0], 0xC4AC30, 0xC4B6B0); AdjustPointer(0x400000+0x307355, &aPermanentShadows[0], 0xC4AC30, 0xC4B6B0); AdjustPointer(0x400000+0x30735F, &aPermanentShadows[0], 0xC4AC30, 0xC4B6B0); AdjustPointer(0x400000+0x307369, &aPermanentShadows[0], 0xC4AC30, 0xC4B6B0); AdjustPointer(0x400000+0x307375, &aPermanentShadows[0], 0xC4AC30, 0xC4B6B0); AdjustPointer(0x400000+0x30737B, &aPermanentShadows[0], 0xC4AC30, 0xC4B6B0); AdjustPointer(0x400000+0x3074F0, &aPermanentShadows[0], 0xC4AC30, 0xC4B6B0); AdjustPointer(0x400000+0x30753E, &aPermanentShadows[0], 0xC4AC30, 0xC4B6E8, 56*48, aPermanentShadows.size()); AdjustPointer(0x400000+0x3075AF, &aPermanentShadows[0], 0xC4AC30, 0xC4B6B0); AdjustPointer(0x400000+0x307613, &aPermanentShadows[0], 0xC4AC30, 0xC4B6E8, 56*48, aPermanentShadows.size()); AdjustPointer(0x400000+0x307631, &aPermanentShadows[0], 0xC4AC30, 0xC4B6B0); AdjustPointer(0x400000+0x30763D, &aPermanentShadows[0], 0xC4AC30, 0xC4B6B0); AdjustPointer(0x400000+0x307770, &aPermanentShadows[0], 0xC4AC30, 0xC4B6B0); AdjustPointer(0x400000+0x30777B, &aPermanentShadows[0], 0xC4AC30, 0xC4B6E8, 56*48, aPermanentShadows.size()); AdjustPointer(0x400000+0x30C957, &aPermanentShadows[0], 0xC4AC30, 0xC4B6B0); AdjustPointer(0x400000+0x30CA84, &aPermanentShadows[0], 0xC4AC30, 0xC4B6E8, 56*48, aPermanentShadows.size()); AdjustPointer(0x400000+0x30CAB0, &aPermanentShadows[0], 0xC4AC30, 0xC4B6B0); AdjustPointer(0x400000+0x30CAC5, &aPermanentShadows[0], 0xC4AC30, 0xC4B6B0); AdjustPointer(0x400000+0x30CACC, &aPermanentShadows[0], 0xC4AC30, 0xC4B6B0); AdjustPointer(0x400000+0x30CAD2, &aPermanentShadows[0], 0xC4AC30, 0xC4B6B0); AdjustPointer(0x400000+0x30CAE2, &aPermanentShadows[0], 0xC4AC30, 0xC4B6B0); AdjustPointer(0x400000+0x30CAF1, &aPermanentShadows[0], 0xC4AC30, 0xC4B6B0); AdjustPointer(0x400000+0x30CAFA, &aPermanentShadows[0], 0xC4AC30, 0xC4B6B0); AdjustPointer(0x400000+0x30CB03, &aPermanentShadows[0], 0xC4AC30, 0xC4B6B0); AdjustPointer(0x400000+0x30CB3D, &aPermanentShadows[0], 0xC4AC30, 0xC4B6E8, 56*48, aPermanentShadows.size()); AdjustPointer(0x400000+0x30CB5E, &aPermanentShadows[0], 0xC4AC30, 0xC4B6B0); AdjustPointer(0x400000+0x30CB80, &aPermanentShadows[0], 0xC4AC30, 0xC4B6B0); AdjustPointer(0x400000+0x30CB8C, &aPermanentShadows[0], 0xC4AC30, 0xC4B6B0); AdjustPointer(0x400000+0x30CB94, &aPermanentShadows[0], 0xC4AC30, 0xC4B6B0); AdjustPointer(0x400000+0x30CB9A, &aPermanentShadows[0], 0xC4AC30, 0xC4B6B0); AdjustPointer(0x400000+0x30CBA3, &aPermanentShadows[0], 0xC4AC30, 0xC4B6B0); AdjustPointer(0x400000+0x30CBBB, &aPermanentShadows[0], 0xC4AC30, 0xC4B6B0); AdjustPointer(0x400000+0x30CBC4, &aPermanentShadows[0], 0xC4AC30, 0xC4B6B0); AdjustPointer(0x400000+0x30CBCD, &aPermanentShadows[0], 0xC4AC30, 0xC4B6B0); AdjustPointer(0x400000+0x30CBFE, &aPermanentShadows[0], 0xC4AC30, 0xC4B6B0); AdjustPointer(0x400000+0x30CC09, &aPermanentShadows[0], 0xC4AC30, 0xC4B6B0); AdjustPointer(0x400000+0x30CC2C, &aPermanentShadows[0], 0xC4AC30, 0xC4B6E8, 56*48, aPermanentShadows.size()); AdjustPointer(0x400000+0x30CC50, &aPermanentShadows[0], 0xC4AC30, 0xC4B6B0); AdjustPointer(0x400000+0x30CC5D, &aPermanentShadows[0], 0xC4AC30, 0xC4B6B0); AdjustPointer(0x400000+0x30CC90, &aPermanentShadows[0], 0xC4AC30, 0xC4B6B0); AdjustPointer(0x400000+0x30CCA0, &aPermanentShadows[0], 0xC4AC30, 0xC4B6E8, 56*48, aPermanentShadows.size()); RedirectJump(0x706FE2, patch_706FE2); RedirectJump(0x7072C0, patch_7072C0); SetUInt(0x70CC86, aPermanentShadows.size()); } void __declspec(naked) patch_706ED0() { __asm { push esi push edi mov edi, ds:[0C403D8h] test edi, edi jz loc_706ED0 align 16 walk_free_list: mov esi, [edi+54h] push edi call dword ptr free add esp, 4 mov edi, esi test edi, edi jnz walk_free_list loc_706ED0: pop edi pop esi jmp ext_706ED0 } } void __declspec(naked) patch_706FE2() { __asm { cmp edi, SSHADS_LIMIT jl loc_7072D2 jmp ext_706FEB loc_7072D2: jmp ext_7072D2 } } void __declspec(naked) patch_7072C0() { __asm { cmp eax, SSHADS_LIMIT jl loc_706FF8 cmp edi, SSHADS_LIMIT jmp ext_7072CC loc_706FF8: jmp ext_706FF8 } } void __declspec(naked) patch_707391() { __asm { mov esi, ds:[0C403DCh] cmp esi, SSHADS_LIMIT jmp ext_70739C } } void __declspec(naked) patch_70990A() { __asm { jnz free_list push 104 // sizeof(CPolyBunch) call dword ptr malloc add esp, 4 mov ebx, eax jmp loc_70991E free_list: mov ecx, [ebx+54h] mov ds:[0C403D8h], ecx loc_70991E: lea eax, [ebx+54h] test ebp, ebp jmp ext_70991E } } void __declspec(naked) patch_70BB3C() { __asm { inc edi cmp edi, SSHADS_LIMIT jmp ext_70BB41 } } void __declspec(naked) patch_70BB60() { __asm { inc edi cmp edi, SSHADS_LIMIT jmp ext_70BB65 } } void __declspec(naked) patch_70BB67() { __asm { cmp edi, SSHADS_LIMIT je loc_70BA6F jmp ext_70BB71 loc_70BA6F: jmp ext_70BA6F } } void __declspec(naked) patch_70BC49() { __asm { cmp edi, SSHADS_LIMIT jge loc_70BB43 jmp ext_70BC53 loc_70BB43: jmp ext_70BB43 } } class StaticShadowsSA : public SimpleAdjuster { public: const char* GetLimitName() { return GetGVM().IsSA()? "StaticShadows" : nullptr; } void ChangeLimit(int, const std::string& value) { SSHADS_LIMIT = std::stoi(value); asShadowsStored.resize(SSHADS_LIMIT * 52); aStaticShadows.resize(SSHADS_LIMIT * 64); aPermanentShadows.resize(SSHADS_LIMIT * 56); PatchStaticShadows(); PatchShadowsStored(); PatchPermanentShadows(); } } StaticShadowsSA; ///////////////////////THIS THING BELOW MAY NOT WORK!!!/////////////////////////////////////////// /////////////////////////////////////////////GTA 3|VC///////////////////////////////////////////// DWORD _EAX; WORD _EBX; /////////////////////////////////////////////GTA Vice City///////////////////////////////////////////// void patch_56E6C0(); void patch_56967E(); void patch_56E924(); void patch_56E93B(); void patch_56EB34(); void patch_56EB43(); void patch_56F09B(); void patch_56F24A(); void patch_56C71B(); void patch_56C7BC(); void patch_56CBA8(); void patch_56CC10(); void patch_568F17(); void PatchStaticShadowsVC() { aStaticShadows.resize(SSHADS_LIMIT * 64); AdjustPointer(0x56966E, &aStaticShadows[0], 0x8615A0, 0x8621A0); AdjustPointer(0x56C56B, &aStaticShadows[0], 0x8615A0, 0x8621A0); AdjustPointer(0x56E92C, &aStaticShadows[0], 0x8615A0, 0x8621A0); AdjustPointer(0x56EB1D, &aStaticShadows[0], 0x8615A0, 0x8621A0); AdjustPointer(0x56EB71, &aStaticShadows[0], 0x8615A0, 0x8621A0); AdjustPointer(0x56EFFD, &aStaticShadows[0], 0x8615A0, 0x8621A0); AdjustPointer(0x56F2AF, &aStaticShadows[0], 0x8615A0, 0x8621A0); AdjustPointer(0x569618, &aStaticShadows[0], 0x8615A0, 0x8621A0); AdjustPointer(0x569664, &aStaticShadows[0], 0x8615A0, 0x8621A0); AdjustPointer(0x56C73C, &aStaticShadows[0], 0x8615A0, 0x8621A0); AdjustPointer(0x56C7E6, &aStaticShadows[0], 0x8615A0, 0x8621A0); AdjustPointer(0x56E934, &aStaticShadows[0], 0x8615A0, 0x8621A0); AdjustPointer(0x56EAEA, &aStaticShadows[0], 0x8615A0, 0x8621A0); AdjustPointer(0x56EB13, &aStaticShadows[0], 0x8615A0, 0x8621A0); AdjustPointer(0x56EB3C, &aStaticShadows[0], 0x8615A0, 0x8621A0); AdjustPointer(0x56EC24, &aStaticShadows[0], 0x8615A0, 0x8621A0); AdjustPointer(0x56F007, &aStaticShadows[0], 0x8615A0, 0x8621A0); AdjustPointer(0x569634, &aStaticShadows[0], 0x8615A0, 0x8621A0); AdjustPointer(0x56EADD, &aStaticShadows[0], 0x8615A0, 0x8621A0); AdjustPointer(0x56EC19, &aStaticShadows[0], 0x8615A0, 0x8621A0); AdjustPointer(0x56C3D3, &aStaticShadows[0], 0x8615A0, 0x8621A0); AdjustPointer(0x56E94F, &aStaticShadows[0], 0x8615A0, 0x8621A0); AdjustPointer(0x56E998, &aStaticShadows[0], 0x8615A0, 0x8621A0); AdjustPointer(0x56EBBD, &aStaticShadows[0], 0x8615A0, 0x8621A0); AdjustPointer(0x56C3E1, &aStaticShadows[0], 0x8615A0, 0x8621A0); AdjustPointer(0x56E972, &aStaticShadows[0], 0x8615A0, 0x8621A0); AdjustPointer(0x56E9C3, &aStaticShadows[0], 0x8615A0, 0x8621A0); AdjustPointer(0x56EBC6, &aStaticShadows[0], 0x8615A0, 0x8621A0); AdjustPointer(0x56C3EF, &aStaticShadows[0], 0x8615A0, 0x8621A0); AdjustPointer(0x56E9EE, &aStaticShadows[0], 0x8615A0, 0x8621A0); AdjustPointer(0x56EBCF, &aStaticShadows[0], 0x8615A0, 0x8621A0); AdjustPointer(0x56C387, &aStaticShadows[0], 0x8615A0, 0x8621A0); AdjustPointer(0x56C5E1, &aStaticShadows[0], 0x8615A0, 0x8621A0); AdjustPointer(0x56C632, &aStaticShadows[0], 0x8615A0, 0x8621A0); AdjustPointer(0x56EA1A, &aStaticShadows[0], 0x8615A0, 0x8621A0); AdjustPointer(0x56EBD9, &aStaticShadows[0], 0x8615A0, 0x8621A0); AdjustPointer(0x56C3B9, &aStaticShadows[0], 0x8615A0, 0x8621A0); AdjustPointer(0x56C5DB, &aStaticShadows[0], 0x8615A0, 0x8621A0); AdjustPointer(0x56C62C, &aStaticShadows[0], 0x8615A0, 0x8621A0); AdjustPointer(0x56EA32, &aStaticShadows[0], 0x8615A0, 0x8621A0); AdjustPointer(0x56EBE3, &aStaticShadows[0], 0x8615A0, 0x8621A0); AdjustPointer(0x56C371, &aStaticShadows[0], 0x8615A0, 0x8621A0); AdjustPointer(0x56C5D5, &aStaticShadows[0], 0x8615A0, 0x8621A0); AdjustPointer(0x56C626, &aStaticShadows[0], 0x8615A0, 0x8621A0); AdjustPointer(0x56EA4A, &aStaticShadows[0], 0x8615A0, 0x8621A0); AdjustPointer(0x56EBED, &aStaticShadows[0], 0x8615A0, 0x8621A0); AdjustPointer(0x56C3A3, &aStaticShadows[0], 0x8615A0, 0x8621A0); AdjustPointer(0x56C5C9, &aStaticShadows[0], 0x8615A0, 0x8621A0); AdjustPointer(0x56C620, &aStaticShadows[0], 0x8615A0, 0x8621A0); AdjustPointer(0x56EA62, &aStaticShadows[0], 0x8615A0, 0x8621A0); AdjustPointer(0x56EBFB, &aStaticShadows[0], 0x8615A0, 0x8621A0); AdjustPointer(0x56C5BB, &aStaticShadows[0], 0x8615A0, 0x8621A0); AdjustPointer(0x56C612, &aStaticShadows[0], 0x8615A0, 0x8621A0); AdjustPointer(0x56EAB7, &aStaticShadows[0], 0x8615A0, 0x8621A0); AdjustPointer(0x56EBAD, &aStaticShadows[0], 0x8615A0, 0x8621A0); AdjustPointer(0x56C5B5, &aStaticShadows[0], 0x8615A0, 0x8621A0); AdjustPointer(0x56C60C, &aStaticShadows[0], 0x8615A0, 0x8621A0); AdjustPointer(0x56EAC6, &aStaticShadows[0], 0x8615A0, 0x8621A0); AdjustPointer(0x56EBB5, &aStaticShadows[0], 0x8615A0, 0x8621A0); AdjustPointer(0x56C7AA, &aStaticShadows[0], 0x8615A0, 0x8621A0); AdjustPointer(0x56C814, &aStaticShadows[0], 0x8615A0, 0x8621A0); AdjustPointer(0x56C81E, &aStaticShadows[0], 0x8615A0, 0x8621A0); AdjustPointer(0x56EA87, &aStaticShadows[0], 0x8615A0, 0x8621A0); AdjustPointer(0x56EB81, &aStaticShadows[0], 0x8615A0, 0x8621A0); AdjustPointer(0x56C931, &aStaticShadows[0], 0x8615A0, 0x8621A0); AdjustPointer(0x56EA93, &aStaticShadows[0], 0x8615A0, 0x8621A0); AdjustPointer(0x56EB8D, &aStaticShadows[0], 0x8615A0, 0x8621A0); AdjustPointer(0x56C757, &aStaticShadows[0], 0x8615A0, 0x8621A0); AdjustPointer(0x56C7F8, &aStaticShadows[0], 0x8615A0, 0x8621A0); AdjustPointer(0x56C802, &aStaticShadows[0], 0x8615A0, 0x8621A0); AdjustPointer(0x56EA7D, &aStaticShadows[0], 0x8615A0, 0x8621A0); AdjustPointer(0x56EB77, &aStaticShadows[0], 0x8615A0, 0x8621A0); AdjustPointer(0x56C9C2, &aStaticShadows[0], 0x8615A0, 0x8621A0); AdjustPointer(0x56EAA1, &aStaticShadows[0], 0x8615A0, 0x8621A0); AdjustPointer(0x56EB97, &aStaticShadows[0], 0x8615A0, 0x8621A0); AdjustPointer(0x56C9B7, &aStaticShadows[0], 0x8615A0, 0x8621A0); AdjustPointer(0x56EAAB, &aStaticShadows[0], 0x8615A0, 0x8621A0); AdjustPointer(0x56EBA1, &aStaticShadows[0], 0x8615A0, 0x8621A0); AdjustPointer(0x56C9D0, &aStaticShadows[0], 0x8615A0, 0x8621A0); AdjustPointer(0x56EAB1, &aStaticShadows[0], 0x8615A0, 0x8621A0); AdjustPointer(0x56EBA7, &aStaticShadows[0], 0x8615A0, 0x8621A0); AdjustPointer(0x569622, &aStaticShadows[0], 0x8615A0, 0x8621A0); AdjustPointer(0x569679, &aStaticShadows[0], 0x8615A0, 0x8621A0); AdjustPointer(0x56EA76, &aStaticShadows[0], 0x8615A0, 0x8621A0); AdjustPointer(0x56EC05, &aStaticShadows[0], 0x8615A0, 0x8621A0); AdjustPointer(0x56C6E5, &aStaticShadows[0], 0x8615A0, 0x8621A0); AdjustPointer(0x56C749, &aStaticShadows[0], 0x8615A0, 0x8621A0); AdjustPointer(0x56CB9A, &aStaticShadows[0], 0x8615A0, 0x8621A0); AdjustPointer(0x56962B, &aStaticShadows[0], 0x8615A0, 0x8621A0); AdjustPointer(0x56EAD0, &aStaticShadows[0], 0x8615A0, 0x8621A0); AdjustPointer(0x56EC0C, &aStaticShadows[0], 0x8615A0, 0x8621A0); AdjustPointer(0x56F011, &aStaticShadows[0], 0x8615A0, 0x8621A0); AdjustPointer(0x56F01B, &aStaticShadows[0], 0x8615A0, 0x8621A0); AdjustPointer(0x56C6EC, &aStaticShadows[0], 0x8615A0, 0x8621A0); AdjustPointer(0x56F025, &aStaticShadows[0], 0x8615A0, 0x8621A0); AdjustPointer(0x56F02F, &aStaticShadows[0], 0x8615A0, 0x8621A0); AdjustPointer(0x56C6F3, &aStaticShadows[0], 0x8615A0, 0x8621A0); AdjustPointer(0x56F039, &aStaticShadows[0], 0x8615A0, 0x8621A0); AdjustPointer(0x56F043, &aStaticShadows[0], 0x8615A0, 0x8621A0); AdjustPointer(0x56C6FA, &aStaticShadows[0], 0x8615A0, 0x8621A0); AdjustPointer(0x56F04D, &aStaticShadows[0], 0x8615A0, 0x8621A0); AdjustPointer(0x56F057, &aStaticShadows[0], 0x8615A0, 0x8621A0); AdjustPointer(0x56C701, &aStaticShadows[0], 0x8615A0, 0x8621A0); AdjustPointer(0x56F061, &aStaticShadows[0], 0x8615A0, 0x8621A0); AdjustPointer(0x56F06B, &aStaticShadows[0], 0x8615A0, 0x8621A0); AdjustPointer(0x56C708, &aStaticShadows[0], 0x8615A0, 0x8621A0); AdjustPointer(0x56F075, &aStaticShadows[0], 0x8615A0, 0x8621A0); AdjustPointer(0x56F07F, &aStaticShadows[0], 0x8615A0, 0x8621A0); AdjustPointer(0x56C70F, &aStaticShadows[0], 0x8615A0, 0x8621A0); AdjustPointer(0x56F089, &aStaticShadows[0], 0x8615A0, 0x8621A0); AdjustPointer(0x56F093, &aStaticShadows[0], 0x8615A0, 0x8621A0); AdjustPointer(0x56C716, &aStaticShadows[0], 0x8615A0, 0x8621A0); RedirectJump(0x56E6C0, patch_56E6C0); RedirectJump(0x56967E, patch_56967E); RedirectJump(0x56E924, patch_56E924); RedirectJump(0x56E93B, patch_56E93B); RedirectJump(0x56EB34, patch_56EB34); RedirectJump(0x56EB43, patch_56EB43); RedirectJump(0x56F09B, patch_56F09B); RedirectJump(0x56F24A, patch_56F24A); RedirectJump(0x56C71B, patch_56C71B); RedirectJump(0x56C7BC, patch_56C7BC); RedirectJump(0x56CBA8, patch_56CBA8); RedirectJump(0x56CC10, patch_56CC10); } DWORD ext_56E6C8 = 0x56E6C8; void __declspec(naked) patch_56E6C0() { __asm { mov _EBX, bx mov eax, SSHADS_LIMIT cmp word ptr ds : [0xA10AAC], bx mov bx, _EBX jmp ext_56E6C8 } } DWORD ext_569684 = 0x569684; void __declspec(naked) patch_56967E() { __asm { add ebx, 40h cmp ecx, SSHADS_LIMIT jmp ext_569684 } } DWORD ext_56E92A = 0x56E92A; DWORD ext_56E93B = 0x56E93B; void __declspec(naked) patch_56E924() { __asm { cmp esi, SSHADS_LIMIT jge loc_56E93B jmp ext_56E92A loc_56E93B: jmp ext_56E93B } } DWORD ext_56E948 = 0x56E948; DWORD ext_56EB27 = 0x56EB27; void __declspec(naked) patch_56E93B() { __asm { cmp esi, SSHADS_LIMIT jge loc_56EB27 mov ebp, esi jmp ext_56E948 loc_56EB27: jmp ext_56EB27 } } DWORD ext_56EB3A = 0x56EB3A; DWORD ext_56EB43 = 0x56EB43; void __declspec(naked) patch_56EB34() { __asm { cmp esi, SSHADS_LIMIT jge loc_56EB43 jmp ext_56EB3A loc_56EB43: jmp ext_56EB43 } } DWORD ext_56EB49 = 0x56EB49; DWORD ext_56EB60 = 0x56EB60; void __declspec(naked) patch_56EB43() { __asm { cmp esi, SSHADS_LIMIT jnz loc_56EB60 jmp ext_56EB49 loc_56EB60: jmp ext_56EB60 } } DWORD ext_56F0A4 = 0x56F0A4; void __declspec(naked) patch_56F09B() { __asm { add edx, 200h cmp eax, SSHADS_LIMIT jmp ext_56F0A4 } } DWORD ext_56F24F = 0x56F24F; void __declspec(naked) patch_56F24A() { __asm { sub edx, ebx cmp eax, SSHADS_LIMIT jmp ext_56F24F } } DWORD ext_56C724 = 0x56C724; void __declspec(naked) patch_56C71B() { __asm { add ebp, 200h cmp eax, SSHADS_LIMIT jmp ext_56C724 } } DWORD ext_56C7C1 = 0x56C7C1; void __declspec(naked) patch_56C7BC() { __asm { pop ecx cmp eax, SSHADS_LIMIT pop ecx jmp ext_56C7C1 } } DWORD ext_56CBAD = 0x56CBAD; void __declspec(naked) patch_56CBA8() { __asm { mov _EAX, eax mov eax, SSHADS_LIMIT cmp dword ptr ds:[esp + 20h], eax mov eax, _EAX jmp ext_56CBAD } } DWORD ext_56CC15 = 0x56CC15; void __declspec(naked) patch_56CC10() { __asm { mov _EAX, eax mov eax, SSHADS_LIMIT cmp dword ptr ds : [esp + 28h], eax mov eax, _EAX jmp ext_56CC15 } } DWORD ext_568F1C = 0x568F1C; void __declspec(naked) patch_568F17() { __asm { sub edx, ebx cmp eax, SSHADS_LIMIT jmp ext_568F1C } } class StaticShadowsVC : public SimpleAdjuster { public: const char* GetLimitName() { return GetGVM().IsVC() ? "StaticShadows" : nullptr; } void ChangeLimit(int, const std::string& value) { SSHADS_LIMIT = std::stoi(value); PatchStaticShadowsVC(); } } StaticShadowsVC; /////////////////////////////////////////////GTA 3///////////////////////////////////////////////////// void patch_56E6C0(); void patch_513214(); void patch_51322B(); void patch_51344C(); void patch_51345B(); void patch_512D58(); void patch_516C30(); void patch_51466B(); void patch_5146C9(); void patch_5148C8(); void patch_5148E1(); void PatchStaticShadowsIII() { aStaticShadows.resize(SSHADS_LIMIT * 64); AdjustPointer(0x512CBA, &aStaticShadows[0], 0x773BE8, 0x77430E); AdjustPointer(0x51321C, &aStaticShadows[0], 0x773BE8, 0x77430E); AdjustPointer(0x513435, &aStaticShadows[0], 0x773BE8, 0x77430E); AdjustPointer(0x513482, &aStaticShadows[0], 0x773BE8, 0x77430E); AdjustPointer(0x514B5B, &aStaticShadows[0], 0x773BE8, 0x77430E); AdjustPointer(0x516BE8, &aStaticShadows[0], 0x773BE8, 0x77430E); AdjustPointer(0x5178CF, &aStaticShadows[0], 0x773BE8, 0x77430E); AdjustPointer(0x512CC4, &aStaticShadows[0], 0x773BE8, 0x77430E); AdjustPointer(0x513224, &aStaticShadows[0], 0x773BE8, 0x77430E); AdjustPointer(0x513454, &aStaticShadows[0], 0x773BE8, 0x77430E); AdjustPointer(0x51468C, &aStaticShadows[0], 0x773BE8, 0x77430E); AdjustPointer(0x5146F6, &aStaticShadows[0], 0x773BE8, 0x77430E); AdjustPointer(0x516BF2, &aStaticShadows[0], 0x773BE8, 0x77430E); AdjustPointer(0x513424, &aStaticShadows[0], 0x773BE8, 0x77430E); AdjustPointer(0x513526, &aStaticShadows[0], 0x773BE8, 0x77430E); AdjustPointer(0x516C0D, &aStaticShadows[0], 0x773BE8, 0x77430E); AdjustPointer(0x51323F, &aStaticShadows[0], 0x773BE8, 0x77430E); AdjustPointer(0x5134D0, &aStaticShadows[0], 0x773BE8, 0x77430E); AdjustPointer(0x5149D4, &aStaticShadows[0], 0x773BE8, 0x77430E); AdjustPointer(0x513277, &aStaticShadows[0], 0x773BE8, 0x77430E); AdjustPointer(0x5132E2, &aStaticShadows[0], 0x773BE8, 0x77430E); AdjustPointer(0x5134D9, &aStaticShadows[0], 0x773BE8, 0x77430E); AdjustPointer(0x5149E2, &aStaticShadows[0], 0x773BE8, 0x77430E); AdjustPointer(0x51331F, &aStaticShadows[0], 0x773BE8, 0x77430E); AdjustPointer(0x5134E2, &aStaticShadows[0], 0x773BE8, 0x77430E); AdjustPointer(0x5149F0, &aStaticShadows[0], 0x773BE8, 0x77430E); AdjustPointer(0x513360, &aStaticShadows[0], 0x773BE8, 0x77430E); AdjustPointer(0x5134EC, &aStaticShadows[0], 0x773BE8, 0x77430E); AdjustPointer(0x51495A, &aStaticShadows[0], 0x773BE8, 0x77430E); AdjustPointer(0x514BE1, &aStaticShadows[0], 0x773BE8, 0x77430E); AdjustPointer(0x514C32, &aStaticShadows[0], 0x773BE8, 0x77430E); AdjustPointer(0x513378, &aStaticShadows[0], 0x773BE8, 0x77430E); AdjustPointer(0x5134F6, &aStaticShadows[0], 0x773BE8, 0x77430E); AdjustPointer(0x5149B0, &aStaticShadows[0], 0x773BE8, 0x77430E); AdjustPointer(0x514BDB, &aStaticShadows[0], 0x773BE8, 0x77430E); AdjustPointer(0x514C2C, &aStaticShadows[0], 0x773BE8, 0x77430E); AdjustPointer(0x513390, &aStaticShadows[0], 0x773BE8, 0x77430E); AdjustPointer(0x513504, &aStaticShadows[0], 0x773BE8, 0x77430E); AdjustPointer(0x514931, &aStaticShadows[0], 0x773BE8, 0x77430E); AdjustPointer(0x514BD5, &aStaticShadows[0], 0x773BE8, 0x77430E); AdjustPointer(0x514C26, &aStaticShadows[0], 0x773BE8, 0x77430E); AdjustPointer(0x5133A8, &aStaticShadows[0], 0x773BE8, 0x77430E); AdjustPointer(0x51350E, &aStaticShadows[0], 0x773BE8, 0x77430E); AdjustPointer(0x514988, &aStaticShadows[0], 0x773BE8, 0x77430E); AdjustPointer(0x514BC9, &aStaticShadows[0], 0x773BE8, 0x77430E); AdjustPointer(0x514C20, &aStaticShadows[0], 0x773BE8, 0x77430E); AdjustPointer(0x5133FD, &aStaticShadows[0], 0x773BE8, 0x77430E); AdjustPointer(0x5134BE, &aStaticShadows[0], 0x773BE8, 0x77430E); AdjustPointer(0x514BBB, &aStaticShadows[0], 0x773BE8, 0x77430E); AdjustPointer(0x514C12, &aStaticShadows[0], 0x773BE8, 0x77430E); AdjustPointer(0x51340E, &aStaticShadows[0], 0x773BE8, 0x77430E); AdjustPointer(0x5134C8, &aStaticShadows[0], 0x773BE8, 0x77430E); AdjustPointer(0x514BB5, &aStaticShadows[0], 0x773BE8, 0x77430E); AdjustPointer(0x514C0C, &aStaticShadows[0], 0x773BE8, 0x77430E); AdjustPointer(0x5133C3, &aStaticShadows[0], 0x773BE8, 0x77430E); AdjustPointer(0x513488, &aStaticShadows[0], 0x773BE8, 0x77430E); AdjustPointer(0x5146A6, &aStaticShadows[0], 0x773BE8, 0x77430E); AdjustPointer(0x514708, &aStaticShadows[0], 0x773BE8, 0x77430E); AdjustPointer(0x514712, &aStaticShadows[0], 0x773BE8, 0x77430E); AdjustPointer(0x5133D9, &aStaticShadows[0], 0x773BE8, 0x77430E); AdjustPointer(0x51349E, &aStaticShadows[0], 0x773BE8, 0x77430E); AdjustPointer(0x514778, &aStaticShadows[0], 0x773BE8, 0x77430E); AdjustPointer(0x5133E7, &aStaticShadows[0], 0x773BE8, 0x77430E); AdjustPointer(0x5134A8, &aStaticShadows[0], 0x773BE8, 0x77430E); AdjustPointer(0x5147D4, &aStaticShadows[0], 0x773BE8, 0x77430E); AdjustPointer(0x5133F1, &aStaticShadows[0], 0x773BE8, 0x77430E); AdjustPointer(0x5134B2, &aStaticShadows[0], 0x773BE8, 0x77430E); AdjustPointer(0x5147DB, &aStaticShadows[0], 0x773BE8, 0x77430E); AdjustPointer(0x5133F7, &aStaticShadows[0], 0x773BE8, 0x77430E); AdjustPointer(0x5134B8, &aStaticShadows[0], 0x773BE8, 0x77430E); AdjustPointer(0x5147E2, &aStaticShadows[0], 0x773BE8, 0x77430E); AdjustPointer(0x5133BC, &aStaticShadows[0], 0x773BE8, 0x77430E); AdjustPointer(0x513514, &aStaticShadows[0], 0x773BE8, 0x77430E); AdjustPointer(0x516BFB, &aStaticShadows[0], 0x773BE8, 0x77430E); AdjustPointer(0x516C28, &aStaticShadows[0], 0x773BE8, 0x77430E); AdjustPointer(0x514635, &aStaticShadows[0], 0x773BE8, 0x77430E); AdjustPointer(0x514699, &aStaticShadows[0], 0x773BE8, 0x77430E); AdjustPointer(0x5148BA, &aStaticShadows[0], 0x773BE8, 0x77430E); AdjustPointer(0x513418, &aStaticShadows[0], 0x773BE8, 0x77430E); AdjustPointer(0x51351B, &aStaticShadows[0], 0x773BE8, 0x77430E); AdjustPointer(0x516C04, &aStaticShadows[0], 0x773BE8, 0x77430E); AdjustPointer(0x5133CD, &aStaticShadows[0], 0x773BE8, 0x77430E); AdjustPointer(0x513492, &aStaticShadows[0], 0x773BE8, 0x77430E); AdjustPointer(0x5146B7, &aStaticShadows[0], 0x773BE8, 0x77430E); AdjustPointer(0x514724, &aStaticShadows[0], 0x773BE8, 0x77430E); AdjustPointer(0x51472E, &aStaticShadows[0], 0x773BE8, 0x77430E); AdjustPointer(0x512CCE, &aStaticShadows[0], 0x773BE8, 0x77430E); AdjustPointer(0x512CD8, &aStaticShadows[0], 0x773BE8, 0x77430E); AdjustPointer(0x51463C, &aStaticShadows[0], 0x773BE8, 0x77430E); AdjustPointer(0x512CE2, &aStaticShadows[0], 0x773BE8, 0x77430E); AdjustPointer(0x512CEC, &aStaticShadows[0], 0x773BE8, 0x77430E); AdjustPointer(0x514643, &aStaticShadows[0], 0x773BE8, 0x77430E); AdjustPointer(0x512CF6, &aStaticShadows[0], 0x773BE8, 0x77430E); AdjustPointer(0x512D00, &aStaticShadows[0], 0x773BE8, 0x77430E); AdjustPointer(0x51464A, &aStaticShadows[0], 0x773BE8, 0x77430E); AdjustPointer(0x512D0A, &aStaticShadows[0], 0x773BE8, 0x77430E); AdjustPointer(0x512D14, &aStaticShadows[0], 0x773BE8, 0x77430E); AdjustPointer(0x514651, &aStaticShadows[0], 0x773BE8, 0x77430E); AdjustPointer(0x512D1E, &aStaticShadows[0], 0x773BE8, 0x77430E); AdjustPointer(0x512D28, &aStaticShadows[0], 0x773BE8, 0x77430E); AdjustPointer(0x514658, &aStaticShadows[0], 0x773BE8, 0x77430E); AdjustPointer(0x512D32, &aStaticShadows[0], 0x773BE8, 0x77430E); AdjustPointer(0x512D3C, &aStaticShadows[0], 0x773BE8, 0x77430E); AdjustPointer(0x51465F, &aStaticShadows[0], 0x773BE8, 0x77430E); AdjustPointer(0x512D46, &aStaticShadows[0], 0x773BE8, 0x77430E); AdjustPointer(0x512D50, &aStaticShadows[0], 0x773BE8, 0x77430E); AdjustPointer(0x514666, &aStaticShadows[0], 0x773BE8, 0x77430E); RedirectJump(0x513214, patch_513214); RedirectJump(0x51322B, patch_51322B); RedirectJump(0x51344C, patch_51344C); RedirectJump(0x51345B, patch_51345B); RedirectJump(0x51466B, patch_51466B); RedirectJump(0x5146C9, patch_5146C9); RedirectJump(0x5148C8, patch_5148C8); RedirectJump(0x5148E1, patch_5148E1); RedirectJump(0x512D58, patch_512D58); RedirectJump(0x516C30, patch_516C30); } DWORD ext_51321A = 0x51321A; DWORD ext_51322B = 0x51322B; void __declspec(naked) patch_513214() { __asm { cmp ebp, SSHADS_LIMIT jge loc_51322B jmp ext_51321A loc_51322B: jmp ext_51322B } } DWORD ext_513238 = 0x513238; DWORD ext_513442 = 0x513442; void __declspec(naked) patch_51322B() { __asm { cmp ebp, SSHADS_LIMIT jge loc_513442 mov edx, ebp jmp ext_513238 loc_513442: jmp ext_513442 } } DWORD ext_513452 = 0x513452; DWORD ext_51345B = 0x51345B; void __declspec(naked) patch_51344C() { __asm { cmp ebp, SSHADS_LIMIT jge loc_51345B jmp ext_513452 loc_51345B : jmp ext_51345B } } DWORD ext_513538 = 0x513538; DWORD ext_513465 = 0x513465; void __declspec(naked) patch_51345B() { __asm { cmp ebp, SSHADS_LIMIT jnz loc_513538 jmp ext_513465 loc_513538 : jmp ext_513538 } } DWORD ext_512D61 = 0x512D61; void __declspec(naked) patch_512D58() { __asm { add edx, 200h cmp eax, SSHADS_LIMIT jmp ext_512D61 } } DWORD ext_516C36 = 0x516C36; void __declspec(naked) patch_516C30() { __asm { add ebp, 40h cmp ebx, SSHADS_LIMIT jmp ext_516C36 } } DWORD ext_514674 = 0x514674; void __declspec(naked) patch_51466B() { __asm { add ebp, 200h cmp eax, SSHADS_LIMIT jmp ext_514674 } } DWORD ext_5146CE = 0x5146CE; void __declspec(naked) patch_5146C9() { __asm { pop ecx cmp eax, SSHADS_LIMIT pop ecx jmp ext_5146CE } } DWORD ext_5148CD = 0x5148CD; void __declspec(naked) patch_5148C8() { __asm { mov _EAX, eax mov eax, SSHADS_LIMIT cmp dword ptr[esp + 18h], eax mov eax, _EAX jmp ext_5148CD } } DWORD ext_5148E6 = 0x5148E6; void __declspec(naked) patch_5148E1() { __asm { mov _EAX, eax mov eax, SSHADS_LIMIT cmp dword ptr[esp + 20h], eax mov eax, _EAX jmp ext_5148E6 } } class StaticShadowsIII : public SimpleAdjuster { public: const char* GetLimitName() { return GetGVM().IsIII() ? "StaticShadows" : nullptr; } void ChangeLimit(int, const std::string& value) { SSHADS_LIMIT = std::stoi(value); PatchStaticShadowsIII(); } } StaticShadowsIII;
40.752505
113
0.695926
EightyVice
270902945fbb0bafcef69d1010e7b2409904154c
884
cpp
C++
Durna/Source/Runtime/Render/Buffer.cpp
MrWpGg/Durna
62c8ca2d69623e70e2dac49a5560cd3ac2c304ed
[ "Apache-2.0" ]
null
null
null
Durna/Source/Runtime/Render/Buffer.cpp
MrWpGg/Durna
62c8ca2d69623e70e2dac49a5560cd3ac2c304ed
[ "Apache-2.0" ]
null
null
null
Durna/Source/Runtime/Render/Buffer.cpp
MrWpGg/Durna
62c8ca2d69623e70e2dac49a5560cd3ac2c304ed
[ "Apache-2.0" ]
null
null
null
#include "DurnaPCH.h" #include "Buffer.h" #include "Runtime/Render/Renderer.h" #include "Runtime/Platform/OpenGL/OpenGLBuffer.h" namespace Durna { VertexBuffer* VertexBuffer::Create(float* Vertices, uint32 Size) { switch (Renderer::GetAPI()) { case RendererAPI::API::None: DRN_ASSERT(false, "Render API 'None' not supported!"); return nullptr; case RendererAPI::API::OpenGL: return new OpenGLVertexBuffer(Vertices, Size); default: DRN_ASSERT(false, "Unkown render API!"); return nullptr; } } IndexBuffer* IndexBuffer::Create(uint32* Indices, uint32 Size) { switch (Renderer::GetAPI()) { case RendererAPI::API::None: DRN_ASSERT(false, "Render API 'None' not supported!"); return nullptr; case RendererAPI::API::OpenGL: return new OpenGLIndexBuffer(Indices, Size); default: DRN_ASSERT(false, "Unkown render API!"); return nullptr; } } }
30.482759
102
0.714932
MrWpGg
27107cb661a4eb240d9e8dc5a1e41175be0b0735
1,422
cpp
C++
2020-sp-a-hw6-tgfnzb-master/2020-sp-a-hw6-tgfnzb-master/pa06.cpp
thomasfan100/DataStructure
4a69da72b8ae12aaa18363061528094c114a324b
[ "MIT" ]
null
null
null
2020-sp-a-hw6-tgfnzb-master/2020-sp-a-hw6-tgfnzb-master/pa06.cpp
thomasfan100/DataStructure
4a69da72b8ae12aaa18363061528094c114a324b
[ "MIT" ]
null
null
null
2020-sp-a-hw6-tgfnzb-master/2020-sp-a-hw6-tgfnzb-master/pa06.cpp
thomasfan100/DataStructure
4a69da72b8ae12aaa18363061528094c114a324b
[ "MIT" ]
null
null
null
#include "MyMap.h" int main() { MyMap<int, std::string> map_obj; map_obj.insert(MyPair<int, std::string>(3, "h")); map_obj[54].push_back('w'); map_obj[34] = "x"; map_obj[54] = "x"; map_obj[154] = "p"; map_obj[73] = "w"; map_obj[5] = "a"; map_obj[36] = "x"; map_obj[32] = "x"; map_obj[84] = "x"; map_obj.at(34) = "y"; const MyPair<int, std::string> *temp = map_obj.find(34); cout << temp->first << " " << temp->second << endl; map_obj.erase(34); cout << (map_obj.find(34) == nullptr) << endl; MyMap<int, std::string> map_obj2(map_obj); MyMap<int, std::string> map_obj3; map_obj3 = map_obj2 = map_obj; cout << "==== printing tree ====" << endl; map_obj2.print(); cout << "==== done printing tree ====" << endl; cout << "Size is: " << map_obj2.size() << endl; cout << "Count for 32 is: " << map_obj2.count(32) << endl << endl; map_obj.clear(); cout << "==== printing tree ====" << endl; map_obj.print(); cout << "==== done printing tree ====" << endl; cout << "Size is: " << map_obj.size() << endl; cout << "Count for 57 is: " << map_obj.count(57) << endl; try { map_obj.at(34) = "k"; } catch(const std::out_of_range &e) { cout << e.what(); } MyMap<char, int> new_tree; get_letter_frequency(new_tree); new_tree.print(); return 0; }
22.21875
70
0.523207
thomasfan100
2711c3e28c8d027c23751b5c08e27d208a47c21e
1,414
cpp
C++
src/core/signalRecord.cpp
BetaRavener/BrainActivityVisualizer
baf61856d67fbe31880bc4c6610621142777ac19
[ "BSD-3-Clause" ]
null
null
null
src/core/signalRecord.cpp
BetaRavener/BrainActivityVisualizer
baf61856d67fbe31880bc4c6610621142777ac19
[ "BSD-3-Clause" ]
null
null
null
src/core/signalRecord.cpp
BetaRavener/BrainActivityVisualizer
baf61856d67fbe31880bc4c6610621142777ac19
[ "BSD-3-Clause" ]
1
2021-07-12T00:49:41.000Z
2021-07-12T00:49:41.000Z
// Author: Ivan Sevcik <ivan-sevcik@hotmail.com> // Licensed under BSD 3-Clause License (see licenses/LICENSE.txt) #include "signalRecord.h" #include <algorithm> SignalRecord::Ptr SignalRecord::create(edf_hdr_struct *header, int signalIdx) { Ptr ptr(new SignalRecord); ptr->_header = header; ptr->_signalIdx = signalIdx; return ptr; } SignalData::Ptr SignalRecord::load() { edf_param_struct& params = _header->signalparam[_signalIdx]; long long samplesCount = params.smp_in_file; // Prepare storage std::vector<double> samples; samples.resize(samplesCount); // Prepare and read file edfrewind(_header->handle, _signalIdx); edfread_physical_samples(_header->handle, _signalIdx, samplesCount, &samples[0]); // Calculate this way to preserve resolution - the duration is in units of 100ns double freq = 1.e7 / (_header->datarecord_duration / params.smp_in_datarecord); SignalData::Ptr signalData = SignalData::create(std::move(samples), freq, label()); signalData->maxAmplitude(params.phys_max); signalData->minAmplitude(params.phys_min); return signalData; } std::string SignalRecord::label() const { std::string label = std::string(_header->signalparam[_signalIdx].label); // Trim the string while(std::isspace(*label.rbegin())) label.erase(label.length()-1); return label; } SignalRecord::SignalRecord() { }
28.857143
88
0.712871
BetaRavener
271a2d5e2ee89727b2187e27ff5c0999e32bfa86
2,274
cpp
C++
MWP8_1B_Budka_Suflera/main.cpp
MichalWilczek/spoj-tasks
6d5d77d750747ecb162c76a2b7eb4b8e8f2c4fc3
[ "Unlicense" ]
null
null
null
MWP8_1B_Budka_Suflera/main.cpp
MichalWilczek/spoj-tasks
6d5d77d750747ecb162c76a2b7eb4b8e8f2c4fc3
[ "Unlicense" ]
null
null
null
MWP8_1B_Budka_Suflera/main.cpp
MichalWilczek/spoj-tasks
6d5d77d750747ecb162c76a2b7eb4b8e8f2c4fc3
[ "Unlicense" ]
null
null
null
#include <iostream> #include <vector> #include <bits/stdc++.h> // std:: istringstream using namespace std; void printWords(vector<string> &words){ int wordsLength = words.size(); for (int i=0; i<wordsLength; i++){ cout << words[i] << endl; } } void extractDataFromString(vector<string> &wordsTextOriginal, string phrase) { istringstream ss(phrase); do { string word; ss >> word; wordsTextOriginal.push_back(word); } while (ss); } void uploadLyrics(vector<string> &textOriginalWords, vector<string> &textInputWords){ string textOriginal; string textInput; getline(cin, textOriginal); cin.sync(); getline(cin, textInput); extractDataFromString(textOriginalWords, textOriginal); extractDataFromString(textInputWords, textInput); } vector<string> findMissingWords(vector<string> &textOriginalWords, vector<string> &textInputWords){ vector<string> textInputWordsMissing; int i = 0; int j = 0; while (i < textOriginalWords.size()){ if (textOriginalWords[i] == textInputWords[j]){ i++; j++; } else { textInputWordsMissing.push_back(textOriginalWords[i]); i++; } } return textInputWordsMissing; } bool myComparator(string a, string b); vector<string> sortAlphabetically(vector<string> &words); void printMissingWords(vector<string> &textInputWordsMissing){ int textInputWordsMissingSize = textInputWordsMissing.size(); cout << textInputWordsMissingSize << endl; if (textInputWordsMissingSize > 0){ sortAlphabetically(textInputWordsMissing); printWords(textInputWordsMissing); } } int main() { vector<string> textOriginalWords; vector<string> textInputWords; uploadLyrics(textOriginalWords, textInputWords); vector<string> textInputWordsMissing = findMissingWords(textOriginalWords, textInputWords); printMissingWords(textInputWordsMissing); return 0; } bool myComparator(string a, string b){ bool comparator; comparator = a < b; return comparator; } vector<string> sortAlphabetically(vector<string> &words){ int wordsLength = words.size(); sort(words.begin(), words.end(), myComparator); return words; }
27.071429
99
0.684257
MichalWilczek
271db97f6fb76016d07cdfd3ed33b056cda4ae36
2,812
hpp
C++
src/cdpi_ssl.hpp
ytakano/catenaccio_dpi
284d8e805cb3a1f4714132063049d78065454261
[ "BSD-3-Clause" ]
2
2015-04-13T19:10:24.000Z
2019-04-27T02:53:49.000Z
src/cdpi_ssl.hpp
ytakano/catenaccio_dpi
284d8e805cb3a1f4714132063049d78065454261
[ "BSD-3-Clause" ]
null
null
null
src/cdpi_ssl.hpp
ytakano/catenaccio_dpi
284d8e805cb3a1f4714132063049d78065454261
[ "BSD-3-Clause" ]
null
null
null
#ifndef CDPI_SSL_HPP #define CDPI_SSL_HPP #include "cdpi_bytes.hpp" #include "cdpi_event.hpp" #include "cdpi_proto.hpp" #include <stdint.h> #include <list> #include <map> enum cdpi_ssl_content_type { SSL_CHANGE_CIPHER_SPEC = 20, SSL_ALERT = 21, SSL_HANDSHAKE = 22, SSL_APPLICATION_DATA = 23, SSL_HEARTBEAT = 24, }; enum cdpi_ssl_handshake_type { SSL_HELLO_REQUEST = 0, SSL_CLIENT_HELLO = 1, SSL_SERVER_HELLO = 2, SSL_HELLO_VERIFY_REQUEST = 3, SSL_NEW_SESSION_TICKET = 4, SSL_CERTIFICATE = 11, SSL_SERVER_KEY_EXCHANGE = 12, SSL_CERTIFICATE_REQUEST = 13, SSL_SERVER_HELLO_DONE = 14, SSL_CERTIFICATE_VERIFY = 15, SSL_CLIENT_KEY_EXCHANGE = 16, SSL_FINISHED = 20, SSL_CERTIFICATE_URL = 21, SSL_CERTIFICATE_STATUS = 22, SSL_SUPPLEMENTAL_DATA = 23, }; class cdpi_ssl; typedef boost::shared_ptr<cdpi_ssl> ptr_cdpi_ssl; class cdpi_ssl : public cdpi_proto { public: cdpi_ssl(cdpi_proto_type type, const cdpi_id_dir &id_dir, cdpi_stream &stream, ptr_cdpi_event_listener listener); virtual ~cdpi_ssl(); static bool is_ssl_client(std::list<cdpi_bytes> &bytes); static bool is_ssl_server(std::list<cdpi_bytes> &bytes); void parse(std::list<cdpi_bytes> &bytes); uint16_t get_ver() { return m_ver; } const uint8_t* get_random() { return m_random; } cdpi_bytes get_session_id() { return m_session_id; } uint32_t get_gmt_unix_time() { return m_gmt_unix_time; } const std::list<uint16_t>& get_cipher_suites() { return m_cipher_suites; } const std::list<uint8_t>& get_compression_methods() { return m_compression_methods; } const std::list<cdpi_bytes>& get_certificats() { return m_certificates; } const cdpi_id_dir &get_id_dir() { return m_id_dir; } bool is_change_cihper_spec() { return m_is_change_cipher_spec; } std::string num_to_cipher(uint16_t num); std::string num_to_compression(uint8_t num); private: uint16_t m_ver; uint8_t m_random[28]; uint32_t m_gmt_unix_time; cdpi_bytes m_session_id; std::list<cdpi_bytes> m_certificates; std::list<uint16_t> m_cipher_suites; std::list<uint8_t> m_compression_methods; cdpi_id_dir m_id_dir; cdpi_stream &m_stream; ptr_cdpi_event_listener m_listener; bool m_is_change_cipher_spec; void parse_handshake(char *data, int len); void parse_client_hello(char *data, int len); void parse_server_hello(char *data, int len); void parse_certificate(char *data, int len); void parse_change_cipher_spec(char *data, int len); }; #endif // CDPI_SSL_HPP
31.595506
89
0.671053
ytakano
2720a52680042f76737d0895811a54abc6994217
6,797
cpp
C++
src/DataSetBuilder.cpp
ddsmarques/pairtree
b04e590acf769269ebc38b76ba1f19d6344fef80
[ "BSD-3-Clause" ]
null
null
null
src/DataSetBuilder.cpp
ddsmarques/pairtree
b04e590acf769269ebc38b76ba1f19d6344fef80
[ "BSD-3-Clause" ]
null
null
null
src/DataSetBuilder.cpp
ddsmarques/pairtree
b04e590acf769269ebc38b76ba1f19d6344fef80
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2018 Daniel dos Santos Marques <danielsmarques7@gmail.com> // License: BSD 3 clause #include "DataSetBuilder.h" #include "Converter.h" #include "ErrorUtils.h" #include "Logger.h" #include "ReadCSV.h" #include <utility> #include <iostream> #include <set> DataSetBuilder::DataSetBuilder() { } DataSet DataSetBuilder::buildFromFile(std::string fileName, int64_t classColStart) { DataSet ds; ReadCSV csvReader; auto rawFile = csvReader.readFile(fileName); ErrorUtils::enforce(rawFile.size() > 0, "Empty file"); Logger::log() << "Started building file " << fileName; int64_t totAttrib = 0; if (classColStart <= 0) { totAttrib = rawFile[0].size() - 1; } else { totAttrib = classColStart; } // Add all attributes to the dataset for (int i = 0; i < totAttrib; i++) { createAttribute(i, std::move(rawFile), ds); } // Add all classes to the dataset createClass(classColStart, std::move(rawFile), ds); createSamples(std::move(rawFile), ds, classColStart); Logger::log() << "Finished building file " << fileName; return ds; } void DataSetBuilder::buildTrainTestFromFile(std::string trainFileName, std::string testFileName, int64_t classColStart, DataSet& trainDS, DataSet& testDS) { ReadCSV csvReader; auto rawTrainFile = csvReader.readFile(trainFileName); auto rawTestFile = csvReader.readFile(testFileName); ErrorUtils::enforce(rawTrainFile.size() > 0, "Empty train file"); ErrorUtils::enforce(rawTestFile.size() > 0, "Empty test file"); ErrorUtils::enforce(rawTrainFile[0].size() == rawTestFile[0].size(), "Train and test number of attributes don't match."); std::vector<std::vector<std::string>> rawFiles(rawTrainFile.size() + rawTestFile.size() - 1, std::vector<std::string>()); for (int64_t i = 0; i < rawTrainFile.size(); i++) { rawFiles[i] = rawTrainFile[i]; } for (int64_t i = 1; i < rawTestFile.size(); i++) { rawFiles[rawTrainFile.size() + i - 1] = rawTestFile[i]; } Logger::log() << "Started building train and test files."; int64_t totAttrib = 0; if (classColStart <= 0) { totAttrib = rawFiles[0].size() - 1; } else { totAttrib = classColStart; } // Add all attributes to the dataset for (int i = 0; i < totAttrib; i++) { createAttribute(i, std::move(rawFiles), trainDS); } // Add all classes to the dataset createClass(classColStart, std::move(rawFiles), trainDS); testDS.initAllAttributes(trainDS); // Add all samples createSamples(std::move(rawTrainFile), trainDS, classColStart); createSamples(std::move(rawTestFile), testDS, classColStart); Logger::log() << "Finished building train and test files."; } void DataSetBuilder::createAttribute(int col, std::vector<std::vector<std::string>>&& rawFile, DataSet& ds) { auto colType = getAttributeType(col, std::forward<std::vector<std::vector<std::string>>&&>(rawFile)); if (colType == AttributeType::INTEGER) { std::shared_ptr<Attribute<int64_t>> attrib = std::make_shared<Attribute<int64_t>>(AttributeType::INTEGER); attrib->setName(rawFile[0][col]); for (int i = 1; i < rawFile.size(); i++) if (col < rawFile[i].size()) { attrib->addValue(Converter::fromString<int64_t>(rawFile[i][col])); } attrib->sortIndexes(); ds.addAttribute<int64_t>(attrib); } else if (colType == AttributeType::DOUBLE) { std::shared_ptr<Attribute<double>> attrib = std::make_shared<Attribute<double>>(AttributeType::DOUBLE); attrib->setName(rawFile[0][col]); for (int i = 1; i < rawFile.size(); i++) if (col < rawFile[i].size()) { attrib->addValue(Converter::fromString<double>(rawFile[i][col])); } attrib->sortIndexes(); ds.addAttribute<double>(attrib); } else { std::shared_ptr<Attribute<std::string>> attrib = std::make_shared<Attribute<std::string>>(AttributeType::STRING); attrib->setName(rawFile[0][col]); for (int i = 1; i < rawFile.size(); i++) if (col < rawFile[i].size()) { attrib->addValue(rawFile[i][col]); } attrib->sortIndexes(); ds.addAttribute<std::string>(attrib); } } void DataSetBuilder::createClass(int64_t colStart, std::vector<std::vector<std::string>>&& rawFile, DataSet& ds) { if (colStart <= 0) { std::set<std::string> values; for (int64_t i = 1; i < rawFile.size(); i++) if (rawFile[i].size() > 0) { values.insert(rawFile[i][rawFile[i].size() - 1]); } std::vector<std::string> classes; for (auto&& s : values) { classes.push_back(s); } std::sort(classes.begin(), classes.end()); ds.setClasses(std::move(classes)); } else { ds.setClasses(std::vector<std::string>(rawFile[0].begin() + colStart, rawFile[0].end())); } } AttributeType DataSetBuilder::getAttributeType(int col, std::vector<std::vector<std::string>>&& rawFile) { bool isInteger = true; bool isDouble = true; for (int i = 1; i < rawFile.size(); i++) { if (col < rawFile[i].size()) { isInteger = isInteger & Converter::isInteger(rawFile[i][col]); isDouble = isDouble & Converter::isDouble(rawFile[i][col]); } } if (!isInteger && !isDouble) { return AttributeType::STRING; } else if (!isInteger) { return AttributeType::DOUBLE; } else if (isInteger) { return AttributeType::INTEGER; } } void DataSetBuilder::createSamples(std::vector<std::vector<std::string>>&& rawFile, DataSet& ds, int64_t classColStart) { int64_t totAttrib = ds.getTotAttributes(); // Create all samples for (int i = 1; i < rawFile.size(); i++) if (rawFile[i].size() > 0) { std::shared_ptr<Sample> s = std::make_shared<Sample>(ds.getTotAttributes(), ds.getTotClasses()); // Sample attributes for (int j = 0; j < totAttrib; j++) { if (ds.getAttributeType(j) == AttributeType::INTEGER) { s->inxValue_[j] = ds.getValueInx(j, Converter::fromString<int64_t>(rawFile[i][j])); } else if (ds.getAttributeType(j) == AttributeType::DOUBLE) { s->inxValue_[j] = ds.getValueInx(j, Converter::fromString<double>(rawFile[i][j])); } else { s->inxValue_[j] = ds.getValueInx(j, rawFile[i][j]); } } // Sample class benefit if (classColStart <= 0) { s->benefit_[ds.getClassInx(rawFile[i][totAttrib])] = -1; } else { for (int j = classColStart; j < rawFile[i].size(); j++) { s->benefit_[j - classColStart] = -Converter::fromString<double>(rawFile[i][j]); } } ds.addSample(s); } }
34.328283
123
0.61895
ddsmarques
272209a3f9b28db074f6ddd67885ddb87cbbf5b4
3,828
cpp
C++
src/ngraph/op/concat.cpp
bergtholdt/ngraph
55ca8bb15488ac7a567bb420ca32fcee25e60fe6
[ "Apache-2.0" ]
null
null
null
src/ngraph/op/concat.cpp
bergtholdt/ngraph
55ca8bb15488ac7a567bb420ca32fcee25e60fe6
[ "Apache-2.0" ]
null
null
null
src/ngraph/op/concat.cpp
bergtholdt/ngraph
55ca8bb15488ac7a567bb420ca32fcee25e60fe6
[ "Apache-2.0" ]
null
null
null
//***************************************************************************** // Copyright 2017-2018 Intel Corporation // // 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 <cassert> #include <memory> #include "ngraph/op/concat.hpp" #include "ngraph/op/slice.hpp" using namespace std; using namespace ngraph; op::Concat::Concat(const NodeVector& args, size_t concatenation_axis) : RequiresTensorViewArgs("Concat", args) , m_concatenation_axis(concatenation_axis) { if (m_inputs.size() < 1) { throw ngraph_error("At least one argument required"); } auto& input_0 = get_inputs().at(0); auto input_0_shape = input_0.get_shape(); if (m_concatenation_axis >= input_0_shape.size()) { throw ngraph_error("Concatenation axis is out of bounds"); } size_t concatenation_axis_length = input_0_shape.at(m_concatenation_axis); auto& input_0_element_type = input_0.get_element_type(); for (auto i = 1; i < get_inputs().size(); i++) { auto& input_i = get_inputs().at(i); auto input_i_shape = input_i.get_shape(); if (input_i_shape.size() != input_0_shape.size()) { throw ngraph_error("Arguments to concat do not have same rank"); } if (input_i.get_element_type() != input_0_element_type) { throw ngraph_error("Argument element types do not match"); } for (auto j = 0; j < input_i_shape.size(); j++) { if (j != m_concatenation_axis && input_0_shape.at(j) != input_i_shape.at(j)) { throw ngraph_error( "Arguments to concat do not have same dimension on a non-concatenation axis"); } else if (j == m_concatenation_axis) { concatenation_axis_length += input_i_shape.at(j); } } } vector<size_t> concatenated_shape = input_0_shape; concatenated_shape.at(m_concatenation_axis) = concatenation_axis_length; set_value_type_checked(make_shared<TensorViewType>(input_0_element_type, concatenated_shape)); } shared_ptr<Node> op::Concat::copy_with_new_args(const NodeVector& new_args) const { return make_shared<Concat>(new_args, m_concatenation_axis); } void op::Concat::generate_adjoints(autodiff::Adjoints& adjoints, const NodeVector& deltas) { auto delta = deltas.at(0); auto concat_result_shape = get_outputs().at(0).get_shape(); Coordinate arg_delta_slice_lower = Coordinate(concat_result_shape.size(), 0); Coordinate arg_delta_slice_upper = concat_result_shape; Coordinate arg_delta_slice_strides = Coordinate(concat_result_shape.size(), 1); size_t pos = 0; for (auto arg : get_arguments()) { auto arg_shape = arg->get_shape(); auto slice_width = arg_shape[m_concatenation_axis]; size_t next_pos = pos + slice_width; arg_delta_slice_lower[m_concatenation_axis] = pos; arg_delta_slice_upper[m_concatenation_axis] = next_pos; adjoints.add_delta( arg, make_shared<op::Slice>( delta, arg_delta_slice_lower, arg_delta_slice_upper, arg_delta_slice_strides)); pos = next_pos; } }
33.578947
98
0.644201
bergtholdt
2728732cf362f116d480d9dc38848ecdc0111aff
2,015
cpp
C++
source/utils/Constants.cpp
sirCamp/RunEscape
ae8185c955fb8dad13e3f188828a6b7a4ebd6f9d
[ "MIT" ]
null
null
null
source/utils/Constants.cpp
sirCamp/RunEscape
ae8185c955fb8dad13e3f188828a6b7a4ebd6f9d
[ "MIT" ]
null
null
null
source/utils/Constants.cpp
sirCamp/RunEscape
ae8185c955fb8dad13e3f188828a6b7a4ebd6f9d
[ "MIT" ]
null
null
null
// // Created by stefano on 02/09/16. // class Constants{ public: static const int LOAD_RAW_TEXTURE = 1; static const int LOAD_BMP_TEXTURE = 2; static const int LOAD_JGP_TEXTURE = 3; static const int ESC_KEY = 27; static const int SPACEBAR = 32; static const char UP_KEY = 'w'; static const char DOWN_KEY = 's'; static const char RIGHT_KEY = 'd'; static const char LEFT_KEY = 'a'; static const double PI; static const char *TEXTURE_FLOOR_CONFIGURATION; static const char *TEXTURE_SKY_CONFIGURATION; static const char *TEXTURE_WALL_CONFIGURATION; static const float ALARM_R_FACTOR; static const float ALARM_Z_FACTOR; static const string EXIT_TEXT; static const string LOSE_TEXT ; static const string WIN_TEXT ; static const string LOSE_TITLE; static const string WIN_TITLE; static const char *AUDIO_ALARM; static const char *AUDIO_WORLD; static const char *WORLD_CONFIGURATION; static const char *ALARM_CONFIGURATION; }; const float Constants::ALARM_R_FACTOR = 0.5; const float Constants::ALARM_Z_FACTOR = 0.25; const string Constants::EXIT_TEXT = "Type \"Esc\" to quit"; const string Constants::LOSE_TEXT = "You Lose! There are # alarms that are not disabled yet"; const string Constants::WIN_TEXT = "You Win!"; const string Constants::LOSE_TITLE = "You Lose!"; const string Constants::WIN_TITLE = "You Win!"; const double Constants::PI = 3.14159265358979323846; const char *Constants::AUDIO_ALARM = "assets/audio/336899__lalks__siren-02-feeling_2.wav"; const char *Constants::AUDIO_WORLD = "assets/audio/121980__stk13__jungle-ninja.wav"; const char *Constants::WORLD_CONFIGURATION = "configuration.txt"; const char *Constants::ALARM_CONFIGURATION = "alarms.txt"; const char *Constants::TEXTURE_FLOOR_CONFIGURATION = "assets/texture/floor.bmp"; const char *Constants::TEXTURE_SKY_CONFIGURATION = "assets/texture/sky.bmp"; const char *Constants::TEXTURE_WALL_CONFIGURATION = "assets/texture/wall.bmp";
31.484375
93
0.743424
sirCamp
272b7ca0b2de1d98d1cb5d0391672e523f82afce
294
hpp
C++
library/ATF/$0BC19B3D86456E0AB84C9DE48A18D228.hpp
lemkova/Yorozuya
f445d800078d9aba5de28f122cedfa03f26a38e4
[ "MIT" ]
29
2017-07-01T23:08:31.000Z
2022-02-19T10:22:45.000Z
library/ATF/$0BC19B3D86456E0AB84C9DE48A18D228.hpp
kotopes/Yorozuya
605c97d3a627a8f6545cc09f2a1b0a8afdedd33a
[ "MIT" ]
90
2017-10-18T21:24:51.000Z
2019-06-06T02:30:33.000Z
library/ATF/$0BC19B3D86456E0AB84C9DE48A18D228.hpp
kotopes/Yorozuya
605c97d3a627a8f6545cc09f2a1b0a8afdedd33a
[ "MIT" ]
44
2017-12-19T08:02:59.000Z
2022-02-24T23:15:01.000Z
// This file auto generated by plugin for ida pro. Generated code only for x64. Please, dont change manually #pragma once #include <common/common.h> START_ATF_NAMESPACE union $0BC19B3D86456E0AB84C9DE48A18D228 { wchar_t *wszArg; char *szArg; }; END_ATF_NAMESPACE
19.6
108
0.714286
lemkova
2734f6cf93207e5e09b958cb048a2b9653103461
104
hpp
C++
include/ompu/geo.hpp
ompu/ompu
c45d292a0af1b50039db9aa79e444fb7019615e9
[ "MIT" ]
4
2017-09-28T13:53:32.000Z
2018-02-14T21:29:25.000Z
include/ompu/geo.hpp
ompu/ompu
c45d292a0af1b50039db9aa79e444fb7019615e9
[ "MIT" ]
null
null
null
include/ompu/geo.hpp
ompu/ompu
c45d292a0af1b50039db9aa79e444fb7019615e9
[ "MIT" ]
null
null
null
#pragma once #include "ompu/geo/geo.hpp" #include "ompu/geo/strats.hpp" #include "ompu/geo/models.hpp"
17.333333
30
0.730769
ompu
2738410e308c848172ada9673fa45bf92d569319
2,179
cpp
C++
a2oj/Graphs/chicago.cpp
onexmaster/cp
b78b0f1e586d6977d86c97b32f48fed33f1469af
[ "Apache-2.0", "MIT" ]
null
null
null
a2oj/Graphs/chicago.cpp
onexmaster/cp
b78b0f1e586d6977d86c97b32f48fed33f1469af
[ "Apache-2.0", "MIT" ]
null
null
null
a2oj/Graphs/chicago.cpp
onexmaster/cp
b78b0f1e586d6977d86c97b32f48fed33f1469af
[ "Apache-2.0", "MIT" ]
null
null
null
// Created by Tanuj Jain #include<bits/stdc++.h> #include<ext/pb_ds/assoc_container.hpp> #include<ext/pb_ds/tree_policy.hpp> using namespace std; using namespace __gnu_pbds; #define pb push_back #define mp make_pair typedef long long ll; typedef pair<int,int> pii; template<class T> using oset=tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>; const int MAXN=105; double dist[MAXN]; double ada_f[MAXN][MAXN]; void dijkstras(map<int,vector<pair<int,double>>>&ada, int n) { for(int i=1;i<=n;i++) dist[i]=-1.0; dist[1]=1.0; //using max heap here, since we want to find the path which maximizes my probabilty priority_queue<pair<double,int>>pq; pq.push({1.0,1}); while(!pq.empty()) { double curr_prob=pq.top().first; int curr=pq.top().second; pq.pop(); //cout<<curr<<endl; for(auto edges : ada[curr]) { if(dist[edges.first]<curr_prob*edges.second) { dist[edges.first]=curr_prob*edges.second; pq.push({dist[edges.first], edges.first}); } } } } void floyd_warshall(int n) { for(int k=1;k<=n;k++) { for(int i=1;i<=n;i++) { for(int j=1;j<=n;j++) ada_f[i][j]=max(ada_f[i][j], ada_f[i][k]*ada_f[j][k]); } } } int main() { ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); #ifndef ONLINE_JUDGE freopen("inputf.in","r",stdin); freopen("outputf.in","w",stdout); #endif int n; while(cin>>n) { if(n==0) return 0; else { int m; cin>>m; map<int,vector<pair<int,double>>>ada; for(int i=0;i<m;i++) { int x,y; double prob; cin>>x>>y>>prob; prob/=100.0; ada[x].pb({y,prob}); ada[y].pb({x,prob}); ada_f[x][y]=prob; ada_f[y][x]=prob; } dijkstras(ada, n); //floyd_warshall(n); // for(int i=1;i<=n;i++) // cout<<dist[i]<<" "; // cout<<endl; // for(int i=1;i<=n;i++) // { // for(int j=1;j<=n;j++) // cout<<ada_f[i][j]<<" "; // cout<<endl; // } //cout<<fixed<<setprecision(6)<<dist[n]*100<<" "<<"percent"<<endl; //cout<<fixed<<setprecision(6)<<ada_f[1][n]*100<<" "<<"percent"<<endl; } } }
21.574257
106
0.565856
onexmaster
2739a7a9d82bb157c828e09447b8b7498e8ef55a
12,053
cpp
C++
xtd.forms.native.wxwidgets/src/xtd/forms/native/wxwidgets/control.cpp
lineCode/xtd.forms
53b126a41513b4009870498b9f8e522dfc94c8de
[ "MIT" ]
1
2022-02-04T08:15:31.000Z
2022-02-04T08:15:31.000Z
xtd.forms.native.wxwidgets/src/xtd/forms/native/wxwidgets/control.cpp
lineCode/xtd.forms
53b126a41513b4009870498b9f8e522dfc94c8de
[ "MIT" ]
null
null
null
xtd.forms.native.wxwidgets/src/xtd/forms/native/wxwidgets/control.cpp
lineCode/xtd.forms
53b126a41513b4009870498b9f8e522dfc94c8de
[ "MIT" ]
null
null
null
#include <map> #include <stdexcept> #include <xtd/drawing/system_colors.hpp> #include <xtd/drawing/system_fonts.hpp> #include <xtd/forms/native/application.hpp> #include <xtd/forms/native/control.hpp> #include "hdc_wrapper.hpp" #include "wx_button.hpp" #include "wx_check_box.hpp" #include "wx_control.hpp" #include "wx_form.hpp" #include "wx_group_box.hpp" #include "wx_label.hpp" #include "wx_list_box.hpp" #include "wx_panel.hpp" #include "wx_progress_bar.hpp" #include "wx_radio_button.hpp" #include "wx_text_box.hpp" #include "wx_track_bar.hpp" #include <wx/dcmemory.h> #include <wx/dcclient.h> #include <wx/dcscreen.h> #include <wx/font.h> using namespace std; using namespace xtd; using namespace xtd::drawing; using namespace xtd::forms::native; extern int32_t __mainloop_runnning__; color control::back_color(intptr_t control) { if (control == 0) return color::empty; wxColour colour = reinterpret_cast<control_handler*>(control)->control()->GetBackgroundColour(); #if defined (__WXOSX__) return color::from_handle(reinterpret_cast<intptr_t>(colour.OSXGetNSColor())); #endif return color::from_argb(colour.Alpha(), colour.Red(), colour.Green(), colour.Blue()); } void control::back_color(intptr_t control, const color& color) { if (control == 0) return; #if defined (__WXOSX__) if (color.handle()) reinterpret_cast<control_handler*>(control)->control()->SetBackgroundColour(wxColour(reinterpret_cast<WX_NSColor>(color.handle()))); else reinterpret_cast<control_handler*>(control)->control()->SetBackgroundColour(wxColour(color.r(), color.g(), color.b(), color.a())); #else reinterpret_cast<control_handler*>(control)->control()->SetBackgroundColour(wxColour(color.r(), color.g(), color.b(), color.a())); #endif } intptr_t control::create(const forms::create_params& create_params) { application::start_application(); // Must be first if (create_params.class_name() == "button") return reinterpret_cast<intptr_t>(new wx_button(create_params)); if (create_params.class_name() == "checkbox") return reinterpret_cast<intptr_t>(new wx_check_box(create_params)); if (create_params.class_name() == "form") return reinterpret_cast<intptr_t>(new wx_form(create_params)); if (create_params.class_name() == "groupbox") return reinterpret_cast<intptr_t>(new wx_group_box(create_params)); if (create_params.class_name() == "label") return reinterpret_cast<intptr_t>(new wx_label(create_params)); if (create_params.class_name() == "listbox") return reinterpret_cast<intptr_t>(new wx_list_box(create_params)); if (create_params.class_name() == "panel") return reinterpret_cast<intptr_t>(new wx_panel(create_params)); if (create_params.class_name() == "progressbar") return reinterpret_cast<intptr_t>(new wx_progress_bar(create_params)); if (create_params.class_name() == "radiobutton") return reinterpret_cast<intptr_t>(new wx_radio_button(create_params)); if (create_params.class_name() == "textbox") return reinterpret_cast<intptr_t>(new wx_text_box(create_params)); if (create_params.class_name() == "trackbar") return reinterpret_cast<intptr_t>(new wx_track_bar(create_params)); return reinterpret_cast<intptr_t>(new wx_control(create_params)); } intptr_t control::create_paint_graphics(intptr_t control) { xtd::drawing::native::hdc_wrapper* hdc_wrapper = new xtd::drawing::native::hdc_wrapper(); if (control == 0) hdc_wrapper->create<wxScreenDC>(); else hdc_wrapper->create<wxPaintDC>(reinterpret_cast<control_handler*>(control)->control()); return reinterpret_cast<intptr_t>(hdc_wrapper); } intptr_t control::create_graphics(intptr_t control) { xtd::drawing::native::hdc_wrapper* hdc_wrapper = new xtd::drawing::native::hdc_wrapper(); if (control == 0) hdc_wrapper->create<wxScreenDC>(); else hdc_wrapper->create<wxClientDC>(reinterpret_cast<control_handler*>(control)->control()); return reinterpret_cast<intptr_t>(hdc_wrapper); } intptr_t control::def_wnd_proc(intptr_t control, intptr_t hwnd, int32_t msg, intptr_t wparam, intptr_t lparam, intptr_t presult, intptr_t handle) { if (!control) return 0; switch (msg) { case WM_GETTEXTLENGTH: return (reinterpret_cast<control_handler*>(hwnd))->control()->GetLabel().ToStdString().size(); break; case WM_GETTEXT: return strlen(strncpy(reinterpret_cast<char*>(lparam), reinterpret_cast<control_handler*>(hwnd)->control()->GetLabel().ToStdString().c_str(), wparam)); break; } if (handle != 0) return reinterpret_cast<control_handler*>(control)->call_def_wnd_proc(hwnd, msg, wparam, lparam, presult, handle); return 0; } color control::default_back_color() { #if wxMAJOR_VERSION >= 3 && wxMINOR_VERSION >= 1 return system_colors::control(); #else static color default_color; if (default_color == color::empty) { native::application::start_application(); wxFrame* frame = new wxFrame(nullptr, wxID_ANY, ""); wxButton* button = new wxButton(frame, wxID_ANY, ""); wxColour colour = button->GetBackgroundColour(); #if defined (__WXOSX__) default_color = color::from_handle(reinterpret_cast<intptr_t>(colour.OSXGetNSColor())); #else default_color = color::from_argb(colour.Alpha(), colour.Red(), colour.Green(), colour.Blue()); #endif delete button; delete frame; } return default_color; #endif } color control::default_fore_color() { #if wxMAJOR_VERSION >= 3 && wxMINOR_VERSION >= 1 return system_colors::control_text(); #else static color default_color; if (default_color == color::empty) { native::application::start_application(); wxFrame* frame = new wxFrame(nullptr, wxID_ANY, ""); wxButton* button = new wxButton(frame, wxID_ANY, ""); wxColour colour = button->GetForegroundColour(); #if defined (__WXOSX__) default_color = color::from_handle(reinterpret_cast<intptr_t>(colour.OSXGetNSColor())); #else default_color = color::from_argb(colour.Alpha(), colour.Red(), colour.Green(), colour.Blue()); #endif delete button; delete frame; } return default_color; #endif } font control::default_font() { return system_fonts::default_font(); } void control::destroy(intptr_t control) { if (control == 0) return; if (reinterpret_cast<control_handler*>(control)->control() == 0) return; if (wxTheApp) { reinterpret_cast<control_handler*>(control)->destroy(); #if !defined (__WXOSX__) wxTheApp->wxEvtHandler::ProcessPendingEvents(); //if (!wxTheApp->IsMainLoopRunning()) { //application::end_application(); //application::start_application(); //} #endif } delete reinterpret_cast<class control_handler*>(control); } void control::init() { application::start_application(); // Must be first } drawing::rectangle control::client_rectangle(intptr_t control) { if (control == 0) return {}; wxRect rect = reinterpret_cast<control_handler*>(control)->control()->GetClientRect(); return {rect.GetX(), rect.GetY(), rect.GetWidth(), rect.GetHeight()}; } drawing::size control::client_size(intptr_t control) { if (control == 0) return {}; wxSize size = reinterpret_cast<control_handler*>(control)->control()->GetClientSize(); return {size.GetWidth(), size.GetHeight()}; } void control::client_size(intptr_t control, const drawing::size& size) { if (control == 0) return; reinterpret_cast<control_handler*>(control)->control()->SetClientSize(size.width(), size.height()); } bool control::enabled(intptr_t control) { if (control == 0) return false; return reinterpret_cast<control_handler*>(control)->control()->IsEnabled(); } void control::enabled(intptr_t control, bool enabled) { if (control == 0) return; reinterpret_cast<control_handler*>(control)->control()->Enable(enabled); } color control::fore_color(intptr_t control) { if (control == 0) return color::empty; wxColour colour = reinterpret_cast<control_handler*>(control)->control()->GetForegroundColour(); #if defined (__WXOSX__) return color::from_handle(reinterpret_cast<intptr_t>(colour.OSXGetNSColor())); #endif return color::from_argb(colour.Alpha(), colour.Red(), colour.Green(), colour.Blue()); } void control::fore_color(intptr_t control, const color& color) { if (control == 0) return; #if defined (__WXOSX__) if (color.handle()) reinterpret_cast<control_handler*>(control)->control()->SetForegroundColour(wxColour(reinterpret_cast<WX_NSColor>(color.handle()))); else reinterpret_cast<control_handler*>(control)->control()->SetForegroundColour(wxColour(color.r(), color.g(), color.b(), color.a())); #else reinterpret_cast<control_handler*>(control)->control()->SetForegroundColour(wxColour(color.r(), color.g(), color.b(), color.a())); #endif } drawing::font control::font(intptr_t control) { return drawing::font::from_hfont(reinterpret_cast<intptr_t>(new wxFont(reinterpret_cast<control_handler*>(control)->control()->GetFont()))); } void control::font(intptr_t control, const drawing::font& font) { if (control == 0) return; reinterpret_cast<control_handler*>(control)->control()->SetFont(*reinterpret_cast<wxFont*>(font.handle())); } point control::location(intptr_t control) { if (control == 0) return {}; wxPoint location = reinterpret_cast<control_handler*>(control)->control()->GetPosition(); return {location.x, location.y}; } void control::location(intptr_t control, const point& location) { if (control == 0) return; reinterpret_cast<control_handler*>(control)->control()->SetPosition({location.x(), location.y()}); } intptr_t control::parent(intptr_t control) { return reinterpret_cast<intptr_t>(reinterpret_cast<control_handler*>(control)->control()->GetParent()); } void control::parent(intptr_t control, intptr_t parent) { reinterpret_cast<control_handler*>(control)->control()->Reparent(reinterpret_cast<control_handler*>(parent)->control()); } drawing::size control::size(intptr_t control) { if (control == 0) return {}; wxSize size = reinterpret_cast<control_handler*>(control)->control()->GetSize(); return {size.GetWidth(), size.GetHeight()}; } void control::size(intptr_t control, const drawing::size& size) { if (control == 0) return; reinterpret_cast<control_handler*>(control)->SetSize(size.width(), size.height()); } string control::text(intptr_t control) { if (control == 0) return {}; //return reinterpret_cast<control_handler*>(control)->control()->GetLabel().ToStdString(); intptr_t result = send_message(control, control, WM_GETTEXTLENGTH, 0, 0); string text(result, 0); result = send_message(control, control, WM_GETTEXT, result + 1, reinterpret_cast<intptr_t>(text.data())); return text; } void control::text(intptr_t control, const string& text) { if (control == 0) return; reinterpret_cast<control_handler*>(control)->control()->SetLabel(text); send_message(control, control, WM_SETTEXT, 0, reinterpret_cast<intptr_t>(reinterpret_cast<control_handler*>(control)->control()->GetLabel().ToStdString().c_str())); } bool control::visible(intptr_t control) { if (control == 0) return false; return reinterpret_cast<control_handler*>(control)->control()->IsShown(); } void control::visible(intptr_t control, bool visible) { if (control == 0) return; reinterpret_cast<control_handler*>(control)->control()->Show(visible); } void control::refresh(intptr_t control) { if (control == 0) return; reinterpret_cast<control_handler*>(control)->control()->Refresh(); } void control::register_wnd_proc(intptr_t control, const delegate<intptr_t(intptr_t, int32_t, intptr_t, intptr_t, intptr_t)>& wnd_proc) { if (control == 0) return; reinterpret_cast<control_handler*>(control)->wnd_proc += wnd_proc; } void control::unregister_wnd_proc(intptr_t control, const delegate<intptr_t(intptr_t, int32_t, intptr_t, intptr_t, intptr_t)>& wnd_proc) { if (control == 0) return; reinterpret_cast<control_handler*>(control)->wnd_proc -= wnd_proc; } intptr_t control::send_message(intptr_t control, intptr_t hwnd, int32_t msg, intptr_t wparam, intptr_t lparam) { if (hwnd == 0) return -1; return reinterpret_cast<control_handler*>(control)->send_message(hwnd, msg, wparam, lparam, 0); }
41.136519
179
0.739318
lineCode
273ca986ebe51734419d4f96004ac7b23c6b2989
2,503
cpp
C++
regression/esbmc-cpp/cpp/ch18_9/main.cpp
shmarovfedor/esbmc
3226a3d68b009d44b9535a993ac0f25e1a1fbedd
[ "BSD-3-Clause" ]
143
2015-06-22T12:30:01.000Z
2022-03-21T08:41:17.000Z
regression/esbmc-cpp/cpp/ch18_9/main.cpp
shmarovfedor/esbmc
3226a3d68b009d44b9535a993ac0f25e1a1fbedd
[ "BSD-3-Clause" ]
542
2017-06-02T13:46:26.000Z
2022-03-31T16:35:17.000Z
regression/esbmc-cpp/cpp/ch18_9/main.cpp
shmarovfedor/esbmc
3226a3d68b009d44b9535a993ac0f25e1a1fbedd
[ "BSD-3-Clause" ]
81
2015-10-21T22:21:59.000Z
2022-03-24T14:07:55.000Z
// Fig. 18.18: fig18_18.cpp // Using functions islower, isupper, tolower and toupper. #include <iostream> using std::cout; using std::endl; #include <cctype> // character-handling function prototypes int main() { cout << "According to islower:\n" << ( islower( 'p' ) ? "p is a" : "p is not a" ) << " lowercase letter\n" << ( islower( 'P' ) ? "P is a" : "P is not a" ) << " lowercase letter\n" << ( islower( '5' ) ? "5 is a" : "5 is not a" ) << " lowercase letter\n" << ( islower( '!' ) ? "! is a" : "! is not a" ) << " lowercase letter\n"; cout << "\nAccording to isupper:\n" << ( isupper( 'D' ) ? "D is an" : "D is not an" ) << " uppercase letter\n" << ( isupper( 'd' ) ? "d is an" : "d is not an" ) << " uppercase letter\n" << ( isupper( '8' ) ? "8 is an" : "8 is not an" ) << " uppercase letter\n" << ( isupper('$') ? "$ is an" : "$ is not an" ) << " uppercase letter\n"; cout << "\nu converted to uppercase is " << static_cast< char >( toupper( 'u' ) ) << "\n7 converted to uppercase is " << static_cast< char >( toupper( '7' ) ) << "\n$ converted to uppercase is " << static_cast< char >( toupper( '$' ) ) << "\nL converted to lowercase is " << static_cast< char >( tolower( 'L' ) ) << endl; return 0; } // end main /************************************************************************** * (C) Copyright 1992-2003 by Deitel & Associates, Inc. and Prentice * * Hall. All Rights Reserved. * * * * DISCLAIMER: The authors and publisher of this book have used their * * best efforts in preparing the book. These efforts include the * * development, research, and testing of the theories and programs * * to determine their effectiveness. The authors and publisher make * * no warranty of any kind, expressed or implied, with regard to these * * programs or to the documentation contained in these books. The authors * * and publisher shall not be liable in any event for incidental or * * consequential damages in connection with, or arising out of, the * * furnishing, performance, or use of these programs. * *************************************************************************/
43.155172
75
0.495006
shmarovfedor
27402df1b135e669d9c38c3a3d821b6ce9354195
714
cpp
C++
12/1277. Count Square Submatrices with All Ones.cpp
eagleoflqj/LeetCode
ca5dd06cad4c7fe5bf679cca7ee60f4348b316e9
[ "MIT" ]
null
null
null
12/1277. Count Square Submatrices with All Ones.cpp
eagleoflqj/LeetCode
ca5dd06cad4c7fe5bf679cca7ee60f4348b316e9
[ "MIT" ]
1
2021-12-25T10:33:23.000Z
2022-02-16T00:34:05.000Z
12/1277. Count Square Submatrices with All Ones.cpp
eagleoflqj/LeetCode
ca5dd06cad4c7fe5bf679cca7ee60f4348b316e9
[ "MIT" ]
null
null
null
class Solution { public: int countSquares(vector<vector<int>>& matrix) { int m = matrix.size(), n = matrix[0].size(); int ret = accumulate(matrix[0].begin(), matrix[0].end(), 0); for(int i = 1; i < m; ++i) { ret += matrix[i][0]; for(int j = 1; j < n; ++j) { if(!matrix[i][j]) continue; int left = matrix[i - 1][j], up = matrix[i][j - 1]; if(left == up) matrix[i][j] = left + (matrix[i - left][j - left] > 0); else matrix[i][j] = min(left, up) + 1; ret += matrix[i][j]; } } return ret; } };
32.454545
75
0.387955
eagleoflqj
27407d070f3394d3f897392e53f9776529bdbf3d
321
cpp
C++
HelloWorld/Panda3D HelloWorld/Hello World.cpp
RockRockWhite/Panda3D-learning
5752b0b437083b8d9f4d7f1b01ec0eda219f6979
[ "MIT" ]
null
null
null
HelloWorld/Panda3D HelloWorld/Hello World.cpp
RockRockWhite/Panda3D-learning
5752b0b437083b8d9f4d7f1b01ec0eda219f6979
[ "MIT" ]
null
null
null
HelloWorld/Panda3D HelloWorld/Hello World.cpp
RockRockWhite/Panda3D-learning
5752b0b437083b8d9f4d7f1b01ec0eda219f6979
[ "MIT" ]
null
null
null
#include "pandaFrameWork.h" #include "windowFrameWork.h" int main(int argc,char* argv[]) { PandaFramework framework; WindowFramework* window; framework.open_framework(argc, argv); framework.set_window_title("Hello World!"); window = framework.open_window(); framework.main_loop(); framework.close_framework(); }
21.4
44
0.76324
RockRockWhite
27441f67cc80217ecd3973aead6ddc66b95cb8b6
1,904
cpp
C++
linked_lists/linked_list.cpp
agurusa/interview_prep
b777e0803ee8d3316c0f3fb60efd8463d1437424
[ "MIT" ]
null
null
null
linked_lists/linked_list.cpp
agurusa/interview_prep
b777e0803ee8d3316c0f3fb60efd8463d1437424
[ "MIT" ]
null
null
null
linked_lists/linked_list.cpp
agurusa/interview_prep
b777e0803ee8d3316c0f3fb60efd8463d1437424
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> // build the linked list class Node{ public: Node *next = NULL; int data; Node(int d){ data = d; } //included for comparisons in tests.cpp friend bool operator == (const Node lhs, const Node rhs){ return(lhs.data == rhs.data); } friend std::ostream& operator <<( std::ostream& os, const Node& node){ os << node.data; return os; } }; class LinkedList { public: Node *head = NULL; LinkedList(std::vector<int> d = {}){ for(int i = 0; i < d.size(); i++){ appendToTail(d[i]); } } void appendToTail(int d){ Node *end = new Node(d); Node *n = head; if(head == NULL){ head = end; } else{ while(n->next != NULL){ n = n->next; } n->next = end; } } void deleteNode(Node *node){ Node *n = head; if(node == n){ head = n->next; } else{ while(n!=NULL){ Node *nn = n->next; if(nn == node){ if(nn->next != NULL){ n->next = nn->next; } else{ n->next = NULL; } } else{ n = n->next; } } } } //included for comparisons in tests.cpp friend bool operator == (const LinkedList lhs, const LinkedList rhs){ Node *nl = lhs.head; Node *nr = rhs.head; if(nl->data != nr->data){ return false; } while(nl != NULL && nr!= NULL){ Node *nln = nl->next; Node *nrn = nr->next; if(nln == NULL || nrn == NULL){ if(nln == NULL && nrn == NULL){ return true; } else{ return false; } } else if(nln->data != nrn->data){ return false; } else{ nl = nl->next; nr = nr->next; } } return true; } friend std::ostream& operator <<( std::ostream& os, LinkedList const& list){ Node *n = list.head; while(n!= NULL){ os << n->data << " "; n = n->next; } return os; } Node* node_at_i(int i){ Node*n = head; for(int j = 0; j < i; j++){ n = n->next; } return n; } };
16.701754
77
0.527836
agurusa
274bb8d4dac24cf0d494098d0ccd7c82538bf0ac
1,468
cpp
C++
Visual Mercutio/zDB/PSS_DatabaseManipulator.cpp
Jeanmilost/Visual-Mercutio
f079730005b6ce93d5e184bb7c0893ccced3e3ab
[ "MIT" ]
1
2022-01-31T06:24:24.000Z
2022-01-31T06:24:24.000Z
Visual Mercutio/zDB/PSS_DatabaseManipulator.cpp
Jeanmilost/Visual-Mercutio
f079730005b6ce93d5e184bb7c0893ccced3e3ab
[ "MIT" ]
2
2021-04-11T15:50:42.000Z
2021-06-05T08:23:04.000Z
Visual Mercutio/zDB/PSS_DatabaseManipulator.cpp
Jeanmilost/Visual-Mercutio
f079730005b6ce93d5e184bb7c0893ccced3e3ab
[ "MIT" ]
2
2021-01-08T00:55:18.000Z
2022-01-31T06:24:18.000Z
/**************************************************************************** * ==> PSS_DatabaseManipulator ---------------------------------------------* **************************************************************************** * Description : Provides a database manipulator * * Developer : Processsoft * ****************************************************************************/ #include "stdafx.h" #include "PSS_DatabaseManipulator.h" #ifdef _DEBUG #undef THIS_FILE static char THIS_FILE[] = __FILE__; #define new DEBUG_NEW #endif //--------------------------------------------------------------------------- // PSS_DatabaseManipulator //--------------------------------------------------------------------------- PSS_DatabaseManipulator::PSS_DatabaseManipulator(const CString& name, IEType type) : m_Name(name), m_Type(type) {} //--------------------------------------------------------------------------- PSS_DatabaseManipulator::~PSS_DatabaseManipulator() {} //--------------------------------------------------------------------------- bool PSS_DatabaseManipulator::CreateDatabase() { return true; } //--------------------------------------------------------------------------- bool PSS_DatabaseManipulator::GetTableList(CStringArray& tableArray) { return true; } //---------------------------------------------------------------------------
38.631579
84
0.330381
Jeanmilost
274e27e5519110ecb255b595c16644c5ce072780
918
inl
C++
Source/Foundation/Time/Time.inl
yuyang158/TianEngine
59029bde8af0f45d5adc99324ca7bc38d4cb8de9
[ "MIT" ]
null
null
null
Source/Foundation/Time/Time.inl
yuyang158/TianEngine
59029bde8af0f45d5adc99324ca7bc38d4cb8de9
[ "MIT" ]
null
null
null
Source/Foundation/Time/Time.inl
yuyang158/TianEngine
59029bde8af0f45d5adc99324ca7bc38d4cb8de9
[ "MIT" ]
null
null
null
#include "Time.h" TIAN_FORCE_INLINE constexpr double Time::GetTotalNanoseconds() const { return m_fTime * 0.000000001; } TIAN_FORCE_INLINE constexpr double Time::GetTotalMicroseconds() const { return m_fTime * 0.000001; } TIAN_FORCE_INLINE constexpr double Time::GetTotalMilliseconds() const { return m_fTime * 0.001; } TIAN_FORCE_INLINE constexpr double Time::GetTotalSeconds() const { return m_fTime; } TIAN_FORCE_INLINE constexpr void Time::operator-=(const Time& other) { m_fTime -= other.m_fTime; } TIAN_FORCE_INLINE constexpr void Time::operator+=(const Time& other) { m_fTime += other.m_fTime; } TIAN_FORCE_INLINE constexpr Time Time::operator-() { return Time(-m_fTime); } TIAN_FORCE_INLINE constexpr Time Time::operator-(const Time& other) { return Time(m_fTime - other.m_fTime); } TIAN_FORCE_INLINE constexpr Time Time::operator+(const Time& other) { return Time(m_fTime + other.m_fTime); }
24.810811
71
0.764706
yuyang158
274f9df4ba6c1d2136e0afa3a8b9d99df2e4262e
25,288
inl
C++
src/fonts/stb_font_times_25_usascii.inl
stetre/moonfonts
5c8010c02ea62edcf42902e09478b0cd14af56ea
[ "MIT" ]
3
2018-03-13T12:51:57.000Z
2021-10-11T11:32:17.000Z
src/fonts/stb_font_times_25_usascii.inl
stetre/moonfonts
5c8010c02ea62edcf42902e09478b0cd14af56ea
[ "MIT" ]
null
null
null
src/fonts/stb_font_times_25_usascii.inl
stetre/moonfonts
5c8010c02ea62edcf42902e09478b0cd14af56ea
[ "MIT" ]
null
null
null
// Font generated by stb_font_inl_generator.c (4/1 bpp) // // Following instructions show how to use the only included font, whatever it is, in // a generic way so you can replace it with any other font by changing the include. // To use multiple fonts, replace STB_SOMEFONT_* below with STB_FONT_times_25_usascii_*, // and separately install each font. Note that the CREATE function call has a // totally different name; it's just 'stb_font_times_25_usascii'. // /* // Example usage: static stb_fontchar fontdata[STB_SOMEFONT_NUM_CHARS]; static void init(void) { // optionally replace both STB_SOMEFONT_BITMAP_HEIGHT with STB_SOMEFONT_BITMAP_HEIGHT_POW2 static unsigned char fontpixels[STB_SOMEFONT_BITMAP_HEIGHT][STB_SOMEFONT_BITMAP_WIDTH]; STB_SOMEFONT_CREATE(fontdata, fontpixels, STB_SOMEFONT_BITMAP_HEIGHT); ... create texture ... // for best results rendering 1:1 pixels texels, use nearest-neighbor sampling // if allowed to scale up, use bilerp } // This function positions characters on integer coordinates, and assumes 1:1 texels to pixels // Appropriate if nearest-neighbor sampling is used static void draw_string_integer(int x, int y, char *str) // draw with top-left point x,y { ... use texture ... ... turn on alpha blending and gamma-correct alpha blending ... glBegin(GL_QUADS); while (*str) { int char_codepoint = *str++; stb_fontchar *cd = &fontdata[char_codepoint - STB_SOMEFONT_FIRST_CHAR]; glTexCoord2f(cd->s0, cd->t0); glVertex2i(x + cd->x0, y + cd->y0); glTexCoord2f(cd->s1, cd->t0); glVertex2i(x + cd->x1, y + cd->y0); glTexCoord2f(cd->s1, cd->t1); glVertex2i(x + cd->x1, y + cd->y1); glTexCoord2f(cd->s0, cd->t1); glVertex2i(x + cd->x0, y + cd->y1); // if bilerping, in D3D9 you'll need a half-pixel offset here for 1:1 to behave correct x += cd->advance_int; } glEnd(); } // This function positions characters on float coordinates, and doesn't require 1:1 texels to pixels // Appropriate if bilinear filtering is used static void draw_string_float(float x, float y, char *str) // draw with top-left point x,y { ... use texture ... ... turn on alpha blending and gamma-correct alpha blending ... glBegin(GL_QUADS); while (*str) { int char_codepoint = *str++; stb_fontchar *cd = &fontdata[char_codepoint - STB_SOMEFONT_FIRST_CHAR]; glTexCoord2f(cd->s0f, cd->t0f); glVertex2f(x + cd->x0f, y + cd->y0f); glTexCoord2f(cd->s1f, cd->t0f); glVertex2f(x + cd->x1f, y + cd->y0f); glTexCoord2f(cd->s1f, cd->t1f); glVertex2f(x + cd->x1f, y + cd->y1f); glTexCoord2f(cd->s0f, cd->t1f); glVertex2f(x + cd->x0f, y + cd->y1f); // if bilerping, in D3D9 you'll need a half-pixel offset here for 1:1 to behave correct x += cd->advance; } glEnd(); } */ #ifndef STB_FONTCHAR__TYPEDEF #define STB_FONTCHAR__TYPEDEF typedef struct { // coordinates if using integer positioning float s0,t0,s1,t1; signed short x0,y0,x1,y1; int advance_int; // coordinates if using floating positioning float s0f,t0f,s1f,t1f; float x0f,y0f,x1f,y1f; float advance; } stb_fontchar; #endif #define STB_FONT_times_25_usascii_BITMAP_WIDTH 256 #define STB_FONT_times_25_usascii_BITMAP_HEIGHT 84 #define STB_FONT_times_25_usascii_BITMAP_HEIGHT_POW2 128 #define STB_FONT_times_25_usascii_FIRST_CHAR 32 #define STB_FONT_times_25_usascii_NUM_CHARS 95 #define STB_FONT_times_25_usascii_LINE_SPACING 16 static unsigned int stb__times_25_usascii_pixels[]={ 0x44028013,0x05002602,0x266661cc,0xbcca9800,0x00c40001,0x10099998, 0x40062000,0x18006200,0x20102200,0x00010008,0x00080002,0x08180054, 0xc8001b88,0x4c0ae201,0x2200b985,0x447f601c,0x2a04fccc,0x12ea21bd, 0xfdded880,0x99df102e,0x44003605,0x02eecced,0xdabb8bf3,0x3f3b203f, 0x4341d804,0x2cc05ccd,0x5d9db100,0x26e75400,0x36e20680,0x44abdece, 0x90003ffb,0x5981e805,0x00ec00f8,0x904f80e6,0x70091007,0x109f507f, 0x3b6e207f,0x7f700cee,0xff709f50,0x20ff2254,0x1a037c4d,0x0fe6c8b3, 0xbd1000d8,0x1f88034c,0x2093017a,0x7dc40df9,0x0003fb85,0x426401d1, 0x36035459,0x44f80003,0x322002e8,0x5c09f500,0xf81fc44f,0x2a0fa6b2, 0x513ea04f,0x3e62ecdf,0x3ea0fcc6,0x43b8d102,0x1dc17a4f,0x7c47f500, 0x7d46e801,0x3e207201,0x2a16e00e,0x16e0003f,0x6c5987d8,0x0003ea07, 0x007b13e0,0x1ff10710,0x3e21fe80,0x3c967a83,0x3a007fc4,0x7d9be61f, 0xf83e47f8,0x21c89306,0x261f24f8,0x51fdc005,0x887f700d,0x3a21a05f, 0xfa85800f,0x0be60003,0x362cc3f4,0x400bd00f,0x2d49f009,0x43513730, 0xd805fc84,0x360fe26f,0x321ccb0f,0x26fb805f,0xf10e65f8,0x1fd06e8d, 0x266f2662,0x49f109e9,0x4000e86d,0x005d36fa,0x01ff03f9,0x00df5093, 0x018fea0a,0x0df06f80,0x981fc8b3,0x1feb803f,0x440f49f0,0x243f953d, 0x7dc027f4,0xf707f10f,0x07fd016b,0x27c1ff50,0x0ff07ee0,0x7e6547fa, 0x23cfcccc,0x05913a5e,0x1b9ff100,0xfd133326,0x3903fd01,0x4000bf90, 0x3fffabfa,0x26c1fa00,0x641ee2cc,0x1fe8802f,0x6c1e69f0,0xf06a37c3, 0x3ff5007f,0x3fe20fe2,0x01ffc05d,0x07f0ffcc,0x82fc84e8,0x24c680fe, 0x30fc47cc,0x37ec000b,0x07fc1fe4,0xe83417ec,0x3ea0003f,0x04ffc9ce, 0x0b503fb0,0xfd04c8b3,0x407f2003,0x8d90d94f,0xf10dc4f8,0x5ff1005f, 0x7fcc0fe2,0x05ff102f,0x1745ff10,0x3be60d50,0x1621be20,0x82f26077, 0x200d40e8,0x642ffcd8,0xfb07f885,0xff884987,0x0fea0002,0xf9001ff3, 0x4b30ae05,0x003fe039,0xb4f80fe4,0x7d41fa89,0x01ffc242,0x3f88ffc4, 0x413ff620,0xff8803ff,0x00d80761,0x3f6f3ff2,0x00e44a84,0xcae88b20, 0x3f27f505,0x3e207a0f,0x1c83fb07,0x0003ff88,0x0bfa0fea,0x6980ff20, 0x3e016d66,0x03f9000f,0x1761753e,0x3fa121f6,0x10ff9803,0xbffd007f, 0xf3009fd0,0x3880641f,0x8bf23500,0xfcccddca,0x44a803cc,0xf987f15e, 0x1d57fe24,0x1fb03ff0,0x013fe068,0xfc83fa80,0x303fc803,0x0552cc17, 0xfc8007f4,0x883a9f01,0x222fcc3f,0xa805fc83,0x200fe26f,0x7ec3fe8d, 0x1c6fa805,0xf8800330,0x26ba620f,0x40099e99,0xf8fe20e8,0x3ea0fe45, 0x17f405bf,0xd812a3f4,0x3ea0006f,0xd802fb83,0x5986982f,0x01fd81e4, 0x53e03f90,0xfb07ea2c,0xff980d87,0xf117ec00,0x1be2b007,0xfd801ff1, 0x20002001,0x498d01fb,0x7f307600,0x207fe3ec,0x7dc02ffd,0x00e45f83, 0x13003ff3,0x0fd83fa8,0x4d81fd80,0xb8354598,0x03f9002f,0x7f52553e, 0x1c87eb22,0xf9813ea0,0x2141fc45,0x13ee1f65,0x00004f98,0x5880fd40, 0x84a801dc,0xff17a4f8,0x83fff309,0x3f513e23,0x0efc8068,0x0fea0a60, 0x8374017e,0x7e45985f,0x9002fa81,0x3453e03f,0xf31bbff1,0xc81c5b57, 0x885e982f,0xd960e83f,0xf307f904,0xf109f309,0x80bea00d,0x4400e44a, 0x17c57a06,0x2e233fee,0xdacffeae,0x87d07d41,0x3df9003a,0x17ea0750, 0x7f1001d7,0xb1661fa0,0x4013a01f,0x749f01fc,0x3950b260,0x37a60398, 0xf102edbb,0xf9ac9d07,0x2f3ba601,0x0bf302ed,0x5dc40df3,0x1a15c00b, 0x3f300ec0,0xfec881d7,0x3ff624ff,0x7b7b503f,0x75400390,0x402dddff, 0x00decefb,0x1f601f70,0x4c0fd166,0x201f9007,0x80016a4f,0xfffb800d, 0x2e0fe201,0x00ccecfe,0x00400660,0x0004c011,0x28802813,0x9802b880, 0x0c006201,0x0cc00050,0x0004c400,0x985c80ba,0x0b2035c5,0x44f81f20, 0x01c8005c,0x403ffe60,0x166203f8,0x00000000,0x00000000,0x00000000, 0x00000000,0x3b800000,0x22cc0ec0,0x40744078,0x84f81760,0x03b1005c, 0x01df9100,0x009007f1,0x00000000,0x00000000,0x00000000,0x00000000, 0x00ee0000,0x2e166095,0xf9064403,0x55441d17,0x59b504fa,0x000cc981, 0x10e75c40,0x000355bf,0x00000000,0x00000000,0x00000000,0x00000000, 0x00cc0000,0x2048802a,0xdb31400a,0xaaaa8819,0x6e654401,0x800000bc, 0x2aaaa098,0x00000001,0x00000000,0x00000000,0x00000000,0x00000000, 0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000, 0x00000000,0x00000000,0x26001880,0x80070209,0x00100408,0x00600aa0, 0x2a80bb98,0x0002a000,0xa8044000,0xfffd8002,0x2001cc4f,0x26188000, 0x2effea80,0x417fffb3,0x3ae4ffc8,0xe980dfff,0x400205ff,0x2e201bdb, 0x5bddccdd,0x3ae200e4,0x442ccedd,0x801ccbcb,0xfb104fea,0x9ac805ff, 0x09fd52fe,0xed9bc880,0x5dff53cc,0xf9804fb8,0x002ff543,0x03ffffe6, 0x12e003fb,0xf9bfd980,0x7fc40cff,0x3605fe83,0x880bfd03,0x809d503f, 0xee8804e8,0x24c7e980,0x5fb03b20,0x803544c8,0xb57b04f9,0x896e01ff, 0x0013e64e,0x21aff8bb,0x006985fa,0x0bf307fd,0x39800d80,0x9801fa00, 0xffb9ccfc,0xfa84fc84,0x7d403e06,0x5c434c07,0x13e604fe,0x3e602f40, 0x05f10340,0x441f88ba,0x84f9802f,0xe81fe40b,0x0027cc05,0x81fd87f1, 0x401640fe,0x5f883fdc,0x00012600,0x800bfe60,0x07fcc5fa,0x3fe21fe6, 0x7fc05980,0xf980b201,0x6c01ba04,0x640c801f,0x2e05f702,0x0fe0bea2, 0x4c013e20,0x8809f03f,0x13ea004f,0x89f505f7,0x3faca806,0x36005f88, 0x00000bdf,0x5400dfbb,0xe82fd83f,0xc83fe82f,0xd02fdc02,0xf904f980, 0x00bf5003,0x2a093022,0x221881ef,0x403ea0ff,0x004f88a8,0x09f101f5, 0x80664f88,0xd036c6f8,0xd1012a1f,0xbf107f51,0x3fffe600,0x1002a01f, 0x54007fed,0xb83fc83f,0x437fc44f,0x80ff8806,0x427c404a,0x201516f9, 0x340003fc,0x803ffe88,0x80e99efc,0x4fdcadd8,0xcc883b00,0xf880ccef, 0x205ffe8c,0x405f32fb,0xd801b3fa,0xbf107f51,0x4c15ff44,0x2e22ffea, 0xb9e400fe,0x07f5005f,0x8ff105f7,0x1661ffbb,0x0f427ec0,0x3ee13e20, 0x40cfdcbd,0x266202fe,0x9815c199,0x6402efff,0x89d00eff,0x76c404fc, 0x8809f101,0x05fb0cef,0x4005666c,0x254059fe,0x4bf107f5,0xffb000e9, 0x2007f441,0x001ff10e,0x03fb07f5,0xfc8e8bfa,0x7cc00b24,0x7c4034c7, 0x7e43fd84,0x980bfe23,0x24c2effc,0x1bfff910,0x5c1fff40,0x3027cc0f, 0xf105fffb,0x545f8809,0x0003b03f,0x2c405ff7,0x57e20fea,0x7ec000d9, 0x95007ec2,0xfa803fd8,0x3ee06f84,0x69be6d15,0x591ff400,0xfd09f100, 0x3e26f881,0x03ff804f,0xfffd300d,0x9ff75b01,0x04f886f8,0x9f10ff90, 0x7cc4f880,0xaccdf984,0x407f802a,0x441fd40d,0x8000dadf,0x007e43fa, 0x806f981d,0x00fcc6fa,0x74771ff1,0x5400499f,0x7c401a6f,0xff80ff84, 0x3a017fe1,0x2005702f,0x526c6ffb,0x217e23ff,0x3f6004f8,0x22027c41, 0x4427c44f,0xeffffffd,0xeb813200,0xcefdcccc,0x03bf7e21,0x3f217c00, 0xddddf300,0xfa805ffd,0x801fcbdd,0x3f20eafd,0xff8002cc,0x9f1004a9, 0x3fb01fb0,0x7f403fe4,0x00a8b301,0x07e61ff5,0x21be69f5,0x3ea004f8, 0x22027c41,0x4827c44f,0x8136a666,0x3fff200e,0x23ffffff,0x005fadf8, 0x07e40f88,0x0bf702d8,0x0198bfa8,0xf317bea0,0x3ee000df,0x9f1000ed, 0x8d905f90,0x7f402ff8,0x40571a01,0xd01f71fd,0xf103fe2d,0x44354009, 0x227c404f,0x202d84f8,0x000b3039,0x57e20fea,0x264004fc,0x034407e4, 0x7d401ff1,0x0bfe0003,0x440013fa,0x3e2005ff,0x4f84f884,0x3a01ffb8, 0x5b8ae01f,0x17cc3fa0,0x887fd1e4,0x20f2005f,0x27c405f8,0x09f313e2, 0x03a2662c,0x441fd400,0x360bfa5f,0x320b912e,0x6403c80f,0x00fea05f, 0xfb80fc80,0x0bf60001,0xf704f880,0xfa807cc3,0x403fd01f,0x2a13ee58, 0x3e22f43f,0x2633fe60,0x2f209efd,0x3e603aa0,0x262fcc06,0xcdffd85f, 0x3fe61edb,0x3ea0002f,0x3e25f983,0x77ffdc1f,0xf307f603,0x01ffa803, 0x540009f5,0x8000f105,0x2fcc0079,0x01d97b50,0xcbceed88,0x2e6802df, 0x3fecdfdc,0x1bbbed88,0xfaefffa8,0x76ffec2e,0x59ffd704,0x517ffb50, 0xb7107ffb,0x0b72079d,0xa87f5000,0xff98bffd,0x1004c0bf,0x3ee3dff7, 0xffd703ef,0xbdedb89f,0x0c030000,0x7000c000,0x44039ffd,0x03330000, 0xa9810980,0x26003001,0x04c40310,0x00000000,0x00000000,0x00000000, 0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000, 0x00000000,0x00000000,0x00000000,0x00000000,0x3ff6a000,0x7f5c41df, 0x400b983f,0x18a62000,0x3bfff950,0x403fff22,0x743efeb8,0x1fffffff, 0xbdffffb3,0x6ffca839,0x477ffa00,0x0cdfffc9,0x67ffe4c0,0x077ffae2, 0xddffffb3,0xffc98079,0x3ff262df,0x3ffe22df,0x4fffffff,0x3bbfff26, 0xf933fffe,0xffddddff,0xffffd98f,0x000bdeef,0x1f3013fe,0x980ffc88, 0x6402dffc,0x404efcbe,0xdfd105fd,0x7cc3cc01,0x87eeeeef,0x7ff515fd, 0x3003ffb0,0x1bf209ff,0x6c17f200,0x527e401e,0xfc801dfb,0x221bee05, 0x01df701e,0x87b109f9,0x20d105fc,0x3ee60dfc,0x07fb002f,0x03f60788, 0x0fffaf7e,0x013ee274,0x7fd409f9,0x0b61a205,0x227dc26c,0x7fdc0ff9, 0x03ffd805,0xf7000bf7,0x7001d709,0x807ff09f,0x17ee04fb,0x0ffcc0a6, 0x89104fb8,0x202e05fb,0x7fd104fb,0x8805fb00,0x5503f606,0x0fb86fa8, 0x3f2027cc,0x0fff6a03,0x3f014344,0x7ff09f70,0x200ffbb8,0xf503fce9, 0x89f7000b,0x9f7000ea,0xfb80df90,0x2617ea04,0x5c09fd00,0xbf50204f, 0x04fb8040,0xfb00bfe6,0x32068805,0x2fe81c0f,0x027c437c,0xaca80ff2, 0x006882ff,0x427dc1ea,0x7e5dc4fe,0x0ff2b204,0x5c002fd4,0x8003aa4f, 0x06fc84fb,0xbf5027dc,0x2037e400,0xf50084fb,0x4fb8060b,0x36027ec0, 0x9034402f,0x87ee001f,0x04f885f8,0x29501fe4,0x03441ffb,0x13ee0990, 0x8bb83ff1,0xf96880ff,0x0017ea07,0x0075d3ee,0xff113ee0,0x204fb807, 0xff3005fa,0x484fb803,0x8160bf50,0x3fd404fb,0xd100bf60,0xc8007e40, 0x7c437cc7,0x501fe404,0xd1077ec9,0xfb80fc00,0x9dc37e44,0xf93c84fc, 0x0017ea07,0x003ef3ee,0xfd893ee0,0x027dc00c,0xff100bf5,0x33bf7007, 0x37ea0b93,0x205ca999,0x7fcc04fb,0x100bf600,0x8007e40d,0x207fc43e, 0x1fe404f8,0x25fe8950,0x40f50068,0xdfebbefb,0x1ff33b80,0x207f90f8, 0xfb8005fa,0xb8003ffe,0x00dfedef,0xddddff70,0xb00bfddd,0x3bee00bf, 0xf505edcc,0x0bd9999d,0x3e2027dc,0x00bf602f,0x007e40d1,0x43fe82d4, 0x1fe404f9,0x4ff88950,0x813200d1,0x00998cfb,0x2e3fd8ee,0x7d40ff24, 0xacfb8005,0x7dc003ff,0x5c00df74,0x017ea04f,0x2e001ff5,0xfa82444f, 0x3ee05885,0x00ffcc04,0x068805f9,0x03a003f2,0x65d77fd4,0x01fe404f, 0x15ff3095,0xb807e00d,0x98ee004f,0x3fc83a6f,0x7000bf50,0x00ffea9f, 0x13f64fb8,0xf5027dc0,0x017fc40b,0x20509f70,0x5c0505fa,0x07fd404f, 0x58807f90,0x59003f20,0x8bffd980,0x01fe404f,0x2bfea095,0x5c079806, 0xd0ee004f,0x3fc8b55f,0x7000bf50,0x01ffd49f,0x3fa24fb8,0x204fb802, 0x17f605fa,0x4009f700,0xfb8005fa,0x2037e404,0x025404fb,0x01dc01f9, 0x2027c430,0x812a01fc,0x4c806ffc,0x70027dc0,0x41eefa87,0x0bf503fc, 0x227dc0a8,0xfb804ffa,0x2007fcc4,0x17ea04fb,0x170077dc,0x2a004fb8, 0x2e05405f,0x07fe604f,0x1e80ff10,0x25403f20,0x509f1000,0x4a803f21, 0x7c037ec0,0x0027dc01,0x90bfd077,0x017ea07f,0xf509f70b,0x84fb809f, 0x3ee00efb,0x2617ee04,0x21a201ff,0x3ea004fb,0x3ee16205,0x009fd104, 0x0f6217ea,0x09501f90,0x13e2002a,0x701369f7,0x406e880d,0x06fc8079, 0x0bee1320,0x37e413f6,0x7e41f4c4,0x01bff905,0x2ff41bf2,0x7e40bf90, 0x2604fe86,0x005fc85d,0x1ec41bee,0x7fd427e4,0x6ffdc002,0xfd803dec, 0x66667d41,0xbf3006ed,0x204cff88,0x201cffc9,0x30264069,0x405bfff9, 0x341cffc9,0x473fff66,0xffffffc9,0x3260ffff,0x3a61cfff,0x931dffff, 0xf885bfff,0xff930cff,0x7fe4c59f,0xffff72cf,0x7fffffff,0x167ffe4c, 0xddfff730,0x4c1fffdd,0xeeeffffc,0x260000bc,0x3fee0019,0xfffff52e, 0xb5007fff,0x009817dd,0x54008000,0x00000000,0x00000000,0x00000000, 0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000, 0x00000000,0x00000000,0x00000000,0x00000000,0x6cc04000,0xdeeeffff, 0xfffff881,0x0fffffff,0x3bffffb3,0x516ffecc,0x883bfffd,0xf913effc, 0x00c47dff,0x02a20014,0x013300c4,0xa8803510,0x00530088,0x00000000, 0x43118800,0x8620003b,0x00029819,0x27ec0910,0x4c1bfb51,0xa89fe21e, 0x83ffcc0f,0xffd103f8,0xfb80de80,0x2200ff87,0xd79d1005,0x6c1fe81b, 0xb103fcad,0xd885ff79,0x74c1fdab,0x3ea0cfcb,0xdffb88df,0xfea9bee1, 0xa8fee22f,0x13faa4fd,0x7ff39fb3,0x40033b22,0xffe8dfd9,0x0fffd88f, 0xfcccdee8,0xfb81363f,0x14c7fd04,0x202e1fe2,0x04c82ffa,0xf8817fcc, 0xdb0df500,0x4402c401,0xd913ea2f,0x1fd07dc1,0x22fd87b0,0x1f10f43b, 0x0fee27d4,0x986885f9,0xfa85986f,0x2e227d44,0xb81dabdf,0x7d4401de, 0x199f90ce,0x2e1613ee,0xb813f25f,0x44df504f,0x0443fc40,0x16a0ffb8, 0x2c837dc0,0x4001be60,0xd87c8058,0x7e47d805,0x3e207e40,0x643517a5, 0x46f86f84,0xd815c4f9,0x7cc0e40f,0x7c427cc4,0x0bb6a006,0x37c45f88, 0x3e61437c,0x99dfb50e,0x3ea09f70,0x003fc407,0x00e9afec,0x0b313fa0, 0x10006f98,0x000bf00b,0xd07faa08,0x7e43fa0d,0xddddf01e,0x1fc83ddd, 0x20683fea,0xf982c4fa,0x7c427cc4,0xbec98004,0x37c2fc40,0x3fa203f4, 0xf7027c41,0x1013f609,0xff1000ff,0xf98003d7,0xf3003a1f,0x0162000d, 0x70000bf1,0x7c43f95b,0x3625fb06,0x0fe20dff,0x2f64f980,0xfe80933f, 0x13e60550,0x09f109f3,0x107f4400,0xfd0df0bf,0xf883fd80,0x4c37ee04, 0x4400dfda,0xff50007f,0x5bee0007,0x06f9803c,0xffffffc8,0xf11fffff, 0x1f44000f,0x07fc43f9,0x3fea17e4,0x8009f11f,0x65be937e,0x059fdc00, 0x09f313e6,0x710009f1,0x85f8819d,0x2e07e86f,0x409f105f,0xffedeffb, 0x07f8800e,0x0017fa00,0x3006dfe8,0x162000df,0x02a07fe0,0x41fc8dd0, 0x30fc82fd,0x1ff2fe44,0xb5f70130,0x20167f21,0x26049ef8,0x4427cc4f, 0x3b26004f,0x3e17e203,0xdf307e86,0xb813e201,0x04ffa84f,0x98003fc4, 0x30002ffe,0x3e6003ff,0x00b10006,0x40388bfb,0x20fe46f8,0x165d84fb, 0x41efc9ba,0x4c9df104,0xdf9002ef,0x2a2fc401,0x804f884f,0xf8801dda, 0x87e86f85,0xf1381fe8,0x9827dc09,0x1fe201ff,0x3ea3a200,0x1ff0000f, 0xf11be600,0x402c403f,0x0fcbeff8,0x35fd07ec,0x74477fdb,0x3e83a61f, 0xbfff1174,0x0fec05f9,0x5f9801fa,0xcb8aff80,0x82fcc1ef,0x2000ceb8, 0xf86f85f9,0x2a83fd87,0x27dc09f1,0x7c409fd0,0x361e8007,0x1ff0005f, 0xf31be600,0x802c409f,0xe81dffe9,0x27bfaa1f,0x7ec40ef9,0x77f41ddc, 0xffe984cb,0x5c2d402d,0x40174004,0xdf99fffa,0x033ffaa2,0xd9800177, 0xffd98bff,0x0dffc99c,0xdddddff5,0xb817e25f,0x813fa04f,0x1e4007f8, 0x2000bfe2,0xdf3000ff,0x2c40b310,0x08802200,0x0c400810,0x22006210, 0x02202000,0x0c400300,0x00000031,0x00000000,0x2e05cf7c,0x03ff504f, 0xb7003fc4,0x0003fee0,0x3ea001ff,0x02805706,0x00000000,0x00000000, 0x00000000,0x00000000,0x40000000,0x4fc81efc,0x201ff5c4,0xfb800ff9, 0x003bfe00,0xb8017fc4,0x0003a87f,0x00198620,0x1c880000,0x00200170, 0x02044083,0x6eedc351,0xdddddddd,0x110054c1,0x88888880,0x77408888, 0x00003eee,0x3fff2602,0x01cdeeef,0x0fbffee2,0x20efff54,0x04ffffc8, 0x05f7ff5c,0x2dfffc88,0x26000033,0x5ffe8cfd,0xd34ffd98,0xed98007f, 0x3007f102,0xfa9fd40d,0x25fb9fe4,0x266627e8,0x19999999,0x056feee4, 0x3a25f88e,0xeeeeeeee,0x3bbba2ee,0x0000003e,0x00000000,0x00000000, 0x44000000,0xfd88cefb,0x3a27fd02,0x077aa001,0x6457c722,0x2e079d01, 0x3fc9f74f,0x0fc43ff9,0xb50e2000,0x7cc7b7bf,0x00000006,0x00000000, 0x00000000,0x00000000,0x22fcc000,0x1ff103fa,0x9d710059,0x6d7fc401, 0xd3b83fe9,0x3ea7f501,0x85731ba3,0x11111139,0x0c111111,0x01037710, 0x00000000,0x00000000,0x00000000,0x00000000,0xf989f100,0x013bea04, 0x44005d93,0x880bceda,0x47e216a6,0x161762f8,0xdddddb8c,0x01dddddd, 0x00000000,0x00000000,0x00000000,0x00000000,0xf1000000,0x6c04f889, 0x013ee03f,0x3377b260,0x40ec2d81,0x43c87e0f,0x0000002b,0x00000000, 0x00000000,0x00000000,0x00000000,0xf1000000,0x6c04f889,0x3b2600fe, 0x8ef9800b,0x1663fd8d,0xa8b161a2,0x000000a2,0x00000000,0x00000000, 0x00000000,0x00000000,0x10000000,0x204f889f,0x8806f9ac,0x2e200ceb, 0x74372f88,0x04087700,0x00000000,0x00000000,0x00000000,0x00000000, 0x00000000,0x22000000,0xa827c44f,0xa800ff24,0x1fc401de,0x000e014c, 0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0xf3000000, 0x6985f98b,0x20017fc4,0x02a02ed9,0x00000000,0x00000000,0x00000000, 0x00000000,0x00000000,0x00000000,0x3ffaa000,0x0bffea8b,0x7fd45ff5, 0x1c88003f,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000, 0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000, 0x00000000, }; static signed short stb__times_25_usascii_x[95]={ 0,2,1,0,1,0,0,0,0,0,1,0,1,0, 1,0,0,2,0,0,0,1,0,0,1,0,1,1,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0, 0,0,-1,0,0,0,0,1,0,0,0,0,0,0,0,1,0,0,0,-1,1,0,-1,0,0,0,0,0,0,0, -2,0,0,0,0,0,-1,0,0,1,0,0,0,0,0,0,0,3,1,1,0, }; static signed short stb__times_25_usascii_y[95]={ 20,4,4,4,3,4,4,4,4,4,4,6,17,14, 17,4,4,4,4,4,4,5,4,5,4,4,9,9,7,10,7,4,4,4,5,4,5,5,5,4,5,5,5,5, 5,5,5,4,5,4,5,4,5,5,5,5,5,5,5,4,4,4,4,23,4,9,4,9,4,9,4,9,4,4, 4,4,4,9,9,9,9,9,9,9,6,9,9,9,9,9,9,4,4,4,12, }; static unsigned short stb__times_25_usascii_w[95]={ 0,4,7,11,10,19,17,4,8,7,9,13,4,7, 4,7,11,7,11,10,11,9,11,11,9,11,4,4,13,13,13,9,20,17,14,15,16,14,12,16,16,7,9,17, 14,20,17,16,12,16,16,11,14,17,17,22,17,16,14,6,7,6,11,13,4,10,12,10,12,10,10,11,12,6, 7,12,6,18,12,11,12,12,8,7,7,12,12,17,12,12,10,7,2,8,13, }; static unsigned short stb__times_25_usascii_h[95]={ 0,17,8,17,19,17,17,8,21,21,10,13,7,2, 4,17,17,16,16,17,16,16,17,16,17,17,12,15,11,5,11,17,21,16,15,17,15,15,15,17,15,15,16,15, 15,15,16,17,15,21,15,17,15,16,16,16,15,15,15,21,17,21,9,2,5,12,17,12,17,12,16,16,16,16, 21,16,16,11,11,12,16,16,11,12,15,12,12,12,11,16,11,21,21,21,4, }; static unsigned short stb__times_25_usascii_s[95]={ 252,126,163,153,98,165,185,171,29,1,141, 87,176,233,214,215,203,247,26,73,133,158,1,79,50,141,112,82,127,186,212, 131,53,175,9,223,235,220,207,13,175,74,51,140,125,104,61,109,91,74,158, 38,24,1,229,206,39,57,192,91,30,46,151,219,181,117,239,101,60,148,84, 108,95,168,38,145,19,226,101,128,193,38,203,140,1,190,177,159,114,120,245, 21,18,9,200, }; static unsigned short stb__times_25_usascii_t[95]={ 1,1,71,1,1,1,1,71,1,1,71, 58,71,71,71,1,1,23,41,23,23,23,23,41,23,1,58,58,71,71,58, 1,1,23,58,1,41,41,41,23,41,58,41,41,41,41,41,1,41,1,41, 23,58,41,23,23,58,58,41,1,23,1,71,71,71,58,1,58,23,58,23, 23,23,23,1,23,41,58,71,58,23,41,58,58,58,58,58,58,71,23,58, 1,1,1,71, }; static unsigned short stb__times_25_usascii_a[95]={ 90,120,147,181,181,301,281,65, 120,120,181,204,90,120,90,100,181,181,181,181,181,181,181,181, 181,181,100,100,204,204,204,160,333,261,241,241,261,221,201,261, 261,120,141,261,221,321,261,261,201,261,241,201,221,261,261,341, 261,261,221,120,100,120,169,181,120,160,181,160,181,160,120,181, 181,100,100,181,100,281,181,181,181,181,120,141,100,181,181,261, 181,181,160,173,72,173,195, }; // Call this function with // font: NULL or array length // data: NULL or specified size // height: STB_FONT_times_25_usascii_BITMAP_HEIGHT or STB_FONT_times_25_usascii_BITMAP_HEIGHT_POW2 // return value: spacing between lines static void stb_font_times_25_usascii(stb_fontchar font[STB_FONT_times_25_usascii_NUM_CHARS], unsigned char data[STB_FONT_times_25_usascii_BITMAP_HEIGHT][STB_FONT_times_25_usascii_BITMAP_WIDTH], int height) { int i,j; if (data != 0) { unsigned int *bits = stb__times_25_usascii_pixels; unsigned int bitpack = *bits++, numbits = 32; for (i=0; i < STB_FONT_times_25_usascii_BITMAP_WIDTH*height; ++i) data[0][i] = 0; // zero entire bitmap for (j=1; j < STB_FONT_times_25_usascii_BITMAP_HEIGHT-1; ++j) { for (i=1; i < STB_FONT_times_25_usascii_BITMAP_WIDTH-1; ++i) { unsigned int value; if (numbits==0) bitpack = *bits++, numbits=32; value = bitpack & 1; bitpack >>= 1, --numbits; if (value) { if (numbits < 3) bitpack = *bits++, numbits = 32; data[j][i] = (bitpack & 7) * 0x20 + 0x1f; bitpack >>= 3, numbits -= 3; } else { data[j][i] = 0; } } } } // build font description if (font != 0) { float recip_width = 1.0f / STB_FONT_times_25_usascii_BITMAP_WIDTH; float recip_height = 1.0f / height; for (i=0; i < STB_FONT_times_25_usascii_NUM_CHARS; ++i) { // pad characters so they bilerp from empty space around each character font[i].s0 = (stb__times_25_usascii_s[i]) * recip_width; font[i].t0 = (stb__times_25_usascii_t[i]) * recip_height; font[i].s1 = (stb__times_25_usascii_s[i] + stb__times_25_usascii_w[i]) * recip_width; font[i].t1 = (stb__times_25_usascii_t[i] + stb__times_25_usascii_h[i]) * recip_height; font[i].x0 = stb__times_25_usascii_x[i]; font[i].y0 = stb__times_25_usascii_y[i]; font[i].x1 = stb__times_25_usascii_x[i] + stb__times_25_usascii_w[i]; font[i].y1 = stb__times_25_usascii_y[i] + stb__times_25_usascii_h[i]; font[i].advance_int = (stb__times_25_usascii_a[i]+8)>>4; font[i].s0f = (stb__times_25_usascii_s[i] - 0.5f) * recip_width; font[i].t0f = (stb__times_25_usascii_t[i] - 0.5f) * recip_height; font[i].s1f = (stb__times_25_usascii_s[i] + stb__times_25_usascii_w[i] + 0.5f) * recip_width; font[i].t1f = (stb__times_25_usascii_t[i] + stb__times_25_usascii_h[i] + 0.5f) * recip_height; font[i].x0f = stb__times_25_usascii_x[i] - 0.5f; font[i].y0f = stb__times_25_usascii_y[i] - 0.5f; font[i].x1f = stb__times_25_usascii_x[i] + stb__times_25_usascii_w[i] + 0.5f; font[i].y1f = stb__times_25_usascii_y[i] + stb__times_25_usascii_h[i] + 0.5f; font[i].advance = stb__times_25_usascii_a[i]/16.0f; } } } #ifndef STB_SOMEFONT_CREATE #define STB_SOMEFONT_CREATE stb_font_times_25_usascii #define STB_SOMEFONT_BITMAP_WIDTH STB_FONT_times_25_usascii_BITMAP_WIDTH #define STB_SOMEFONT_BITMAP_HEIGHT STB_FONT_times_25_usascii_BITMAP_HEIGHT #define STB_SOMEFONT_BITMAP_HEIGHT_POW2 STB_FONT_times_25_usascii_BITMAP_HEIGHT_POW2 #define STB_SOMEFONT_FIRST_CHAR STB_FONT_times_25_usascii_FIRST_CHAR #define STB_SOMEFONT_NUM_CHARS STB_FONT_times_25_usascii_NUM_CHARS #define STB_SOMEFONT_LINE_SPACING STB_FONT_times_25_usascii_LINE_SPACING #endif
61.378641
117
0.762971
stetre
2751e269435c1bc0e48312261d13497f3df556a3
110
cpp
C++
openexr-c/abigen/imf_testfile.cpp
vfx-rs/openexr-bind
ee4fd6010beedb0247737a39ee61ffb87c586448
[ "BSD-3-Clause" ]
7
2021-06-04T20:59:16.000Z
2022-02-11T01:00:42.000Z
openexr-c/abigen/imf_testfile.cpp
vfx-rs/openexr-bind
ee4fd6010beedb0247737a39ee61ffb87c586448
[ "BSD-3-Clause" ]
35
2021-05-14T04:28:22.000Z
2021-12-30T12:08:40.000Z
openexr-c/abigen/imf_testfile.cpp
vfx-rs/openexr-bind
ee4fd6010beedb0247737a39ee61ffb87c586448
[ "BSD-3-Clause" ]
5
2021-05-15T04:02:56.000Z
2021-07-02T05:38:01.000Z
#include <OpenEXR/ImfTestFile.h> #include "imf_testfile.hpp" void abi_gen_imf_testfile(std::ostream& os) { }
18.333333
45
0.763636
vfx-rs
2755f82798cd92f4a023afcae3c6265e63fa4729
13,033
cpp
C++
TwoDacConsistencyLogger/WasapiInput.cpp
AVLatency/Latency-Measurement
a85b8d0dbfa7eb79a8858936f0313a272726f35c
[ "MIT" ]
4
2022-02-17T20:09:30.000Z
2022-03-28T22:34:43.000Z
TwoDacConsistencyLogger/WasapiInput.cpp
AVLatency/Latency-Measurement
a85b8d0dbfa7eb79a8858936f0313a272726f35c
[ "MIT" ]
2
2022-02-17T20:16:22.000Z
2022-02-18T15:42:28.000Z
TwoDacConsistencyLogger/WasapiInput.cpp
AVLatency/Latency-Measurement
a85b8d0dbfa7eb79a8858936f0313a272726f35c
[ "MIT" ]
1
2022-03-24T12:10:38.000Z
2022-03-24T12:10:38.000Z
#include "WasapiInput.h" #include <mmdeviceapi.h> #include <cmath> #include <cstdio> #include <Functiondiscoverykeys_devpkey.h> #include <comdef.h> #include <format> // REFERENCE_TIME time units per second and per millisecond #define REFTIMES_PER_SEC 10000000 #define REFTIMES_PER_MILLISEC 10000 #define EXIT_ON_ERROR(hres) \ if (FAILED(hres)) { goto Exit; } #define SAFE_RELEASE(punk) \ if ((punk) != NULL) \ { (punk)->Release(); (punk) = NULL; } const IID IID_IAudioCaptureClient = __uuidof(IAudioCaptureClient); WasapiInput::WasapiInput(const GeneratedSamples& config) { testWaveDurationInSeconds = config.TestWaveDurationInSeconds(); } WasapiInput::~WasapiInput() { if (recordedAudio != NULL) { delete[] recordedAudio; } } UINT16 WasapiInput::GetFormatID() { return EXTRACT_WAVEFORMATEX_ID(&waveFormat.SubFormat); } void WasapiInput::StartRecording() { const CLSID CLSID_MMDeviceEnumerator = __uuidof(MMDeviceEnumerator); const IID IID_IMMDeviceEnumerator = __uuidof(IMMDeviceEnumerator); const IID IID_IAudioClient = __uuidof(IAudioClient); HRESULT hr; REFERENCE_TIME hnsRequestedDuration = REFTIMES_PER_SEC; REFERENCE_TIME hnsActualDuration; UINT32 bufferFrameCount; UINT32 numFramesAvailable; IMMDeviceEnumerator* pEnumerator = NULL; IMMDevice* pDevice = NULL; IAudioClient* pAudioClient = NULL; IAudioCaptureClient* pCaptureClient = NULL; WAVEFORMATEX* pWaveFormat = NULL; UINT32 packetLength = 0; BOOL bDone = FALSE; BYTE* pData; DWORD flags; bool pastInitialDiscontinuity = false; IPropertyStore* pProps = NULL; LPWSTR pwszID = NULL; hr = CoInitialize(NULL); hr = CoCreateInstance( CLSID_MMDeviceEnumerator, NULL, CLSCTX_ALL, IID_IMMDeviceEnumerator, (void**)&pEnumerator); EXIT_ON_ERROR(hr) hr = pEnumerator->GetDefaultAudioEndpoint( eCapture, eConsole, &pDevice); EXIT_ON_ERROR(hr) // Get the endpoint ID string. hr = pDevice->GetId(&pwszID); EXIT_ON_ERROR(hr) hr = pDevice->OpenPropertyStore(STGM_READ, &pProps); EXIT_ON_ERROR(hr) PROPVARIANT varName; // Initialize container for property value. PropVariantInit(&varName); // Get the endpoint's friendly-name property. hr = pProps->GetValue(PKEY_Device_FriendlyName, &varName); EXIT_ON_ERROR(hr) DeviceName = std::format("{} ({})", (char*)_bstr_t(varName.pwszVal), (char*)_bstr_t(pwszID)); // endpoint friendly name and endpoint ID. CoTaskMemFree(pwszID); pwszID = NULL; PropVariantClear(&varName); SAFE_RELEASE(pProps) hr = pDevice->Activate( IID_IAudioClient, CLSCTX_ALL, NULL, (void**)&pAudioClient); EXIT_ON_ERROR(hr) // TODO: make this exclusive mode so I can have the software select the highest sample rate(??) // Or just show the user what their current sample rate is and tell them to change it in the windows control panel // if they want more options. hr = pAudioClient->GetMixFormat(&pWaveFormat); EXIT_ON_ERROR(hr) hr = pAudioClient->Initialize( AUDCLNT_SHAREMODE_SHARED, 0, hnsRequestedDuration, 0, pWaveFormat, NULL); EXIT_ON_ERROR(hr) // Get the size of the allocated buffer. hr = pAudioClient->GetBufferSize(&bufferFrameCount); EXIT_ON_ERROR(hr) hr = pAudioClient->GetService( IID_IAudioCaptureClient, (void**)&pCaptureClient); EXIT_ON_ERROR(hr) // Notify the audio sink which format to use. hr = SetFormat(pWaveFormat); EXIT_ON_ERROR(hr) // Calculate the actual duration of the allocated buffer. hnsActualDuration = (double)REFTIMES_PER_SEC * bufferFrameCount / pWaveFormat->nSamplesPerSec; hr = pAudioClient->Start(); // Start recording. EXIT_ON_ERROR(hr) // Each loop fills about half of the shared buffer. while (bDone == FALSE) { // Sleep for half the buffer duration. Sleep(hnsActualDuration / REFTIMES_PER_MILLISEC / 2); hr = pCaptureClient->GetNextPacketSize(&packetLength); EXIT_ON_ERROR(hr) while (packetLength != 0) { // Get the available data in the shared buffer. hr = pCaptureClient->GetBuffer( &pData, &numFramesAvailable, &flags, NULL, NULL); // TODO: pu64QPCPosition parameter could be used for Bluetooth latency testing! EXIT_ON_ERROR(hr) if (flags & AUDCLNT_BUFFERFLAGS_SILENT) { pData = NULL; // Tell CopyData to write silence. } if (flags & AUDCLNT_BUFFERFLAGS_DATA_DISCONTINUITY) { if (pastInitialDiscontinuity) { ThrowAwayRecording(); } } else { pastInitialDiscontinuity = true; } // Copy the available capture data to the audio sink. hr = CopyData( pData, numFramesAvailable, &bDone); EXIT_ON_ERROR(hr) hr = pCaptureClient->ReleaseBuffer(numFramesAvailable); EXIT_ON_ERROR(hr) hr = pCaptureClient->GetNextPacketSize(&packetLength); EXIT_ON_ERROR(hr) } } hr = pAudioClient->Stop(); // Stop recording. EXIT_ON_ERROR(hr) Exit: CoUninitialize(); CoTaskMemFree(pWaveFormat); SAFE_RELEASE(pEnumerator) SAFE_RELEASE(pDevice) SAFE_RELEASE(pAudioClient) SAFE_RELEASE(pCaptureClient) } HRESULT WasapiInput::SetFormat(WAVEFORMATEX* wfex) { //TODO: a whole bunch of validation of this, as explained here: https://matthewvaneerde.wordpress.com/2011/09/09/how-to-validate-and-log-a-waveformatex/ // Documentation here: https://docs.microsoft.com/en-us/windows/win32/api/mmreg/ns-mmreg-waveformatextensible // Example here: https://gist.github.com/mhamilt/859e57f064e4d5b2bb8e78ae55439d70#file-wasapi-console-cpp-L64 if (wfex->wFormatTag == WAVE_FORMAT_EXTENSIBLE) { //typedef struct { // WAVEFORMATEX Format; // union { // WORD wValidBitsPerSample; /* bits of precision */ // WORD wSamplesPerBlock; /* valid if wBitsPerSample==0 */ // WORD wReserved; /* If neither applies, set to zero. */ // } Samples; // DWORD dwChannelMask; /* which channels are */ // GUID SubFormat; waveFormat = *reinterpret_cast<const WAVEFORMATEXTENSIBLE*>(wfex); } else { //typedef struct tWAVEFORMATEX //{ // WORD wFormatTag; /* waveFormat type */ // WORD nChannels; /* number of channels (i.e. mono, stereo...) */ // DWORD nSamplesPerSec; /* sample rate */ // DWORD nAvgBytesPerSec; /* for buffer estimation */ // WORD nBlockAlign; /* block size of data */ // WORD wBitsPerSample; /* Number of bits per sample of mono data */ // WORD cbSize; /* The count in bytes of the size of // extra information (after cbSize) */ // This is just an old-style WAVEFORMATEX struct, so convert it to the new WAVEFORMATEXTENSIBLE waveFormat: waveFormat.Format = *wfex; waveFormat.Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE; waveFormat.Samples.wReserved = 0; waveFormat.Samples.wSamplesPerBlock = 0; waveFormat.Samples.wValidBitsPerSample = waveFormat.Format.wBitsPerSample; waveFormat.dwChannelMask = 0; INIT_WAVEFORMATEX_GUID(&waveFormat.SubFormat, wfex->wFormatTag); } #ifdef _DEBUG printf("TestRecordingSink::SetFormat\nFormat type: 0x%.4x\nChannels: %u\nSamples Per Sec: %u\nAvg Bytes Per Sec: %u\nBlock Align: %u\nBits Per Sample: %u\ncbSize: %u\nValid Bits Per Sample: %u\nSamples Per Block: %u\nChannel Mask: 0x%.8x\n", GetFormatID(), waveFormat.Format.nChannels, waveFormat.Format.nSamplesPerSec, waveFormat.Format.nAvgBytesPerSec, waveFormat.Format.nBlockAlign, waveFormat.Format.wBitsPerSample, waveFormat.Format.cbSize, waveFormat.Samples.wValidBitsPerSample, waveFormat.Samples.wSamplesPerBlock, waveFormat.dwChannelMask); #endif if (waveFormat.Samples.wValidBitsPerSample != waveFormat.Format.wBitsPerSample) { return -1; // Not supported yet! } else if (waveFormat.Format.nChannels != 2) { return -1; // Not supported! } recordedAudioLength = recordedAudioNumChannels * round(waveFormat.Format.nSamplesPerSec * testWaveDurationInSeconds); recordedAudio = new float[recordedAudioLength]; return S_OK; } HRESULT WasapiInput::CopyData(BYTE* pData, UINT32 bufferFrameCount, BOOL* bDone) { if (FinishedRecording()) { *bDone = true; return S_OK; } WORD numChannels = waveFormat.Format.nChannels; if (GetFormatID() == WAVE_FORMAT_IEEE_FLOAT && waveFormat.Format.wBitsPerSample == 32) { float* castData = (float*)pData; for (UINT32 i = 0; i < bufferFrameCount * numChannels; i += numChannels) { for (int c = 0; c < numChannels; c++) { recordedAudio[recordedAudioIndex] = pData == NULL ? 0.0f : castData[i + c]; recordedAudioIndex++; if (FinishedRecording()) { *bDone = true; return S_OK; } } } return S_OK; } else if (GetFormatID() == WAVE_FORMAT_PCM && waveFormat.Format.wBitsPerSample == 16) { // This is confirmed to be Little Endian on my computer! // (settings bytes manually as big endian results in garbage, but setting // them little endian manually works perfectly) INT16* castData = (INT16*)pData; for (UINT32 i = 0; i < bufferFrameCount * numChannels; i += numChannels) { for (int c = 0; c < numChannels; c++) { recordedAudio[recordedAudioIndex] = pData == NULL ? 0.0f : castData[i + c] / (float)SHRT_MIN * -1.0f; recordedAudioIndex++; if (FinishedRecording()) { *bDone = true; return S_OK; } } } return S_OK; } else if (GetFormatID() == WAVE_FORMAT_PCM && waveFormat.Format.wBitsPerSample == 24) { //// nBlockAlign and bufferFrameCount are only used for the buffer size! //int dataLength = bufferFrameCount * waveFormat.Format.nBlockAlign; //// Actual frame size is 32 bits for 24 bit audio: //int bytesPerSampleWithPadding = 32 / 8; //int bytesPerFrame = bytesPerSampleWithPadding * waveFormat.Format.nChannels; //for (int i = 0; i < dataLength; i += bytesPerFrame) //{ // int thirtyTwoBit = (int)round(sin(1) * INT24_MAX); // for (int c = 0; c < numChannels; c++) // { // int channelOffset = c * bytesPerSampleWithPadding; // pData[i + channelOffset + 0] = 0; // padding // pData[i + channelOffset + 1] = thirtyTwoBit; // little endian, least significant first // pData[i + channelOffset + 2] = thirtyTwoBit >> 8; // pData[i + channelOffset + 3] = thirtyTwoBit >> 16; // pData[i + channelOffset + 3] |= (thirtyTwoBit >> 31) << 7; // negative bit // } //} //return S_OK; return -1; // TODO: write this when I'm making something public facing. } else if (GetFormatID() == WAVE_FORMAT_PCM && waveFormat.Format.wBitsPerSample == 32) { INT32* castData = (INT32*)pData; for (UINT32 i = 0; i < bufferFrameCount * numChannels; i += numChannels) { for (int c = 0; c < numChannels; c++) { recordedAudio[recordedAudioIndex] = pData == NULL ? 0.0f : castData[i + c] / (float)INT_MIN * -1.0f; recordedAudioIndex++; if (FinishedRecording()) { *bDone = true; return S_OK; } } } return S_OK; } else { return -1; } } bool WasapiInput::FinishedRecording() { return recordedAudioIndex >= recordedAudioLength; } void WasapiInput::ThrowAwayRecording() { // Write garbage to the recording and set it to be completed RecordingFailed = true; bool high = true; for (int i = 0; i < recordedAudioLength;) { recordedAudio[i] = high ? 1 : -1; i++; if (recordedAudioLength % 2 == 0) { recordedAudio[i] = high ? 1 : -1; i++; } high = !high; } recordedAudioIndex = recordedAudioLength; }
33.332481
245
0.609069
AVLatency
27560e816977bb293bda88293cf0d2ff992af5e0
25,229
cpp
C++
Src/Hardware/MCU/STM32F4xx/Src/USB_MCU.cpp
ThBreuer/EmbSysLib
650122100e876a819b1b4e6d52aed24e5504e86e
[ "MIT" ]
1
2020-01-11T09:53:11.000Z
2020-01-11T09:53:11.000Z
Src/Hardware/MCU/STM32F4xx/Src/USB_MCU.cpp
ThBreuer/EmbSysLib
650122100e876a819b1b4e6d52aed24e5504e86e
[ "MIT" ]
null
null
null
Src/Hardware/MCU/STM32F4xx/Src/USB_MCU.cpp
ThBreuer/EmbSysLib
650122100e876a819b1b4e6d52aed24e5504e86e
[ "MIT" ]
1
2021-07-20T05:06:11.000Z
2021-07-20T05:06:11.000Z
//******************************************************************* /*! \file USB_MCU.cpp \author Thomas Breuer (Bonn-Rhein-Sieg University of Applied Sciences) \date 23.03.2016 This file is released under the MIT License. This implementaion is partially derived from STM32CubeF4 (see: http://www.st.com/web/en/catalog/tools/PF259243) */ //******************************************************************* #include "USB_MCU.h" //******************************************************************* #define USB_PCGCCTL *(__IO DWORD *)((DWORD)USB_OTG_FS + USB_OTG_PCGCCTL_BASE) #define USB_DEVICE ((USB_OTG_DeviceTypeDef *)((DWORD)USB_OTG_FS + USB_OTG_DEVICE_BASE )) //******************************************************************* // // cHwUSB::EndpointIN // //******************************************************************* //------------------------------------------------------------------- cHwUSB_0::EndpointIN::EndpointIN( void ) { } //------------------------------------------------------------------- void cHwUSB_0::EndpointIN::init( BYTE numIn ) { num = numIn; inep = ((USB_OTG_INEndpointTypeDef *)((DWORD)USB_OTG_FS + USB_OTG_IN_ENDPOINT_BASE + (num)*USB_OTG_EP_REG_SIZE)); fifo = (__IO DWORD *)((DWORD)USB_OTG_FS + USB_OTG_FIFO_BASE + (num)*USB_OTG_FIFO_SIZE ); } //------------------------------------------------------------------- void cHwUSB_0::EndpointIN::config( WORD epMPS, BYTE epType ) { txBuf.maxpacket = epMPS; if( num == 0 ) { epMPS = 0; // MPS has to be 64 for endpoint 0 } USB_DEVICE->DAINTMSK |= USB_OTG_DAINTMSK_IEPM & ((1 << (num))); if( !(inep->DIEPCTL & USB_OTG_DIEPCTL_USBAEP) ) { inep->DIEPCTL |= ( (epMPS & USB_OTG_DIEPCTL_MPSIZ ) | (epType << 18 ) | (num << 22 ) | USB_OTG_DIEPCTL_SD0PID_SEVNFRM | USB_OTG_DIEPCTL_USBAEP ); } } //------------------------------------------------------------------- void cHwUSB_0::EndpointIN::flush( void ) { DWORD count = 200000; USB_OTG_FS->GRSTCTL = USB_OTG_GRSTCTL_TXFFLSH | (num << 5); while( (USB_OTG_FS->GRSTCTL & USB_OTG_GRSTCTL_TXFFLSH) && (count--) ); } //------------------------------------------------------------------- void cHwUSB_0::EndpointIN::reset() { inep->DIEPINT = 0xFF; } //------------------------------------------------------------------- void cHwUSB_0::EndpointIN::start() { if( inep->DIEPCTL & USB_OTG_DIEPCTL_EPENA ) { inep->DIEPCTL = ( USB_OTG_DIEPCTL_EPDIS | USB_OTG_DIEPCTL_SNAK ); } else { inep->DIEPCTL = 0; } inep->DIEPTSIZ = 0; inep->DIEPINT = 0xFF; } //------------------------------------------------------------------- void cHwUSB_0::EndpointIN::setStall( void ) { if( !(inep->DIEPCTL & USB_OTG_DIEPCTL_EPENA) ) { inep->DIEPCTL &= ~(USB_OTG_DIEPCTL_EPDIS); } inep->DIEPCTL |= USB_OTG_DIEPCTL_STALL; } //--------------------------------------------------------------- void cHwUSB_0::EndpointIN::clrStall( void ) { inep->DIEPCTL &= ~USB_OTG_DIEPCTL_STALL; inep->DIEPCTL |= USB_OTG_DIEPCTL_SD0PID_SEVNFRM; } //------------------------------------------------------------------- WORD cHwUSB_0::EndpointIN::write( BYTE *dataPtr, WORD len ) { len = MIN( len, (WORD)128 ); for(WORD i = 0; i < len; i++ ) { txBuf.data[i] = dataPtr[i]; } txBuf.size = len; txBuf.flag = true; return( len ); } //------------------------------------------------------------------- void cHwUSB_0::EndpointIN::writeToFifo( void ) { WORD len = MIN( txBuf.size, txBuf.maxpacket ); WORD cnt = (len + 3) / 4; if( (inep->DTXFSTS & USB_OTG_DTXFSTS_INEPTFSAV) >= cnt ) { __packed DWORD *src = (__packed DWORD *)&txBuf.data[0]; txBuf.size = 0; txBuf.flag = false; for( WORD i = 0; i < cnt; i++, src ++) { *fifo = *src; } } if( len <= 0 ) { USB_DEVICE->DIEPEMPMSK &= ~(0x1 << num); } } //------------------------------------------------------------------- void cHwUSB_0::EndpointIN::transmit( bool flag ) { WORD mps = txBuf.maxpacket; WORD len = MIN( txBuf.size, txBuf.maxpacket ); if( !txBuf.flag ) { transmitZLP(); return; } if( len == 0 ) // Zero Length Packet? { if( flag ) { transmitZLP(); } } else { BYTE pktCnt = ((len + mps -1)/ mps); inep->DIEPTSIZ &= ~( USB_OTG_DIEPTSIZ_PKTCNT | USB_OTG_DIEPTSIZ_XFRSIZ ); inep->DIEPTSIZ |= ( (USB_OTG_DIEPTSIZ_PKTCNT & (pktCnt << 19)) |(USB_OTG_DIEPTSIZ_XFRSIZ & len) ); USB_DEVICE->DIEPEMPMSK |= 1 << num; // Enable Tx FIFO Empty Interrupt inep->DIEPCTL |= ( USB_OTG_DIEPCTL_CNAK | USB_OTG_DIEPCTL_EPENA ); // Enable EP } } //------------------------------------------------------------------- void cHwUSB_0::EndpointIN::transmitZLP( void ) { inep->DIEPTSIZ &= ~( USB_OTG_DIEPTSIZ_PKTCNT | USB_OTG_DIEPTSIZ_XFRSIZ ); inep->DIEPTSIZ |= ( USB_OTG_DIEPTSIZ_PKTCNT & (1 << 19) ); inep->DIEPCTL |= ( USB_OTG_DIEPCTL_CNAK | USB_OTG_DIEPCTL_EPENA ); // Enable EP } //------------------------------------------------------------------- DWORD cHwUSB_0::EndpointIN::getInterrupt( void ) { DWORD msk = USB_DEVICE->DIEPMSK | (((USB_DEVICE->DIEPEMPMSK >> num) & 0x1) << 7); return( inep->DIEPINT & msk ); } //------------------------------------------------------------------- void cHwUSB_0::EndpointIN::clrInterrupt( DWORD interruptID ) { inep->DIEPINT = interruptID; } //******************************************************************* // // cHwUSB::EndpointOUT // //******************************************************************* //------------------------------------------------------------------- cHwUSB_0::EndpointOUT::EndpointOUT( void ) { } //------------------------------------------------------------------- void cHwUSB_0::EndpointOUT::init( BYTE numIn ) { num = numIn; outep = ((USB_OTG_OUTEndpointTypeDef *)((DWORD)USB_OTG_FS + USB_OTG_OUT_ENDPOINT_BASE + (num)*USB_OTG_EP_REG_SIZE)); fifo = (__IO DWORD *)((DWORD)USB_OTG_FS + USB_OTG_FIFO_BASE + (num)*USB_OTG_FIFO_SIZE ); } //------------------------------------------------------------------- void cHwUSB_0::EndpointOUT::config( WORD epMPS, BYTE epType ) { rxBuf.maxpacket = epMPS; if( num == 0 ) { epMPS = 0; // MPS has to be 64 for endpoint 0 } USB_DEVICE->DAINTMSK |= USB_OTG_DAINTMSK_OEPM & ((1 << (num)) << 16); if( !(outep->DOEPCTL & USB_OTG_DOEPCTL_USBAEP) ) { outep->DOEPCTL |= ( (epMPS & USB_OTG_DOEPCTL_MPSIZ ) | (epType << 18 ) | (USB_OTG_DIEPCTL_SD0PID_SEVNFRM) | (USB_OTG_DOEPCTL_USBAEP)); } if( num > 0 ) { receive(); } } //------------------------------------------------------------------- void cHwUSB_0::EndpointOUT::flush( void ) { DWORD count = 200000; USB_OTG_FS->GRSTCTL = USB_OTG_GRSTCTL_RXFFLSH; while( (USB_OTG_FS->GRSTCTL & USB_OTG_GRSTCTL_RXFFLSH) && (count--) ); } //------------------------------------------------------------------- void cHwUSB_0::EndpointOUT::reset() { outep->DOEPINT = 0xFF; } //------------------------------------------------------------------- void cHwUSB_0::EndpointOUT::start() { if( outep->DOEPCTL & USB_OTG_DOEPCTL_EPENA ) { outep->DOEPCTL = ( USB_OTG_DOEPCTL_EPDIS | USB_OTG_DOEPCTL_SNAK ); } else { outep->DOEPCTL = 0; } if( num == 0 ) // Setup control EP { outep->DOEPTSIZ = (USB_OTG_DOEPTSIZ_PKTCNT & (1 << 19)) | MAX_EP0_SIZE | USB_OTG_DOEPTSIZ_STUPCNT; } else { outep->DOEPTSIZ = 0; outep->DOEPINT = 0xFF; } } //------------------------------------------------------------------- void cHwUSB_0::EndpointOUT::setStall( void ) { if( !(outep->DOEPCTL & USB_OTG_DOEPCTL_EPENA) ) { outep->DOEPCTL &= ~(USB_OTG_DOEPCTL_EPDIS); } outep->DOEPCTL |= USB_OTG_DOEPCTL_STALL; if( num == 0 ) { outep->DOEPTSIZ = ( (USB_OTG_DOEPTSIZ_PKTCNT & (1 << 19)) | MAX_EP0_SIZE | USB_OTG_DOEPTSIZ_STUPCNT ); } } //--------------------------------------------------------------- void cHwUSB_0::EndpointOUT::clrStall( void ) { outep->DOEPCTL &= ~USB_OTG_DOEPCTL_STALL; outep->DOEPCTL |= USB_OTG_DOEPCTL_SD0PID_SEVNFRM; } //------------------------------------------------------------------- WORD cHwUSB_0::EndpointOUT::read( BYTE *dataPtr, WORD len ) { len = MIN( len, (WORD)rxBuf.size ); for( WORD i = 0; i < len; i++ ) { dataPtr[i] = rxBuf.data[i]; } rxBuf.size = 0; rxBuf.flag = false; return( len ); } //------------------------------------------------------------------- void cHwUSB_0::EndpointOUT::readFromFifo( WORD len ) { WORD cnt = (len + 3) / 4; __packed DWORD *dest = (__packed DWORD *)&rxBuf.data[0]; rxBuf.size = len; rxBuf.flag = true; for( WORD i = 0; i < cnt; i++, dest++ ) { *dest = *fifo; } } //------------------------------------------------------------------- void cHwUSB_0::EndpointOUT::receive( void ) { WORD mps = rxBuf.maxpacket; WORD len = MIN( rxBuf.size, rxBuf.maxpacket ); if( len == 0 ) { receiveZLP(); } else { BYTE pktcnt = (rxBuf.size + mps -1)/ mps; outep->DOEPTSIZ &= ~( USB_OTG_DOEPTSIZ_PKTCNT | USB_OTG_DOEPTSIZ_XFRSIZ ); outep->DOEPTSIZ |= ( (USB_OTG_DOEPTSIZ_PKTCNT & (pktcnt << 19)) |(USB_OTG_DOEPTSIZ_XFRSIZ & (mps * pktcnt)) ); outep->DOEPCTL |= ( USB_OTG_DOEPCTL_CNAK | USB_OTG_DOEPCTL_EPENA ); // Enable EP } } //------------------------------------------------------------------- void cHwUSB_0::EndpointOUT::receiveZLP() { outep->DOEPTSIZ &= ~( USB_OTG_DOEPTSIZ_PKTCNT | USB_OTG_DOEPTSIZ_XFRSIZ ); outep->DOEPTSIZ |= ( (USB_OTG_DOEPTSIZ_PKTCNT & (1 << 19)) | (USB_OTG_DOEPTSIZ_XFRSIZ & rxBuf.maxpacket) ); outep->DOEPCTL |= ( USB_OTG_DOEPCTL_CNAK | USB_OTG_DOEPCTL_EPENA ); // Enable EP } //------------------------------------------------------------------- DWORD cHwUSB_0::EndpointOUT::getInterrupt( void ) { return( outep->DOEPINT & USB_DEVICE->DOEPMSK ); } //------------------------------------------------------------------- void cHwUSB_0::EndpointOUT::clrInterrupt( DWORD interruptID ) { outep->DOEPINT = interruptID; } //******************************************************************* // // cHwUSB // //******************************************************************* //------------------------------------------------------------------- cHwUSB_0 *cHwUSB_0::usbPtr = 0; //------------------------------------------------------------------- cHwUSB_0::cHwUSB_0( cHwUSBdesc &desc ) : cHwUSB( desc ) { usbPtr = this; for( WORD i = 0; i < NUM_OF_ENDPOINTS; i++ ) { epIN [i].init( i ); epOUT[i].init( i ); } } //------------------------------------------------------------------- void cHwUSB_0::start(void) { cHwPinConfig::set( GPIOA, 9, cHwPinConfig::INPUT|cHwPinConfig::NO_PUPD, 0 ); cHwPinConfig::set( cHwPinConfig::OTG_FS_ID, cHwPinConfig::PULL_UP |cHwPinConfig::HIGH_SPEED |cHwPinConfig::OPEN_DRAIN ); cHwPinConfig::set( cHwPinConfig::OTG_FS_DM, cHwPinConfig::NO_PUPD |cHwPinConfig::HIGH_SPEED |cHwPinConfig::PUSH_PULL ); cHwPinConfig::set( cHwPinConfig::OTG_FS_DP, cHwPinConfig::NO_PUPD |cHwPinConfig::HIGH_SPEED |cHwPinConfig::PUSH_PULL); RCC->AHB2ENR |= RCC_AHB2ENR_OTGFSEN; // Enable USB-FS clock NVIC_EnableIRQ( OTG_FS_IRQn ); USB_OTG_FS->GAHBCFG &= ~USB_OTG_GAHBCFG_GINT; // disable USB interrupts USB_OTG_FS->GUSBCFG |= USB_OTG_GUSBCFG_PHYSEL; // Select FS Embedded PHY CoreReset(); // Reset after a PHY select // and set Host mode USB_OTG_FS->GCCFG = USB_OTG_GCCFG_PWRDWN; // Deactivate the power down USB_OTG_FS->GUSBCFG &= ~( USB_OTG_GUSBCFG_FHMOD // Force Device Mode |USB_OTG_GUSBCFG_FDMOD ); USB_OTG_FS->GUSBCFG |= ( USB_OTG_GUSBCFG_FDMOD ); for (uint32_t i = 0; i < 15 ; i++) { USB_OTG_FS->DIEPTXF[i] = 0; } USB_OTG_FS->GCCFG |= USB_OTG_GCCFG_VBUSBSEN; // Activate VBUS Sensing B USB_OTG_FS->GCCFG |= USB_OTG_GCCFG_NOVBUSSENS; // No Vbus sensing USB_PCGCCTL = 0; // Restart the Phy Clock // Device configuration USB_DEVICE->DCFG |= ( (3 << 0) // Device speed: Full speed |(0 << 11)); // Periodic frame interval: 80% // Flush the FIFO epIN [0].flush(); epOUT[0].flush(); // Clear all pending device interrupts USB_DEVICE->DIEPMSK = 0; USB_DEVICE->DOEPMSK = 0; USB_DEVICE->DAINT = 0xFFFFFFFF; USB_DEVICE->DAINTMSK = 0; for (uint32_t i = 0; i < NUM_OF_ENDPOINTS; i++) { epIN[i].start(); epOUT[i].start(); } USB_DEVICE->DIEPMSK &= ~(USB_OTG_DIEPMSK_TXFURM); // USB_OTG_FS->GINTMSK = 0; // Disable all interrupts USB_OTG_FS->GINTSTS = 0xBFFFFFFF; // Clear any pending interrupts USB_OTG_FS->GINTMSK |= USB_OTG_GINTMSK_RXFLVLM; // Enable the common interrupts // Enable interrupts matching to the Device mode ONLY USB_OTG_FS->GINTMSK |= ( USB_OTG_GINTMSK_USBSUSPM | USB_OTG_GINTMSK_USBRST | USB_OTG_GINTMSK_ENUMDNEM | USB_OTG_GINTMSK_IEPINT | USB_OTG_GINTMSK_OEPINT | USB_OTG_GINTMSK_WUIM ); USB_OTG_FS->GINTMSK |= ( USB_OTG_GINTMSK_SRQIM | USB_OTG_GINTMSK_OTGINT); USB_DEVICE->DCTL |= USB_OTG_DCTL_SDIS; // disconnect WORD offset = 0; USB_OTG_FS->GRXFSIZ = ( 64 ); offset = 64; // set RX fifo size USB_OTG_FS->DIEPTXF0_HNPTXFSIZ = (( 64 << 16) | offset); offset += 64; // set TX 0 fifo size USB_OTG_FS->DIEPTXF[0] = (( 64 << 16) | offset); offset += 64; // set TX 1 fifo size USB_OTG_FS->DIEPTXF[1] = (( 64 << 16) | offset); offset += 64; // set TX 2 fifo size USB_OTG_FS->DIEPTXF[2] = (( 64 << 16) | offset); // set TX 3 fifo size USB_DEVICE->DCTL &= ~USB_OTG_DCTL_SDIS; // connect USB_OTG_FS->GAHBCFG |= USB_OTG_GAHBCFG_GINT; // enable USB interrupts } //------------------------------------------------------------------- inline void cHwUSB_0::isr(void) { // Current mode of operation = Host mode ? if( USB_OTG_FS->GINTSTS & USB_OTG_GINTSTS_CMOD ) { return; } //----------------------------------------------------------------- if( isInterruptPending( USB_OTG_GINTSTS_MMIS ) ) { // incorrect mode clrInterrupt( USB_OTG_GINTSTS_MMIS); } //----------------------------------------------------------------- if( isInterruptPending( USB_OTG_GINTSTS_OEPINT ) ) { DWORD interruptBits = getOutInterrupt(); DWORD interruptType = 0; BYTE epNum = 0; while ( interruptBits ) { if( interruptBits & 0x1 ) { interruptType = epOUT[epNum].getInterrupt(); if( interruptType & USB_OTG_DOEPINT_XFRC ) { // OUT-package received, non-control epOUT[epNum].receive(); eventHandler( epNum, false ); epOUT[epNum].clrInterrupt( USB_OTG_DOEPINT_XFRC ); } if( interruptType & USB_OTG_DOEPINT_STUP ) { // Setup-package received eventHandler( 0, true ); epIN[0].transmit(true); epOUT[epNum].clrInterrupt( USB_OTG_DOEPINT_STUP ); } if( interruptType & USB_OTG_DOEPINT_OTEPDIS ) { epOUT[epNum].clrInterrupt( USB_OTG_DOEPINT_OTEPDIS); } } // handle next endpoint epNum++; interruptBits >>= 1; } } //----------------------------------------------------------------- if( isInterruptPending( USB_OTG_GINTSTS_IEPINT ) ) { DWORD interruptBits = getInInterrupt(); DWORD interruptType = 0; BYTE epNum = 0; while( interruptBits ) { if( interruptBits & 0x1 ) { interruptType = epIN[epNum].getInterrupt( ); if( interruptType & USB_OTG_DIEPINT_XFRC ) { USB_DEVICE->DIEPEMPMSK = ~(0x1 << epNum); epIN[epNum].clrInterrupt( USB_OTG_DIEPINT_XFRC ); epOUT[0].receiveZLP(); eventHandler( epNum | 0x80, true ); epIN[epNum].transmit( false ); } if( interruptType & USB_OTG_DIEPINT_TOC ) { epIN[epNum].clrInterrupt( USB_OTG_DIEPINT_TOC ); } if( interruptType & USB_OTG_DIEPINT_ITTXFE ) { epIN[epNum].clrInterrupt( USB_OTG_DIEPINT_ITTXFE ); } if( interruptType & USB_OTG_DIEPINT_INEPNE ) { epIN[epNum].clrInterrupt( USB_OTG_DIEPINT_INEPNE ); } if( interruptType & USB_OTG_DIEPINT_EPDISD ) { epIN[epNum].clrInterrupt( USB_OTG_DIEPINT_EPDISD ); } if( interruptType & USB_OTG_DIEPINT_TXFE ) { epIN[epNum].writeToFifo(); epIN[epNum].clrInterrupt( USB_OTG_DIEPINT_TXFE ); } } // handle next endpoint epNum++; interruptBits >>= 1; } } //----------------------------------------------------------------- if( isInterruptPending( USB_OTG_GINTSTS_WKUINT ) ) { USB_DEVICE->DCTL &= ~USB_OTG_DCTL_RWUSIG; clrInterrupt( USB_OTG_GINTSTS_WKUINT ); } //----------------------------------------------------------------- if( isInterruptPending( USB_OTG_GINTSTS_USBSUSP ) ) { clrInterrupt( USB_OTG_GINTSTS_USBSUSP ); } //----------------------------------------------------------------- if( isInterruptPending( USB_OTG_GINTSTS_USBRST ) ) { reset(); clrInterrupt( USB_OTG_GINTSTS_USBRST ); } //----------------------------------------------------------------- if( isInterruptPending( USB_OTG_GINTSTS_ENUMDNE ) ) { USB_DEVICE->DCTL |= USB_OTG_DCTL_CGINAK; USB_OTG_FS->GUSBCFG &= ~( USB_OTG_GUSBCFG_TRDT ); USB_OTG_FS->GUSBCFG |= ( USB_OTG_GUSBCFG_TRDT_0 | USB_OTG_GUSBCFG_TRDT_2 ); epOUT[0].config( MAX_EP0_SIZE ); epIN [0].config( MAX_EP0_SIZE ); clrInterrupt( USB_OTG_GINTSTS_ENUMDNE ); } //----------------------------------------------------------------- if( isInterruptPending( USB_OTG_GINTSTS_RXFLVL ) ) { USB_OTG_FS->GINTMSK &= ~(USB_OTG_GINTSTS_RXFLVL); DWORD temp = USB_OTG_FS->GRXSTSP; BYTE epnum = temp & USB_OTG_GRXSTSP_EPNUM; if( ((temp & USB_OTG_GRXSTSP_PKTSTS) >> 17) == 2 ) // Packet status = OUT data packet received { if( temp & USB_OTG_GRXSTSP_BCNT ) { epOUT[epnum].readFromFifo( (temp & USB_OTG_GRXSTSP_BCNT) >> 4 ); } } else if( ((temp & USB_OTG_GRXSTSP_PKTSTS) >> 17) == 6 ) // Packet status = Setup data packet received { epOUT[epnum].readFromFifo( 8 ); } USB_OTG_FS->GINTMSK |= (USB_OTG_GINTSTS_RXFLVL); } //----------------------------------------------------------------- if( isInterruptPending( USB_OTG_GINTSTS_SOF ) ) { clrInterrupt( USB_OTG_GINTSTS_SOF ); } //----------------------------------------------------------------- if( isInterruptPending( USB_OTG_GINTSTS_SRQINT ) ) { clrInterrupt( USB_OTG_GINTSTS_SRQINT ); } //----------------------------------------------------------------- if( isInterruptPending( USB_OTG_GINTSTS_OTGINT ) ) { DWORD temp = USB_OTG_FS->GOTGINT; USB_OTG_FS->GOTGINT |= temp; } } //------------------------------------------------------------------- void cHwUSB_0::reset( void ) { USB_DEVICE->DCTL &= ~USB_OTG_DCTL_RWUSIG; epIN[0].flush(); for( WORD i = 0; i < NUM_OF_ENDPOINTS ; i++ ) { epIN [i].reset(); epOUT[i].reset(); } USB_DEVICE->DAINT = 0xFFFFFFFF; USB_DEVICE->DAINTMSK |= 0x10001; USB_DEVICE->DOEPMSK |= ( USB_OTG_DOEPMSK_STUPM | USB_OTG_DOEPMSK_XFRCM | USB_OTG_DOEPMSK_EPDM | USB_OTG_DOEPMSK_OTEPDM ); USB_DEVICE->DIEPMSK |= ( USB_OTG_DIEPMSK_TOM | USB_OTG_DIEPMSK_XFRCM | USB_OTG_DIEPMSK_EPDM ); USB_DEVICE->DCFG &= ~USB_OTG_DCFG_DAD; // Set Default Address to 0 } //------------------------------------------------------------------- void cHwUSB_0::configure( BYTE flag ) { } //------------------------------------------------------------------- void cHwUSB_0::setAddress( BYTE adr ) { USB_DEVICE->DCFG &= ~USB_OTG_DCFG_DAD; USB_DEVICE->DCFG |= USB_OTG_DCFG_DAD & (adr << 4); epIN[0].transmitZLP(); } //------------------------------------------------------------------- void cHwUSB_0::configEP( BYTE epAddr, WORD epMaxPacketSize, BYTE epType ) { BYTE epNum = epAddr&0x7F; if( epNum < NUM_OF_ENDPOINTS ) { if( epAddr & 0x80 ) { epIN[epNum].config( epMaxPacketSize, epType ); } else { epOUT[epNum].config( epMaxPacketSize, epType ); } clrStallEP( epAddr ); epIN[epNum].transmitZLP(); } } //--------------------------------------------------------------- void cHwUSB_0::setStallEP (BYTE epAddr) { BYTE epNum = epAddr&0x7F; if( epNum < NUM_OF_ENDPOINTS ) { if( epAddr & 0x80 ) { epIN[epNum].setStall(); } else { epOUT[epNum].setStall(); } } } //--------------------------------------------------------------- void cHwUSB_0::clrStallEP (BYTE epAddr) { BYTE epNum = epAddr&0x7F; if( epNum < NUM_OF_ENDPOINTS ) { if( epAddr & 0x80 ) epIN[epNum].clrStall(); else epOUT[epNum].clrStall(); } } //------------------------------------------------------------------- WORD cHwUSB_0::readEP( BYTE epAddr, BYTE *dataPtr, WORD len ) { BYTE epNum = epAddr&0x7F; if( epNum < NUM_OF_ENDPOINTS ) { return( epOUT[epNum].read( dataPtr, len ) ); } return( 0 ); } //------------------------------------------------------------------- WORD cHwUSB_0::writeEP( BYTE epAddr, BYTE *dataPtr, WORD len ) { BYTE epNum = epAddr&0x7F; if( epNum < NUM_OF_ENDPOINTS ) { return( epIN[epNum].write( dataPtr, len ) ); } return( 0 ); } //------------------------------------------------------------------- BYTE cHwUSB_0::CoreReset( void ) { DWORD count = 200000; // Wait for AHB master IDLE state while( !(USB_OTG_FS->GRSTCTL & USB_OTG_GRSTCTL_AHBIDL) ) { if( !count-- ) { return false; } } USB_OTG_FS->GRSTCTL |= USB_OTG_GRSTCTL_CSRST; // Core Soft Reset count = 200000; while( USB_OTG_FS->GRSTCTL & USB_OTG_GRSTCTL_CSRST ) { if( !count-- ) { return false; } } return true; } //------------------------------------------------------------------- DWORD cHwUSB_0::getInInterrupt( void ) { return( USB_DEVICE->DAINT & USB_DEVICE->DAINTMSK & 0xFFFF ); } //------------------------------------------------------------------- DWORD cHwUSB_0::getOutInterrupt( void ) { return( ( USB_DEVICE->DAINT & USB_DEVICE->DAINTMSK & 0xFFFF0000 ) >> 16); } //------------------------------------------------------------------- BYTE cHwUSB_0::isInterruptPending( DWORD interuptID ) { return( ( USB_OTG_FS->GINTSTS & USB_OTG_FS->GINTMSK & interuptID ) == interuptID ); } //------------------------------------------------------------------- void cHwUSB_0::clrInterrupt( DWORD interuptID ) { USB_OTG_FS->GINTSTS |= interuptID; } //------------------------------------------------------------------- //------------------------------------------------------------------- extern "C" { void OTG_FS_IRQHandler(void) { cSystem::disableInterrupt(); cHwUSB_0::usbPtr->isr(); cSystem::enableInterrupt(); } } //EOF
27.908186
118
0.466646
ThBreuer
2757e9c3e95659a0d405e82eaae0c3f11297d662
26,598
cpp
C++
src/gb/cpu/disass.cpp
destoer/destoer-emu
2a7941b175126e998eed2df8df87ee382c43d0b1
[ "BSD-3-Clause" ]
20
2020-01-19T21:54:23.000Z
2021-11-28T17:27:15.000Z
src/gb/cpu/disass.cpp
destoer/destoer-emu
2a7941b175126e998eed2df8df87ee382c43d0b1
[ "BSD-3-Clause" ]
3
2020-05-01T07:46:10.000Z
2021-09-18T13:50:18.000Z
src/gb/cpu/disass.cpp
destoer/destoer-emu
2a7941b175126e998eed2df8df87ee382c43d0b1
[ "BSD-3-Clause" ]
null
null
null
#include <gb/gb.h> #include <destoer-emu/lib.h> namespace gameboy { Disass::Disass(GB &gb) : mem(gb.mem) { rom_sym_table.clear(); mem_sym_table.clear(); sym_file_loaded = false; } void Disass::init() noexcept { load_sym_file(remove_ext(mem.rom_info.filename) + ".sym"); } enum class disass_type { op_u16=0, op_u8=1, op_i8=2, op_none=3 }; constexpr int disass_type_size[] = { 3, // opcode and u16 oper (op_u16) 2, // opcode and u8 oper (op_u8) 2, // ditto (op_i8) 1 // opcode only (op_none) }; struct Disass_entry { const char *fmt_str; disass_type type; }; // tables auto generated with a script constexpr Disass_entry opcode_table[256] = { {"nop",disass_type::op_none}, {"ld bc,{}",disass_type::op_u16}, {"ld (bc),a",disass_type::op_none}, {"inc bc",disass_type::op_none}, {"inc b",disass_type::op_none}, {"dec b",disass_type::op_none}, {"ld b,{}",disass_type::op_u8}, {"rlca",disass_type::op_none}, {"ld ({}),sp",disass_type::op_u16}, {"add hl,bc",disass_type::op_none}, {"ld a,(bc)",disass_type::op_none}, {"dec bc",disass_type::op_none}, {"inc c",disass_type::op_none}, {"dec c",disass_type::op_none}, {"ld c,{}",disass_type::op_u8}, {"rrca",disass_type::op_none}, {"stop",disass_type::op_none}, {"ld de,{}",disass_type::op_u16}, {"ld (de),a",disass_type::op_none}, {"inc de",disass_type::op_none}, {"inc d",disass_type::op_none}, {"dec d",disass_type::op_none}, {"ld d,{}",disass_type::op_u8}, {"rla",disass_type::op_none}, {"jr {}",disass_type::op_i8}, {"add hl,de",disass_type::op_none}, {"ld a,(de)",disass_type::op_none}, {"dec de",disass_type::op_none}, {"inc e",disass_type::op_none}, {"dec e",disass_type::op_none}, {"ld e,{}",disass_type::op_u8}, {"rra",disass_type::op_none}, {"jr nz,{}",disass_type::op_i8}, {"ld hl,{}",disass_type::op_u16}, {"ld (hl+),a",disass_type::op_none}, {"inc hl",disass_type::op_none}, {"inc h",disass_type::op_none}, {"dec h",disass_type::op_none}, {"ld h,{}",disass_type::op_u8}, {"daa",disass_type::op_none}, {"jr z,{}",disass_type::op_i8}, {"add hl,hl",disass_type::op_none}, {"ld a,(hl+)",disass_type::op_none}, {"dec hl",disass_type::op_none}, {"inc l",disass_type::op_none}, {"dec l",disass_type::op_none}, {"ld l,{}",disass_type::op_u8}, {"cpl",disass_type::op_none}, {"jr nc,{}",disass_type::op_i8}, {"ld sp,{}",disass_type::op_u16}, {"ld (hl-),a",disass_type::op_none}, {"inc sp",disass_type::op_none}, {"inc (hl)",disass_type::op_none}, {"dec (hl)",disass_type::op_none}, {"ld (hl),{}",disass_type::op_u8}, {"scf",disass_type::op_none}, {"jr c,{}",disass_type::op_i8}, {"add hl,sp",disass_type::op_none}, {"ld a,(hl-)",disass_type::op_none}, {"dec sp",disass_type::op_none}, {"inc a",disass_type::op_none}, {"dec a",disass_type::op_none}, {"ld a,{}",disass_type::op_u8}, {"ccf",disass_type::op_none}, {"ld b,b",disass_type::op_none}, {"ld b,c",disass_type::op_none}, {"ld b,d",disass_type::op_none}, {"ld b,e",disass_type::op_none}, {"ld b,h",disass_type::op_none}, {"ld b,l",disass_type::op_none}, {"ld b,(hl)",disass_type::op_none}, {"ld b,a",disass_type::op_none}, {"ld c,b",disass_type::op_none}, {"ld c,c",disass_type::op_none}, {"ld c,d",disass_type::op_none}, {"ld c,e",disass_type::op_none}, {"ld c,h",disass_type::op_none}, {"ld c,l",disass_type::op_none}, {"ld c,(hl)",disass_type::op_none}, {"ld c,a",disass_type::op_none}, {"ld d,b",disass_type::op_none}, {"ld d,c",disass_type::op_none}, {"ld d,d",disass_type::op_none}, {"ld d,e",disass_type::op_none}, {"ld d,h",disass_type::op_none}, {"ld d,l",disass_type::op_none}, {"ld d,(hl)",disass_type::op_none}, {"ld d,a",disass_type::op_none}, {"ld e,b",disass_type::op_none}, {"ld e,c",disass_type::op_none}, {"ld e,d",disass_type::op_none}, {"ld e,e",disass_type::op_none}, {"ld e,h",disass_type::op_none}, {"ld e,l",disass_type::op_none}, {"ld e,(hl)",disass_type::op_none}, {"ld e,a",disass_type::op_none}, {"ld h,b",disass_type::op_none}, {"ld h,c",disass_type::op_none}, {"ld h,d",disass_type::op_none}, {"ld h,e",disass_type::op_none}, {"ld h,h",disass_type::op_none}, {"ld h,l",disass_type::op_none}, {"ld h,(hl)",disass_type::op_none}, {"ld h,a",disass_type::op_none}, {"ld l,b",disass_type::op_none}, {"ld l,c",disass_type::op_none}, {"ld l,d",disass_type::op_none}, {"ld l,e",disass_type::op_none}, {"ld l,h",disass_type::op_none}, {"ld l,l",disass_type::op_none}, {"ld l,(hl)",disass_type::op_none}, {"ld l,a",disass_type::op_none}, {"ld (hl),b",disass_type::op_none}, {"ld (hl),c",disass_type::op_none}, {"ld (hl),d",disass_type::op_none}, {"ld (hl),e",disass_type::op_none}, {"ld (hl),h",disass_type::op_none}, {"ld (hl),l",disass_type::op_none}, {"halt",disass_type::op_none}, {"ld (hl),a",disass_type::op_none}, {"ld a,b",disass_type::op_none}, {"ld a,c",disass_type::op_none}, {"ld a,d",disass_type::op_none}, {"ld a,e",disass_type::op_none}, {"ld a,h",disass_type::op_none}, {"ld a,l",disass_type::op_none}, {"ld a,(hl)",disass_type::op_none}, {"ld a,a",disass_type::op_none}, {"add a,b",disass_type::op_none}, {"add a,c",disass_type::op_none}, {"add a,d",disass_type::op_none}, {"add a,e",disass_type::op_none}, {"add a,h",disass_type::op_none}, {"add a,l",disass_type::op_none}, {"add a,(hl)",disass_type::op_none}, {"add a,a",disass_type::op_none}, {"adc a,b",disass_type::op_none}, {"adc a,c",disass_type::op_none}, {"adc a,d",disass_type::op_none}, {"adc a,e",disass_type::op_none}, {"adc a,h",disass_type::op_none}, {"adc a,l",disass_type::op_none}, {"adc a,(hl)",disass_type::op_none}, {"adc a,a",disass_type::op_none}, {"sub a,b",disass_type::op_none}, {"sub a,c",disass_type::op_none}, {"sub a,d",disass_type::op_none}, {"sub a,e",disass_type::op_none}, {"sub a,h",disass_type::op_none}, {"sub a,l",disass_type::op_none}, {"sub a,(hl)",disass_type::op_none}, {"sub a,a",disass_type::op_none}, {"sbc a,b",disass_type::op_none}, {"sbc a,c",disass_type::op_none}, {"sbc a,d",disass_type::op_none}, {"sbc a,e",disass_type::op_none}, {"sbc a,h",disass_type::op_none}, {"sbc a,l",disass_type::op_none}, {"sbc a,(hl)",disass_type::op_none}, {"sbc a,a",disass_type::op_none}, {"and a,b",disass_type::op_none}, {"and a,c",disass_type::op_none}, {"and a,d",disass_type::op_none}, {"and a,e",disass_type::op_none}, {"and a,h",disass_type::op_none}, {"and a,l",disass_type::op_none}, {"and a,(hl)",disass_type::op_none}, {"and a,a",disass_type::op_none}, {"xor a,b",disass_type::op_none}, {"xor a,c",disass_type::op_none}, {"xor a,d",disass_type::op_none}, {"xor a,e",disass_type::op_none}, {"xor a,h",disass_type::op_none}, {"xor a,l",disass_type::op_none}, {"xor a,(hl)",disass_type::op_none}, {"xor a,a",disass_type::op_none}, {"or a,b",disass_type::op_none}, {"or a,c",disass_type::op_none}, {"or a,d",disass_type::op_none}, {"or a,e",disass_type::op_none}, {"or a,h",disass_type::op_none}, {"or a,l",disass_type::op_none}, {"or a,(hl)",disass_type::op_none}, {"or a,a",disass_type::op_none}, {"cp a,b",disass_type::op_none}, {"cp a,c",disass_type::op_none}, {"cp a,d",disass_type::op_none}, {"cp a,e",disass_type::op_none}, {"cp a,h",disass_type::op_none}, {"cp a,l",disass_type::op_none}, {"cp a,(hl)",disass_type::op_none}, {"cp a,a",disass_type::op_none}, {"ret nz",disass_type::op_none}, {"pop bc",disass_type::op_none}, {"jp nz,{}",disass_type::op_u16}, {"jp {}",disass_type::op_u16}, {"call nz,{}",disass_type::op_u16}, {"push bc",disass_type::op_none}, {"add a,{}",disass_type::op_u8}, {"rst 00h",disass_type::op_none}, {"ret z",disass_type::op_none}, {"ret",disass_type::op_none}, {"jp z,{}",disass_type::op_u16}, {"prefix cb",disass_type::op_none}, {"call z,{}",disass_type::op_u16}, {"call {}",disass_type::op_u16}, {"adc a,{}",disass_type::op_u8}, {"rst 08h",disass_type::op_none}, {"ret nc",disass_type::op_none}, {"pop de",disass_type::op_none}, {"jp nc,{}",disass_type::op_u16}, {"unknown opcode",disass_type::op_none}, {"call nc,{}",disass_type::op_u16}, {"push de",disass_type::op_none}, {"sub a,{}",disass_type::op_u8}, {"rst 10h",disass_type::op_none}, {"ret c",disass_type::op_none}, {"reti",disass_type::op_none}, {"jp c,{}",disass_type::op_u16}, {"unknown opcode",disass_type::op_none}, {"call c,{}",disass_type::op_u16}, {"unknown opcode",disass_type::op_none}, {"sbc a,{}",disass_type::op_u8}, {"rst 18h",disass_type::op_none}, {"ld (ff00+{}),a",disass_type::op_u8}, {"pop hl",disass_type::op_none}, {"ld (ff00+c),a",disass_type::op_none}, {"unknown opcode",disass_type::op_none}, {"unknown opcode",disass_type::op_none}, {"push hl",disass_type::op_none}, {"and a,{}",disass_type::op_u8}, {"rst 20h",disass_type::op_none}, {"add sp,{}",disass_type::op_i8}, {"jp hl",disass_type::op_none}, {"ld ({}),a",disass_type::op_u16}, {"unknown opcode",disass_type::op_none}, {"unknown opcode",disass_type::op_none}, {"unknown opcode",disass_type::op_none}, {"xor a,{}",disass_type::op_u8}, {"rst 28h",disass_type::op_none}, {"ld a,(ff00+{})",disass_type::op_u8}, {"pop af",disass_type::op_none}, {"ld a,(ff00+c)",disass_type::op_none}, {"di",disass_type::op_none}, {"unknown opcode",disass_type::op_none}, {"push af",disass_type::op_none}, {"or a,{}",disass_type::op_u8}, {"rst 30h",disass_type::op_none}, {"ld hl,sp+{}",disass_type::op_i8}, {"ld sp,hl",disass_type::op_none}, {"ld a,({})",disass_type::op_u16}, {"ei",disass_type::op_none}, {"unknown opcode",disass_type::op_none}, {"unknown opcode",disass_type::op_none}, {"cp a,{}",disass_type::op_u8}, {"rst 38h",disass_type::op_none} }; constexpr Disass_entry cb_opcode_table[256] = { {"rlc b",disass_type::op_none}, {"rlc c",disass_type::op_none}, {"rlc d",disass_type::op_none}, {"rlc e",disass_type::op_none}, {"rlc h",disass_type::op_none}, {"rlc l",disass_type::op_none}, {"rlc (hl)",disass_type::op_none}, {"rlc a",disass_type::op_none}, {"rrc b",disass_type::op_none}, {"rrc c",disass_type::op_none}, {"rrc d",disass_type::op_none}, {"rrc e",disass_type::op_none}, {"rrc h",disass_type::op_none}, {"rrc l",disass_type::op_none}, {"rrc (hl)",disass_type::op_none}, {"rrc a",disass_type::op_none}, {"rl b",disass_type::op_none}, {"rl c",disass_type::op_none}, {"rl d",disass_type::op_none}, {"rl e",disass_type::op_none}, {"rl h",disass_type::op_none}, {"rl l",disass_type::op_none}, {"rl (hl)",disass_type::op_none}, {"rl a",disass_type::op_none}, {"rr b",disass_type::op_none}, {"rr c",disass_type::op_none}, {"rr d",disass_type::op_none}, {"rr e",disass_type::op_none}, {"rr h",disass_type::op_none}, {"rr l",disass_type::op_none}, {"rr (hl)",disass_type::op_none}, {"rr a",disass_type::op_none}, {"sla b",disass_type::op_none}, {"sla c",disass_type::op_none}, {"sla d",disass_type::op_none}, {"sla e",disass_type::op_none}, {"sla h",disass_type::op_none}, {"sla l",disass_type::op_none}, {"sla (hl)",disass_type::op_none}, {"sla a",disass_type::op_none}, {"sra b",disass_type::op_none}, {"sra c",disass_type::op_none}, {"sra d",disass_type::op_none}, {"sra e",disass_type::op_none}, {"sra h",disass_type::op_none}, {"sra l",disass_type::op_none}, {"sra (hl)",disass_type::op_none}, {"sra a",disass_type::op_none}, {"swap b",disass_type::op_none}, {"swap c",disass_type::op_none}, {"swap d",disass_type::op_none}, {"swap e",disass_type::op_none}, {"swap h",disass_type::op_none}, {"swap l",disass_type::op_none}, {"swap (hl)",disass_type::op_none}, {"swap a",disass_type::op_none}, {"srl b",disass_type::op_none}, {"srl c",disass_type::op_none}, {"srl d",disass_type::op_none}, {"srl e",disass_type::op_none}, {"srl h",disass_type::op_none}, {"srl l",disass_type::op_none}, {"srl (hl)",disass_type::op_none}, {"srl a",disass_type::op_none}, {"bit 0,b",disass_type::op_none}, {"bit 0,c",disass_type::op_none}, {"bit 0,d",disass_type::op_none}, {"bit 0,e",disass_type::op_none}, {"bit 0,h",disass_type::op_none}, {"bit 0,l",disass_type::op_none}, {"bit 0,(hl)",disass_type::op_none}, {"bit 0,a",disass_type::op_none}, {"bit 1,b",disass_type::op_none}, {"bit 1,c",disass_type::op_none}, {"bit 1,d",disass_type::op_none}, {"bit 1,e",disass_type::op_none}, {"bit 1,h",disass_type::op_none}, {"bit 1,l",disass_type::op_none}, {"bit 1,(hl)",disass_type::op_none}, {"bit 1,a",disass_type::op_none}, {"bit 2,b",disass_type::op_none}, {"bit 2,c",disass_type::op_none}, {"bit 2,d",disass_type::op_none}, {"bit 2,e",disass_type::op_none}, {"bit 2,h",disass_type::op_none}, {"bit 2,l",disass_type::op_none}, {"bit 2,(hl)",disass_type::op_none}, {"bit 2,a",disass_type::op_none}, {"bit 3,b",disass_type::op_none}, {"bit 3,c",disass_type::op_none}, {"bit 3,d",disass_type::op_none}, {"bit 3,e",disass_type::op_none}, {"bit 3,h",disass_type::op_none}, {"bit 3,l",disass_type::op_none}, {"bit 3,(hl)",disass_type::op_none}, {"bit 3,a",disass_type::op_none}, {"bit 4,b",disass_type::op_none}, {"bit 4,c",disass_type::op_none}, {"bit 4,d",disass_type::op_none}, {"bit 4,e",disass_type::op_none}, {"bit 4,h",disass_type::op_none}, {"bit 4,l",disass_type::op_none}, {"bit 4,(hl)",disass_type::op_none}, {"bit 4,a",disass_type::op_none}, {"bit 5,b",disass_type::op_none}, {"bit 5,c",disass_type::op_none}, {"bit 5,d",disass_type::op_none}, {"bit 5,e",disass_type::op_none}, {"bit 5,h",disass_type::op_none}, {"bit 5,l",disass_type::op_none}, {"bit 5,(hl)",disass_type::op_none}, {"bit 5,a",disass_type::op_none}, {"bit 6,b",disass_type::op_none}, {"bit 6,c",disass_type::op_none}, {"bit 6,d",disass_type::op_none}, {"bit 6,e",disass_type::op_none}, {"bit 6,h",disass_type::op_none}, {"bit 6,l",disass_type::op_none}, {"bit 6,(hl)",disass_type::op_none}, {"bit 6,a",disass_type::op_none}, {"bit 7,b",disass_type::op_none}, {"bit 7,c",disass_type::op_none}, {"bit 7,d",disass_type::op_none}, {"bit 7,e",disass_type::op_none}, {"bit 7,h",disass_type::op_none}, {"bit 7,l",disass_type::op_none}, {"bit 7,(hl)",disass_type::op_none}, {"bit 7,a",disass_type::op_none}, {"res 0,b",disass_type::op_none}, {"res 0,c",disass_type::op_none}, {"res 0,d",disass_type::op_none}, {"res 0,e",disass_type::op_none}, {"res 0,h",disass_type::op_none}, {"res 0,l",disass_type::op_none}, {"res 0,(hl)",disass_type::op_none}, {"res 0,a",disass_type::op_none}, {"res 1,b",disass_type::op_none}, {"res 1,c",disass_type::op_none}, {"res 1,d",disass_type::op_none}, {"res 1,e",disass_type::op_none}, {"res 1,h",disass_type::op_none}, {"res 1,l",disass_type::op_none}, {"res 1,(hl)",disass_type::op_none}, {"res 1,a",disass_type::op_none}, {"res 2,b",disass_type::op_none}, {"res 2,c",disass_type::op_none}, {"res 2,d",disass_type::op_none}, {"res 2,e",disass_type::op_none}, {"res 2,h",disass_type::op_none}, {"res 2,l",disass_type::op_none}, {"res 2,(hl)",disass_type::op_none}, {"res 2,a",disass_type::op_none}, {"res 3,b",disass_type::op_none}, {"res 3,c",disass_type::op_none}, {"res 3,d",disass_type::op_none}, {"res 3,e",disass_type::op_none}, {"res 3,h",disass_type::op_none}, {"res 3,l",disass_type::op_none}, {"res 3,(hl)",disass_type::op_none}, {"res 3,a",disass_type::op_none}, {"res 4,b",disass_type::op_none}, {"res 4,c",disass_type::op_none}, {"res 4,d",disass_type::op_none}, {"res 4,e",disass_type::op_none}, {"res 4,h",disass_type::op_none}, {"res 4,l",disass_type::op_none}, {"res 4,(hl)",disass_type::op_none}, {"res 4,a",disass_type::op_none}, {"res 5,b",disass_type::op_none}, {"res 5,c",disass_type::op_none}, {"res 5,d",disass_type::op_none}, {"res 5,e",disass_type::op_none}, {"res 5,h",disass_type::op_none}, {"res 5,l",disass_type::op_none}, {"res 5,(hl)",disass_type::op_none}, {"res 5,a",disass_type::op_none}, {"res 6,b",disass_type::op_none}, {"res 6,c",disass_type::op_none}, {"res 6,d",disass_type::op_none}, {"res 6,e",disass_type::op_none}, {"res 6,h",disass_type::op_none}, {"res 6,l",disass_type::op_none}, {"res 6,(hl)",disass_type::op_none}, {"res 6,a",disass_type::op_none}, {"res 7,b",disass_type::op_none}, {"res 7,c",disass_type::op_none}, {"res 7,d",disass_type::op_none}, {"res 7,e",disass_type::op_none}, {"res 7,h",disass_type::op_none}, {"res 7,l",disass_type::op_none}, {"res 7,(hl)",disass_type::op_none}, {"res 7,a",disass_type::op_none}, {"set 0,b",disass_type::op_none}, {"set 0,c",disass_type::op_none}, {"set 0,d",disass_type::op_none}, {"set 0,e",disass_type::op_none}, {"set 0,h",disass_type::op_none}, {"set 0,l",disass_type::op_none}, {"set 0,(hl)",disass_type::op_none}, {"set 0,a",disass_type::op_none}, {"set 1,b",disass_type::op_none}, {"set 1,c",disass_type::op_none}, {"set 1,d",disass_type::op_none}, {"set 1,e",disass_type::op_none}, {"set 1,h",disass_type::op_none}, {"set 1,l",disass_type::op_none}, {"set 1,(hl)",disass_type::op_none}, {"set 1,a",disass_type::op_none}, {"set 2,b",disass_type::op_none}, {"set 2,c",disass_type::op_none}, {"set 2,d",disass_type::op_none}, {"set 2,e",disass_type::op_none}, {"set 2,h",disass_type::op_none}, {"set 2,l",disass_type::op_none}, {"set 2,(hl)",disass_type::op_none}, {"set 2,a",disass_type::op_none}, {"set 3,b",disass_type::op_none}, {"set 3,c",disass_type::op_none}, {"set 3,d",disass_type::op_none}, {"set 3,e",disass_type::op_none}, {"set 3,h",disass_type::op_none}, {"set 3,l",disass_type::op_none}, {"set 3,(hl)",disass_type::op_none}, {"set 3,a",disass_type::op_none}, {"set 4,b",disass_type::op_none}, {"set 4,c",disass_type::op_none}, {"set 4,d",disass_type::op_none}, {"set 4,e",disass_type::op_none}, {"set 4,h",disass_type::op_none}, {"set 4,l",disass_type::op_none}, {"set 4,(hl)",disass_type::op_none}, {"set 4,a",disass_type::op_none}, {"set 5,b",disass_type::op_none}, {"set 5,c",disass_type::op_none}, {"set 5,d",disass_type::op_none}, {"set 5,e",disass_type::op_none}, {"set 5,h",disass_type::op_none}, {"set 5,l",disass_type::op_none}, {"set 5,(hl)",disass_type::op_none}, {"set 5,a",disass_type::op_none}, {"set 6,b",disass_type::op_none}, {"set 6,c",disass_type::op_none}, {"set 6,d",disass_type::op_none}, {"set 6,e",disass_type::op_none}, {"set 6,h",disass_type::op_none}, {"set 6,l",disass_type::op_none}, {"set 6,(hl)",disass_type::op_none}, {"set 6,a",disass_type::op_none}, {"set 7,b",disass_type::op_none}, {"set 7,c",disass_type::op_none}, {"set 7,d",disass_type::op_none}, {"set 7,e",disass_type::op_none}, {"set 7,h",disass_type::op_none}, {"set 7,l",disass_type::op_none}, {"set 7,(hl)",disass_type::op_none}, {"set 7,a",disass_type::op_none} }; bool is_hex_literal(const std::string &str) { for(const auto &c: str) { if( !((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f')) ) { return false; } } return true; } void Disass::load_sym_file(const std::string name) { // for rom // vector of bank size of maps // addr -> string name // everywhere else // TODO: handle other banked areas eg sram sym_file_loaded = false; std::ifstream fp{name}; if(!fp) { return; } // resize our vector to house all our rom banks rom_sym_table.resize(mem.rom_info.no_rom_banks); std::string line; while(std::getline(fp,line)) { // empty line (we dont care) if(!line.size()) { continue; } // comment or section in file we dont care if(line[0] == ';' || line[0] == '[') { continue; } if(line.size() < 8) { printf("sym file line is not long enough: %s\n",line.c_str()); return; } // ok now just parse out the hard coded fields const auto bank_str = line.substr(0,2); if(!is_hex_literal(bank_str)) { printf("sym file invalid bank: %s\n",bank_str.c_str()); return; } const auto addr_str = line.substr(3,4); if(!is_hex_literal(addr_str)) { printf("sym file invalid addr: %s\n",addr_str.c_str()); return; } const auto sym = line.substr(8); const auto bank = std::stoi(bank_str,0,16); const auto addr = std::stoi(addr_str,0,16); // rom_access if(addr < 0x8000) { auto &m = rom_sym_table[bank]; m[addr] = sym; } else { // TODO: support sram, vram, wram memory banks mem_sym_table[addr] = sym; } } sym_file_loaded = true; } bool Disass::get_symbol(uint16_t addr,std::string &sym) { if(!sym_file_loaded) { return false; } if(addr < 0x8000) { // TODO: handle mbc1 funny banking const auto bank = addr < 0x4000 ? 0 : mem.cart_rom_bank; auto &m = rom_sym_table[bank]; if(m.count(addr)) { sym = m[addr]; return true; } else { return false; } } else { if(mem_sym_table.count(addr)) { sym = mem_sym_table[addr]; return true; } else { return false; } } } // not sure if its worth just adding a size field // and having a bunch of extra bytes in the exe uint32_t Disass::get_op_sz(uint16_t addr) noexcept { uint8_t opcode = mem.read_mem(addr++); bool is_cb = opcode == 0xcb; disass_type type = is_cb ? cb_opcode_table[mem.read_mem(addr)].type : opcode_table[opcode].type; int size = is_cb? 1 : 0; // 1 byte prefix for cb return size + disass_type_size[static_cast<int>(type)]; } std::string Disass::disass_op(uint16_t addr) noexcept { uint8_t opcode = mem.read_mem(addr++); if(opcode == 0xcb) { opcode = mem.read_mem(addr); Disass_entry entry = cb_opcode_table[opcode]; return std::string(entry.fmt_str); } else { Disass_entry entry = opcode_table[opcode]; switch(entry.type) { // eg jp case disass_type::op_u16: { const auto v = mem.read_word(addr); std::string symbol = ""; if(get_symbol(v,symbol)) { const auto str = fmt::format(entry.fmt_str,symbol); return fmt::format("{} ; {:x}",str,v); } else { return fmt::format(entry.fmt_str,fmt::format("{:x}",v)); } } // eg ld a, 0xff case disass_type::op_u8: { std::string symbol = ""; const auto v = mem.read_mem(addr); // ld a, (ff00+xx) if(opcode == 0xf0 && get_symbol(0xff00+v,symbol)) { return fmt::format("ld a, ({}) ; (ff00+{:x})",symbol,v); } // ld (0xff00+xx), a else if(opcode == 0xe0 && get_symbol(0xff00+v,symbol)) { return fmt::format("ld ({}), a ; (ff00+{:x})",symbol,v); } else { return fmt::format(entry.fmt_str,fmt::format("{:x}",v)); } } // eg jr case disass_type::op_i8: { const auto operand = static_cast<int8_t>(mem.read_mem(addr++)); const uint16_t v = addr+operand; std::string symbol = ""; if(get_symbol(v,symbol)) { const auto str = fmt::format(entry.fmt_str,symbol); return fmt::format("{} ; {:x}",str,v); } else { return fmt::format(entry.fmt_str,fmt::format("{:x}",v)); } } // eg ld a, b case disass_type::op_none: { return std::string(entry.fmt_str); } } } assert(false); return "disass_failed!?"; // should not be reached } }
33.08209
101
0.553199
destoer
2757f4c75b2b61df4a4ea1e4138293c4af2ba56e
1,131
cpp
C++
src/peptides/InfluenceRange.cpp
csam5596/Epi
e352e766bc3b522c7a02f83b4fe480e860c0f1db
[ "MIT" ]
null
null
null
src/peptides/InfluenceRange.cpp
csam5596/Epi
e352e766bc3b522c7a02f83b4fe480e860c0f1db
[ "MIT" ]
null
null
null
src/peptides/InfluenceRange.cpp
csam5596/Epi
e352e766bc3b522c7a02f83b4fe480e860c0f1db
[ "MIT" ]
null
null
null
#include "peptides/InfluenceRange.h" #include <iostream> InfluenceRange::InfluenceRange(const CodonChange &codonChange) : variantEffectId(codonChange.variantEffectId), veType(codonChange.veType){ unsigned offset = 0; while(codonChange.codonRef.size() > offset && codonChange.codonAlt.size() > offset && codonChange.codonRef.at(offset) == codonChange.codonAlt.at(offset)){ offset++; } // get index of first base that is different (0-based) firstStart = (codonChange.proteinPosition - 1) * 3 + offset; switch(veType){ case VariantEffect::SNV: case VariantEffect::INFRAME_DELETION: lastStart = firstStart; break; case VariantEffect::INFRAME_INSERTION: lastStart = firstStart + (codonChange.getShift() - 1); break; case VariantEffect::FRAMESHIFT_VARIANT: lastStart = std::numeric_limits<long>::max()/2; break; } } void InfluenceRange::shift(int amount) { firstStart += amount; if(veType != VariantEffect::FRAMESHIFT_VARIANT) lastStart += amount; } void InfluenceRange::convertPositions() { firstStart /= 3; if(veType != VariantEffect::FRAMESHIFT_VARIANT){ lastStart /= 3; } }
25.704545
76
0.727675
csam5596
275c57923a24c3caa25c73ab25bd9d2930cf31d2
23,961
cpp
C++
src/AST.cpp
Benjins/simple-vm
ef31ea36ad698a47da81642c97d718d3415bd133
[ "CC-BY-4.0" ]
null
null
null
src/AST.cpp
Benjins/simple-vm
ef31ea36ad698a47da81642c97d718d3415bd133
[ "CC-BY-4.0" ]
null
null
null
src/AST.cpp
Benjins/simple-vm
ef31ea36ad698a47da81642c97d718d3415bd133
[ "CC-BY-4.0" ]
null
null
null
#include "../header/AST.h" #include "../header/Instruction.h" #include "../header/VM.h" #include <algorithm> #include <stdio.h> #define FIND(container, item) std::find((container).begin(), (container).end(), (item)) Statement* CompileTokenToAST(const string& token){ const string operators = "+-*><|&=/"; if(operators.find(token) != string::npos){ return (Statement*)(new Operator(token)); } else{ return (Statement*)(new Builtin(token)); } } typedef string Token; struct TokenStream{ vector<Token> tokens; int cursor; AST* ast; map<string, Type> definedTypes; map<string, FuncDef*> definedFuncs; map<string, FuncDef*> builtinFuncs; int stackSizeInWords; map<string, Type> variables; map<string, int> varRegs; vector<string> binaryOps; vector<string> unaryOps; Stack<Scope*> scopes; bool ExpectAndEatToken(const string& keyWord){ if(tokens[cursor] == keyWord){ cursor++; return true; } return false; } bool ExpectAndEatUniqueName(){ if(definedFuncs.find(tokens[cursor]) == definedFuncs.end() && variables.find(tokens[cursor]) == variables.end()){ cursor++; return true; } return false; } bool ExpectAndEatVariable(){ if(variables.find(tokens[cursor]) != variables.end()){ cursor++; return true; } return false; } bool ExpectAndEatField(StructDef* structType, StructMember* out){ int oldCursor = cursor; for(auto& member : structType->members){ if(member.name == tokens[cursor]){ *out = member; cursor++; return true; } } cursor = oldCursor; return false; } bool ExpectAndEatAssignment(){ int oldCursor = cursor; bool isDeclaration = false; if(!ExpectAndEatVariable()){ cursor = oldCursor; if(!ExpectAndEatType()){ cursor = oldCursor; return false; } else{ if(!ExpectAndEatUniqueName()){ cursor = oldCursor; return false; } else{ const string& typeName = tokens[cursor-2]; const string& varName = tokens[cursor-1]; const Type& varType = definedTypes.find(typeName)->second; AddVariable(varType, varName); isDeclaration = true; } } } string varName = tokens[cursor-1]; Type varType = variables.find(varName)->second; StructDef* structDef = FindStructByName(varType.name); int offset = 0; if(!isDeclaration && structDef != nullptr){ while(structDef != nullptr){ if(ExpectAndEatToken(".")){ StructMember member; if(ExpectAndEatField(structDef, &member)){ offset += member.offset; const Type& fieldType = member.type; varType = fieldType; structDef = FindStructByName(fieldType.name); } } else{ break; } } } if(!ExpectAndEatToken("=")){ cursor = oldCursor; return false; } Value* val; if(!ExpectAndEatValue(&val)){ cursor = oldCursor; return false; } if(!ExpectAndEatToken(";")){ cursor = oldCursor; return false; } Assignment* assgn = new Assignment(); assgn->reg = varRegs.find(varName)->second + offset; assgn->varName = varName; assgn->varType = varType; assgn->val = val; scopes.Peek()->AddStatement(assgn); return true; } void AddVariable(const Type& type, const string& name){ varRegs.insert(std::make_pair(name, stackSizeInWords)); stackSizeInWords += type.sizeInWords; variables.insert(std::make_pair(name, type)); if(scopes.stackSize > 0){ scopes.Peek()->variablesInScope.insert(std::make_pair(name, type)); } } void RemoveVariable(const string& name){ auto variable = variables.find(name); stackSizeInWords -= variable->second.sizeInWords; variables.erase(variable); varRegs.erase(varRegs.find(name)); } bool ExpectAndEatNumber(VMValue* out){ if(ExpectAndConvertNumber(tokens[cursor], out)){ cursor++; return true; } return false; } bool ExpectAndConvertNumber(const string& token, VMValue* out){ static const string _digits = "0123456789"; if(_digits.find(token[0]) != string::npos){ if(out != nullptr){ if(token.find(".") != string::npos){ out->type = ValueType::FLOAT; out->floatValue = atof(token.c_str()); } else{ out->type = ValueType::INT; out->intValue = atoi(token.c_str()); } } return true; } return false; } bool EatFieldName(){ return true; } StructDef* FindStructByName(const string& name){ for(StructDef* astStructDef : ast->structDefs){ if(astStructDef->name == name){ return astStructDef; break; } } return nullptr; } bool ExpectAndEatValue(Value** out){ int oldCursor = cursor; vector<string> valueTokens; int parenCount = 0; //Bit of a hack so i can use JustShuntingYard() for(int index = cursor; index < tokens.size(); index++){ if(tokens[index] == "("){ parenCount++; } else if(tokens[index] == ")"){ parenCount--; } if(tokens[index] == ";" || parenCount < 0){ break; } valueTokens.push_back(tokens[index]); } vector<string> shuntedTokens = JustShuntingYard(valueTokens, definedFuncs, builtinFuncs); Stack<Value*> values; Stack<string> operatorStack; for(int index = 0; index < shuntedTokens.size(); index++){ const string& str = shuntedTokens[index]; VMValue val; if(ExpectAndConvertNumber(str, &val)){ //push num onto stack if(val.type == ValueType::INT){ values.Push(new Literal(val.intValue)); } else{ values.Push(new FloatLiteral(val.floatValue)); } } else if(FIND(binaryOps, str) != binaryOps.end()){ Operator* op = new Operator(str); op->right = values.Pop(); op->left = values.Pop(); values.Push(op); } else if(builtinFuncs.find(str) != builtinFuncs.end() ){ Builtin* builtin = new Builtin(str); FuncDef* def = builtinFuncs.find(str)->second; for(int i = 0; i < def->parameters.size(); i++){ if(values.stackSize == 0){ cout << "\n\nError, function '" << str << "' takes " << def->parameters.size() << " arguments.\n"; return false; } builtin->AddParameter(values.Pop()); } values.Push(builtin); } else if(definedFuncs.find(str) != definedFuncs.end()){ FuncCall* call = new FuncCall(); call->funcName = str; call->varCount = stackSizeInWords; FuncDef* def = definedFuncs.find(str)->second; call->def = def; for(int i = 0; i < def->parameters.size(); i++){ if(values.stackSize == 0){ cout << "\n\nError, function '" << str << "' takes " << def->parameters.size() << " arguments.\n"; return false; } call->AddParameter(values.Pop()); } values.Push(call); } else if(variables.find(str) != variables.end()){ Variable* var = new Variable(); var->varName = str; var->_reg = varRegs.find(str)->second; var->type = definedTypes.find(variables.find(str)->second.name)->second; values.Push(var); } else if(str == "."){ string fieldName = operatorStack.Pop(); Value* val = values.Pop(); Variable* var = dynamic_cast<Variable*>(val); if(var == nullptr){ cout << "\nError: using '.' on non-variable value.\n"; return false; } FieldAccess* fieldAccess = new FieldAccess(); fieldAccess->fieldName = fieldName; fieldAccess->variable = var; StructDef* def = FindStructByName(var->type.name); if(def == nullptr){ printf("\nError: Tried to use '.' operator on variable '%s' of type: '%s'\n", var->varName.c_str(), var->type.name.c_str()); break; } else{ for(auto& member : def->members){ if(member.name == fieldName){ fieldAccess->type = member.type; fieldAccess->offset = member.offset; values.Push(fieldAccess); break; } } } } else{ operatorStack.Push(str); } } if(values.stackSize == 1){ *out = values.Peek(); cursor += valueTokens.size(); return true; } else{ return false; } } bool ExpectAndEatVarDecl(){ int currentCursor = cursor; if(!ExpectAndEatType()){ cursor = currentCursor; return false; } const Type& declType = definedTypes.find(tokens[cursor-1])->second; if(!ExpectAndEatUniqueName()){ cursor = currentCursor; return false; } const string& uniqueName = tokens[cursor-1]; if(ExpectAndEatToken(";")){ AddVariable(declType, uniqueName); return true; } else if(ExpectAndEatToken("=")){ Value* val; if(ExpectAndEatValue(&val)){ AddVariable(declType, uniqueName); Assignment* assgn = new Assignment(); assgn->varName = uniqueName; assgn->varType = declType; assgn->reg = varRegs.find(uniqueName)->second; assgn->val = val; scopes.Peek()->AddStatement(assgn); return true; } else{ cursor = currentCursor; return false; } } else{ //ERROR? cursor = currentCursor; return false; } } bool ExpectAndEatFieldDecl(StructDef* def){ int currentCursor = cursor; if(!ExpectAndEatType()){ cursor = currentCursor; return false; } const Type& declType = definedTypes.find(tokens[cursor-1])->second; if(!ExpectAndEatUniqueName()){ cursor = currentCursor; return false; } const string& uniqueName = tokens[cursor-1]; if(ExpectAndEatToken(";")){ StructMember member; member.name = uniqueName; member.type = declType; member.offset = def->size; def->members.push_back(member); def->size += member.type.sizeInWords; return true; } return false; } bool ExpectAndEatStructDef(){ int oldCursor = cursor; if(!ExpectAndEatToken("struct")){ cursor = oldCursor; return false; } if(!ExpectAndEatUniqueName()){ cursor = oldCursor; return false; } if(!ExpectAndEatToken("{")){ cursor = oldCursor; return false; } StructDef* def = new StructDef(); def->name = tokens[cursor - 2]; while(tokens[cursor] != "}"){ if(!ExpectAndEatFieldDecl(def)){ cursor = oldCursor; delete def; return false; } } if(ExpectAndEatToken("}")){ if(ExpectAndEatToken(";")){ ast->structDefs.push_back(def); Type type = {def->name, def->size}; definedTypes.insert(std::make_pair(def->name, type)); return true; } } delete def; cursor = oldCursor; return false; } void Setup(){ Type intType = {"int", 1}; Type floatType = {"float", 1}; Type voidType = {"void", 0}; FuncDef* printDef = new FuncDef(); printDef->name = "PRINT"; printDef->retType.name = "void"; printDef->retType.sizeInWords = 0; printDef->parameters.insert(std::make_pair("val", intType)); FuncDef* printfDef = new FuncDef(); printfDef->name = "PRINTF"; printfDef->retType.name = "void"; printfDef->retType.sizeInWords = 0; printfDef->parameters.insert(std::make_pair("val", floatType)); FuncDef* readDef = new FuncDef(); readDef->name = "READ"; readDef->retType.name = "int"; readDef->retType.sizeInWords = 1; FuncDef* readfDef = new FuncDef(); readfDef->name = "READF"; readfDef->retType.name = "float"; readfDef->retType.sizeInWords = 1; FuncDef* ftoiDef = new FuncDef(); ftoiDef->name = "PRINTF"; ftoiDef->retType.name = "int"; ftoiDef->retType.sizeInWords = 1; ftoiDef->parameters.insert(std::make_pair("val", floatType)); builtinFuncs.insert(std::make_pair("PRINT", printDef)); builtinFuncs.insert(std::make_pair("PRINTF", printfDef)); builtinFuncs.insert(std::make_pair("READ", readDef)); builtinFuncs.insert(std::make_pair("READF", readfDef)); builtinFuncs.insert(std::make_pair("ftoi", ftoiDef)); definedTypes.insert(std::make_pair("int", intType)); definedTypes.insert(std::make_pair("float", floatType)); definedTypes.insert(std::make_pair("void", voidType)); binaryOps.push_back("+"); binaryOps.push_back("-"); binaryOps.push_back("/"); binaryOps.push_back("*"); binaryOps.push_back("&"); binaryOps.push_back("|"); binaryOps.push_back("=="); binaryOps.push_back(">"); binaryOps.push_back("<"); //unaryOps.push_back("!"); stackSizeInWords = 0; ast = new AST(); } bool ExpectAndEatType(){ if(definedTypes.find(tokens[cursor]) != definedTypes.end()){ cursor++; return true; } } bool ExpectAndEatParameter(){ int oldCursor = cursor; if(!ExpectAndEatType()){ cursor = oldCursor; return false; } if(!ExpectAndEatUniqueName()){ cursor = oldCursor; return false; } return true; } bool ExpectAndEatControlStatement(); bool ExpectAndEatStatement(){ int oldCursor = cursor; if(ExpectAndEatType()){ if(ExpectAndEatUniqueName()){ if(ExpectAndEatToken(";")){ const string& typeName = tokens[cursor - 3]; const string& varName = tokens[cursor - 2]; const Type& varType = definedTypes.find(typeName)->second; AddVariable(varType, varName); return true; } } } cursor = oldCursor; if(ExpectAndEatToken("return")){ Value* val; if(ExpectAndEatValue(&val)){ if(ExpectAndEatToken(";")){ Builtin* builtin = new Builtin("return"); builtin->AddParameter(val); scopes.Peek()->AddStatement(builtin); return true; } else{ delete val; cursor = oldCursor; return false; } } else{ cursor = oldCursor; return false; } } if(ExpectAndEatControlStatement()){ return true; } if(ExpectAndEatAssignment()){ return true; } Value* val; if(ExpectAndEatValue(&val)){ if(ExpectAndEatToken(";")){ scopes.Peek()->AddStatement(val); return true; } else{ delete val; cursor = oldCursor; return false; } } cursor = oldCursor; return false; } bool ExpectAndEatFunctionDef(){ int oldCursor = cursor; if(!ExpectAndEatType()){ cursor = oldCursor; return false; } const string& retTypeName = tokens[cursor - 1]; if(!ExpectAndEatUniqueName()){ cursor = oldCursor; return false; } const string& funcName = tokens[cursor - 1]; if(!ExpectAndEatToken("(")){ cursor = oldCursor; return false; } FuncDef* def = new FuncDef(); const Type& retType = definedTypes.find(retTypeName)->second; def->retType = retType; def->name = funcName; scopes.Push(def); int paramCount = 0; while(tokens[cursor] != ")"){ if(paramCount != 0){ if(!ExpectAndEatToken(",")){ delete def; scopes.Pop(); cursor = oldCursor; return false; } } if(!ExpectAndEatParameter()){ delete def; cursor = oldCursor; return false; } const string& paramTypeName = tokens[cursor - 2]; const string& paramName = tokens[cursor - 1]; const Type& paramType = definedTypes.find(paramTypeName)->second; AddVariable(paramType, paramName); def->parameters.insert(std::make_pair(paramName, paramType)); paramCount++; } if(!ExpectAndEatToken(")")){ delete def; cursor = oldCursor; return false; } if(!ExpectAndEatToken("{")){ delete def; cursor = oldCursor; return false; } ast->defs.push_back(def); definedFuncs.insert(std::make_pair(funcName, def)); while(tokens[cursor] != "}"){ if(!ExpectAndEatStatement()){ definedFuncs.erase(definedFuncs.find(funcName)); ast->defs.erase(FIND(ast->defs, def)); delete def; cursor = oldCursor; return false; } } if(!ExpectAndEatToken("}")){ definedFuncs.erase(definedFuncs.find(funcName)); ast->defs.erase(FIND(ast->defs, def)); delete def; cursor = oldCursor; return false; } scopes.Pop(); for(const auto& variableInScope : def->variablesInScope){ RemoveVariable(variableInScope.first); } return true; } AST* ParseAST(){ Setup(); while(cursor < tokens.size()){ if(ExpectAndEatStructDef()){ } else if(ExpectAndEatVarDecl()){ } else if(ExpectAndEatFunctionDef()){ } else{ cout << "\nError: could not parse: '" << tokens[cursor]<< "'\n"; break; } } return ast; } }; bool TokenStream::ExpectAndEatControlStatement(){ bool isWhile = false; int oldCursor = cursor; if(ExpectAndEatToken("if")){ isWhile = false; } else if(ExpectAndEatToken("while")){ isWhile = true; } else{ cursor = oldCursor; return false; } if(!ExpectAndEatToken("(")){ cursor = oldCursor; return false; } Value* val; if(!ExpectAndEatValue(&val)){ cursor = oldCursor; return false; } if(!ExpectAndEatToken(")")){ delete val; cursor = oldCursor; return false; } if(!ExpectAndEatToken("{")){ delete val; cursor = oldCursor; return false; } IfStatement* ifStmt; if(isWhile){ ifStmt = new WhileStatement(); } else{ ifStmt = new IfStatement(); } scopes.Peek()->AddStatement(ifStmt); scopes.Push(ifStmt); while(tokens[cursor] != "}"){ if(!ExpectAndEatStatement()){ delete ifStmt; cursor = oldCursor; return false; } } if(!ExpectAndEatToken("}")){ delete val; delete ifStmt; cursor = oldCursor; return false; } scopes.Pop(); for(const auto& variableInScope : ifStmt->variablesInScope){ RemoveVariable(variableInScope.first); } ifStmt->test = val; return true; } AST* MakeASTFromTokens(const vector<string>& tokens){ TokenStream stream; stream.tokens = tokens; stream.cursor = 0; return stream.ParseAST(); } void AST::GenerateByteCode(VM& vm){ vm.funcPointers.clear(); vm.byteCodeLoaded.clear(); for(int i = 0; i < defs.size(); i++){ vm.funcPointers.insert(std::pair<string, int>(defs[i]->name, vm.byteCodeLoaded.size())); FuncDef* def = defs[i]; defs[i]->AddByteCode(vm); } } bool AST::TypeCheck(){ for(FuncDef* def : defs){ if(!def->TypeCheck()){ return false; } } return true; } int FuncCall::Evaluate(){ return -1; } bool FuncCall::TypeCheck(){ if(currParams == def->parameters.size()){ bool paramCheck = true; for(int i = 0; i < currParams; i++){ paramCheck &= parameterVals[i]->TypeCheck(); } if(paramCheck){ int idx = 0; for(auto& pair : def->parameters){ paramCheck &= parameterVals[idx]->type.name == pair.second.name; idx++; } if(paramCheck){ type = def->retType; return true; } } } return false; } void FuncCall::AddByteCode(VM& vm){ vm.byteCodeLoaded.push_back(STK_FRAME); //Stack frame? vm.byteCodeLoaded.push_back(INT_DLIT); int retAddrIdx = vm.byteCodeLoaded.size(); vm.byteCodeLoaded.push_back(253); vm.byteCodeLoaded.push_back(253); //Return Addr, which isn't yet known for(int i = 0; i < currParams; i++){ parameterVals[i]->AddByteCode(vm); } int funcAddr = vm.funcPointers.find(funcName)->second; Literal(varCount).AddByteCode(vm); Literal(funcAddr).AddByteCode(vm); vm.byteCodeLoaded.push_back(CALL); vm.byteCodeLoaded[retAddrIdx] = vm.byteCodeLoaded.size() / 256; vm.byteCodeLoaded[retAddrIdx+1] = vm.byteCodeLoaded.size() % 256; } int Builtin::Evaluate(){ return -1; } void Builtin::AddByteCode(VM& vm){ for(int i = 0; i < numParams; i++){ parameterVals[i]->AddByteCode(vm); } if(funcName == "PRINT"){ vm.byteCodeLoaded.push_back(PRINT); } else if(funcName == "PRINTF"){ vm.byteCodeLoaded.push_back(PRINTF); } else if(funcName == "READ"){ vm.byteCodeLoaded.push_back(READ); } else if(funcName == "READF"){ vm.byteCodeLoaded.push_back(READF); } else if(funcName == "return"){ int size = parameterVals[0]->type.sizeInWords; Literal(size).AddByteCode(vm); vm.byteCodeLoaded.push_back(RETURN); } else if(funcName == "itof"){ vm.byteCodeLoaded.push_back(INT_TO_FLT); } } int Assignment::Evaluate(){ return -1; } void Assignment::AddByteCode(VM& vm){ val->AddByteCode(vm); for(int i = 0; i < type.sizeInWords; i++){ //PARAM is used because we need the register to be above the value. //In other words, SAVE_REG will either be phased out, or PARAM will be renamed SAVE_REG, //and the two will be merged. Literal(reg+i).AddByteCode(vm); vm.byteCodeLoaded.push_back(PARAM); } } int Literal::Evaluate(){ return value; } void Literal::AddByteCode(VM& vm){ if(value < 256){ vm.byteCodeLoaded.push_back(INT_LIT); vm.byteCodeLoaded.push_back(value); } else if(value < (1 << 16)){ vm.byteCodeLoaded.push_back(INT_DLIT); vm.byteCodeLoaded.push_back(value / 256); vm.byteCodeLoaded.push_back(value % 256); } else{ const int thirdByte = 1 << 16; const int fourthByte = 1 << 24; vm.byteCodeLoaded.push_back(INT_QLIT); vm.byteCodeLoaded.push_back(value / fourthByte); vm.byteCodeLoaded.push_back((value % fourthByte) / thirdByte); vm.byteCodeLoaded.push_back((value % thirdByte) / 256); vm.byteCodeLoaded.push_back(value % 256); } } void FloatLiteral::AddByteCode(VM& vm){ unsigned char* castPtr = (unsigned char*)&value; vm.byteCodeLoaded.push_back(FLT_LIT); for(int i = 0; i < 4; i++){ vm.byteCodeLoaded.push_back(castPtr[i]); } } int Variable::Evaluate(){ return -1; } void Variable::AddByteCode(VM& vm){ for(int i = type.sizeInWords - 1; i >= 0; i--){ int reg = GetRegister() + i; Literal(reg).AddByteCode(vm); vm.byteCodeLoaded.push_back(LOAD_REG); } } int Operator::Evaluate(){ return -1; } void Operator::AddByteCode(VM& vm){ left->AddByteCode(vm); right->AddByteCode(vm); vm.byteCodeLoaded.push_back(instr); } bool Operator::TypeCheck(){ bool leftIsGood = left->TypeCheck(); bool rightIsGood = right->TypeCheck(); if(leftIsGood && rightIsGood){ if(left->type.name == right->type.name){ if(instr == L_THAN || instr == G_THAN || instr == COMPARE){ type.name = "int"; type.sizeInWords = 1; } else{ type = left->type; } return true; } } return false; } int Scope::Evaluate(){ return -1; } void Scope::AddByteCode(VM& vm){ for(int i = 0; i < numStatements; i++){ statements[i]->AddByteCode(vm); } } int FuncDef::Evaluate(){ return -1; } void FuncDef::AddByteCode(VM& vm){ if(!isExtern){ int totalSize = 0; for(auto& pair : parameters){ totalSize += pair.second.sizeInWords; } for(int regIdx = 0; regIdx < totalSize; regIdx++){ Literal(regIdx).AddByteCode(vm); vm.byteCodeLoaded.push_back(PARAM); } for(int i = 0; i < numStatements; i++){ statements[i]->AddByteCode(vm); } } } int ExternFunc::Evaluate(){ return -1; } void ExternFunc::AddByteCode(VM& vm){ int index = -1; for(int i = 0; i < vm.externFuncNames.size(); i++){ if(vm.externFuncNames[i] == funcName){ index = i; break; } } if(index == -1){ cout << "Could not find extern function with the name '" << funcName << "'\n"; } else{ if(numParams != 1){ cout << "For now, number of params for extern must be 1.\n"; } parameterVals[0]->AddByteCode(vm); vm.byteCodeLoaded.push_back(INT_LIT); vm.byteCodeLoaded.push_back(index); vm.byteCodeLoaded.push_back(EXTERN_CALL); } } int IfStatement::Evaluate(){ return -1; } void IfStatement::AddByteCode(VM& vm){ test->AddByteCode(vm); vm.byteCodeLoaded.push_back(INT_DLIT); int jumpAddrIdx = vm.byteCodeLoaded.size(); vm.byteCodeLoaded.push_back(253); vm.byteCodeLoaded.push_back(253); vm.byteCodeLoaded.push_back(BRANCH); for(int i = 0; i < numStatements; i++){ statements[i]->AddByteCode(vm); } vm.byteCodeLoaded[jumpAddrIdx] = vm.byteCodeLoaded.size() / 256; vm.byteCodeLoaded[jumpAddrIdx+1] = vm.byteCodeLoaded.size() % 256; } int WhileStatement::Evaluate(){ return -1; } void WhileStatement::AddByteCode(VM& vm){ int recurAddrIdx = vm.byteCodeLoaded.size(); test->AddByteCode(vm); vm.byteCodeLoaded.push_back(INT_DLIT); int jumpAddrIdx = vm.byteCodeLoaded.size(); vm.byteCodeLoaded.push_back(253); vm.byteCodeLoaded.push_back(253); vm.byteCodeLoaded.push_back(BRANCH); for(int i = 0; i < numStatements; i++){ statements[i]->AddByteCode(vm); } vm.byteCodeLoaded.push_back(INT_LIT); vm.byteCodeLoaded.push_back(0); vm.byteCodeLoaded.push_back(INT_DLIT); vm.byteCodeLoaded.push_back(recurAddrIdx / 256); vm.byteCodeLoaded.push_back(recurAddrIdx % 256); vm.byteCodeLoaded.push_back(BRANCH); vm.byteCodeLoaded[jumpAddrIdx] = vm.byteCodeLoaded.size() / 256; vm.byteCodeLoaded[jumpAddrIdx+1] = vm.byteCodeLoaded.size() % 256; }
21.528302
129
0.651642
Benjins
276565448f990df77c4985fed6c468a4721dfe14
7,093
cpp
C++
src/engine/ivp/havana/havok/hk_base/memory/memory.cpp
cstom4994/SourceEngineRebuild
edfd7f8ce8af13e9d23586318350319a2e193c08
[ "MIT" ]
6
2022-01-23T09:40:33.000Z
2022-03-20T20:53:25.000Z
src/engine/ivp/havana/havok/hk_base/memory/memory.cpp
cstom4994/SourceEngineRebuild
edfd7f8ce8af13e9d23586318350319a2e193c08
[ "MIT" ]
null
null
null
src/engine/ivp/havana/havok/hk_base/memory/memory.cpp
cstom4994/SourceEngineRebuild
edfd7f8ce8af13e9d23586318350319a2e193c08
[ "MIT" ]
1
2022-02-06T21:05:23.000Z
2022-02-06T21:05:23.000Z
#include <hk_base/base.h> #include <malloc.h> class hk_Memory_With_Size { public: hk_int32 m_size; enum { MAGIC_MEMORY_WITH_SIZE = 0x2345656 } m_magic; hk_int32 m_dummy[2]; }; void hk_Memory::init_memory(char *buffer, int buffer_size) { m_memory_start = buffer; m_used_end = buffer; m_memory_end = m_used_end + buffer_size; m_allocated_memory_blocks = HK_NULL; for (int i = HK_MEMORY_MAX_ROW - 1; i >= 0; i--) { m_free_list[i] = HK_NULL; m_blocks_in_use[i] = 0; } for (int j = 0; j <= HK_MEMORY_MAX_SIZE_SMALL_BLOCK; j++) { int row = size_to_row(j); m_size_to_row[j] = row; m_row_to_size[row] = j; } { // statistics for (int i = 0; i < HK_MEMORY_CLASS_MAX; i++) { hk_Memory_Statistics &s = m_statistics[i]; s.m_max_size_in_use = 0; s.m_size_in_use = 0; s.m_n_allocates = 0; s.m_blocks_in_use = 0; } } } hk_Memory::hk_Memory() { #ifdef HK_MEMORY_POOL_INITIAL_SIZE init_memory( new char[HK_MEMORY_POOL_INITIAL_SIZE], 0 ); #else init_memory(HK_NULL, 0); #endif } hk_Memory::hk_Memory(char *buffer, int buffer_size) { init_memory(buffer, buffer_size); } hk_Memory::~hk_Memory() { //[XXX this does not work in havok since global arrays // may be destructed after this has been called :( //while ( m_allocated_memory_blocks ){ // hk_Memory_Block *b = m_allocated_memory_blocks; // m_allocated_memory_blocks = m_allocated_memory_blocks->m_next; // hk_Memory::aligned_free( (void *)b ); //} //] } void *hk_Memory::allocate_real(int size) { if (size > HK_MEMORY_MAX_SIZE_SMALL_BLOCK) { #ifdef HK_CHECK hk_Console::get_instance()->printf("big block allocated size %i\n", size); #endif return hk_Memory::aligned_malloc(size, HK_MEMORY_CACHE_ALIGNMENT); } int row = m_size_to_row[size]; size = m_row_to_size[row]; int allocated_size = size; void *result; // allocate first block if (size + m_used_end > m_memory_end) { #ifdef HK_CHECK hk_Console::get_instance()->printf("running out of space: block size %i\n", size); #endif hk_Memory_Block *b = (hk_Memory_Block *) hk_Memory::aligned_malloc( sizeof(hk_Memory_Block) + HK_MEMORY_EXTRA_BLOCK_SIZE, HK_MEMORY_CACHE_ALIGNMENT); b->m_next = m_allocated_memory_blocks; m_allocated_memory_blocks = b; m_memory_start = (char *) (b + 1); m_used_end = m_memory_start; m_memory_end = m_used_end + HK_MEMORY_EXTRA_BLOCK_SIZE; } result = (void *) m_used_end; hk_Memory_Elem *el = (hk_Memory_Elem *) m_used_end; el->m_magic = 0; m_used_end += size; // allocate rest to get make sure the alignment is ok int biu = m_blocks_in_use[row]; while (allocated_size < 256) { if (size + m_used_end < m_memory_end) { hk_Memory_Elem *el = (hk_Memory_Elem *) m_used_end; el->m_magic = 0; this->deallocate(m_used_end, size, HK_MEMORY_CLASS_DUMMY); m_used_end += size; } else { break; } allocated_size += size; } m_blocks_in_use[row] = biu; return result; } void *hk_Memory::allocate(int size, hk_MEMORY_CLASS cl) { #ifdef HK_MEMORY_ENABLE_STATISTICS hk_Memory_Statistics &s = m_statistics[cl]; s.m_size_in_use += size; s.m_blocks_in_use += 1; s.m_n_allocates += 1; if (s.m_size_in_use > s.m_max_size_in_use) { s.m_max_size_in_use = s.m_size_in_use; } #endif #ifdef HK_MEMORY_ENABLE_DEBUG_CHECK hk_Memory_With_Size *x = (hk_Memory_With_Size *)this->hk_Memory::aligned_malloc( size + sizeof( hk_Memory_With_Size ), HK_MEMORY_CACHE_ALIGNMENT ); x->m_size = size; x->m_magic = hk_Memory_With_Size::MAGIC_MEMORY_WITH_SIZE; return (void *)(x+1); #else if (size <= HK_MEMORY_MAX_SIZE_SMALL_BLOCK) { int row = m_size_to_row[size]; m_blocks_in_use[row]++; hk_Memory_Elem *n = m_free_list[row]; if (n) { m_free_list[row] = n->m_next; n->m_magic = 0; return (void *) n; } } return allocate_real(size); #endif } void hk_Memory::deallocate(void *p, int size, hk_MEMORY_CLASS cl) { #ifdef HK_MEMORY_ENABLE_STATISTICS hk_Memory_Statistics &s = m_statistics[cl]; s.m_size_in_use -= size; s.m_blocks_in_use -= 1; #endif #ifdef HK_MEMORY_ENABLE_DEBUG_CHECK { hk_Memory_With_Size *x = (hk_Memory_With_Size *)p; x--; HK_ASSERT( x->m_magic == hk_Memory_With_Size::MAGIC_MEMORY_WITH_SIZE ); HK_ASSERT( x->m_size == size ); this->aligned_free( x ); } #else if (size <= HK_MEMORY_MAX_SIZE_SMALL_BLOCK) { hk_Memory_Elem *me = (hk_Memory_Elem *) p; int row = m_size_to_row[size]; m_blocks_in_use[row]--; me->m_next = m_free_list[row]; HK_ASSERT(me->m_magic != HK_MEMORY_MAGIC_NUMBER); me->m_magic = HK_MEMORY_MAGIC_NUMBER; m_free_list[row] = me; } else { hk_Memory::aligned_free((char *) p); } #endif } int hk_Memory::size_to_row(int size) { HK_ASSERT (HK_MEMORY_MAX_ROW == 12); if (size <= 8) return 1; else if (size <= 16) return 2; else if (size <= 32) return 3; else if (size <= 48) return 4; else if (size <= 64) return 5; else if (size <= 96) return 6; else if (size <= 128) return 7; else if (size <= 160) return 8; else if (size <= 192) return 9; else if (size <= 256) return 10; else if (size <= 512) return 11; else { HK_BREAK; return -1; } } void *hk_Memory::allocate_debug(int n, const char * /*file*/, int /*line*/) { return new char[n]; } void hk_Memory::deallocate_debug( void *p, int /*n*/, const char * /*file*/, int /*line*/) { delete[] static_cast<char *>(p); } void *hk_Memory::allocate_and_store_size(int byte_size, hk_MEMORY_CLASS cl) { hk_Memory_With_Size *x = (hk_Memory_With_Size *) this->allocate(byte_size + sizeof(hk_Memory_With_Size), cl); x->m_size = byte_size; x->m_magic = hk_Memory_With_Size::MAGIC_MEMORY_WITH_SIZE; return (void *) (x + 1); } void hk_Memory::deallocate_stored_size(void *p, hk_MEMORY_CLASS cl) { if (p) { hk_Memory_With_Size *x = (hk_Memory_With_Size *) p; x--; HK_ASSERT(x->m_magic == hk_Memory_With_Size::MAGIC_MEMORY_WITH_SIZE); this->deallocate(x, x->m_size + sizeof(hk_Memory_With_Size), cl); } } void *hk_Memory::aligned_malloc(hk_size_t size, hk_size_t alignment) { #if defined(WIN32_) return _aligned_malloc ( size, alignment ); #else return ::malloc(size); #endif } void hk_Memory::aligned_free(void *data) { #if defined(WIN32_) _aligned_free ( data ); #else ::free(data); #endif } hk_Memory *hk_Memory::get_instance() { static hk_Memory s_memory_instance; return &s_memory_instance; }
26.27037
151
0.629071
cstom4994
276c5a2a3a057c08c964e28c37d98dd6eea6646e
5,102
hpp
C++
include/System/Data/ValueType.hpp
v0idp/virtuoso-codegen
6f560f04822c67f092d438a3f484249072c1d21d
[ "Unlicense" ]
null
null
null
include/System/Data/ValueType.hpp
v0idp/virtuoso-codegen
6f560f04822c67f092d438a3f484249072c1d21d
[ "Unlicense" ]
null
null
null
include/System/Data/ValueType.hpp
v0idp/virtuoso-codegen
6f560f04822c67f092d438a3f484249072c1d21d
[ "Unlicense" ]
1
2022-03-30T21:07:35.000Z
2022-03-30T21:07:35.000Z
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "beatsaber-hook/shared/utils/typedefs.h" #include "beatsaber-hook/shared/utils/byref.hpp" // Including type: System.Enum #include "System/Enum.hpp" // Completed includes // Type namespace: System.Data namespace System::Data { // Forward declaring type: ValueType struct ValueType; } #include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp" DEFINE_IL2CPP_ARG_TYPE(::System::Data::ValueType, "System.Data", "ValueType"); // Type namespace: System.Data namespace System::Data { // Size: 0x4 #pragma pack(push, 1) // Autogenerated type: System.Data.ValueType // [TokenAttribute] Offset: FFFFFFFF struct ValueType/*, public ::System::Enum*/ { public: public: // public System.Int32 value__ // Size: 0x4 // Offset: 0x0 int value; // Field size check static_assert(sizeof(int) == 0x4); public: // Creating value type constructor for type: ValueType constexpr ValueType(int value_ = {}) noexcept : value{value_} {} // Creating interface conversion operator: operator ::System::Enum operator ::System::Enum() noexcept { return *reinterpret_cast<::System::Enum*>(this); } // Creating conversion operator: operator int constexpr operator int() const noexcept { return value; } // static field const value: static public System.Data.ValueType Unknown static constexpr const int Unknown = -1; // Get static field: static public System.Data.ValueType Unknown static ::System::Data::ValueType _get_Unknown(); // Set static field: static public System.Data.ValueType Unknown static void _set_Unknown(::System::Data::ValueType value); // static field const value: static public System.Data.ValueType Null static constexpr const int Null = 0; // Get static field: static public System.Data.ValueType Null static ::System::Data::ValueType _get_Null(); // Set static field: static public System.Data.ValueType Null static void _set_Null(::System::Data::ValueType value); // static field const value: static public System.Data.ValueType Bool static constexpr const int Bool = 1; // Get static field: static public System.Data.ValueType Bool static ::System::Data::ValueType _get_Bool(); // Set static field: static public System.Data.ValueType Bool static void _set_Bool(::System::Data::ValueType value); // static field const value: static public System.Data.ValueType Numeric static constexpr const int Numeric = 2; // Get static field: static public System.Data.ValueType Numeric static ::System::Data::ValueType _get_Numeric(); // Set static field: static public System.Data.ValueType Numeric static void _set_Numeric(::System::Data::ValueType value); // static field const value: static public System.Data.ValueType Str static constexpr const int Str = 3; // Get static field: static public System.Data.ValueType Str static ::System::Data::ValueType _get_Str(); // Set static field: static public System.Data.ValueType Str static void _set_Str(::System::Data::ValueType value); // static field const value: static public System.Data.ValueType Float static constexpr const int Float = 4; // Get static field: static public System.Data.ValueType Float static ::System::Data::ValueType _get_Float(); // Set static field: static public System.Data.ValueType Float static void _set_Float(::System::Data::ValueType value); // static field const value: static public System.Data.ValueType Decimal static constexpr const int Decimal = 5; // Get static field: static public System.Data.ValueType Decimal static ::System::Data::ValueType _get_Decimal(); // Set static field: static public System.Data.ValueType Decimal static void _set_Decimal(::System::Data::ValueType value); // static field const value: static public System.Data.ValueType Object static constexpr const int Object = 6; // Get static field: static public System.Data.ValueType Object static ::System::Data::ValueType _get_Object(); // Set static field: static public System.Data.ValueType Object static void _set_Object(::System::Data::ValueType value); // static field const value: static public System.Data.ValueType Date static constexpr const int Date = 7; // Get static field: static public System.Data.ValueType Date static ::System::Data::ValueType _get_Date(); // Set static field: static public System.Data.ValueType Date static void _set_Date(::System::Data::ValueType value); // Get instance field reference: public System.Int32 value__ [[deprecated("Use field access instead!")]] int& dyn_value__(); }; // System.Data.ValueType #pragma pack(pop) static check_size<sizeof(ValueType), 0 + sizeof(int)> __System_Data_ValueTypeSizeCheck; static_assert(sizeof(ValueType) == 0x4); } #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
48.132075
89
0.712074
v0idp
276f1f587049258200919ee6d084a75f3eb8b027
740
cpp
C++
kuangbin/hdu-1257.cpp
Broduker/oj
b114434df5627c79a646e076a034a0ecc4c7484c
[ "MIT" ]
null
null
null
kuangbin/hdu-1257.cpp
Broduker/oj
b114434df5627c79a646e076a034a0ecc4c7484c
[ "MIT" ]
null
null
null
kuangbin/hdu-1257.cpp
Broduker/oj
b114434df5627c79a646e076a034a0ecc4c7484c
[ "MIT" ]
null
null
null
/* translation: 求最长上升子序列 solution: 经典dp dp[i] = max(dp[i],dp[k]) k:1~i-1 && seq[k]<seq[i]   note: dp[i]初始化为1 date: 2019.08 */ #include <iostream> #include <cstdio> #include <algorithm> #include <cstring> const int MAXN = 30010; int seq[MAXN],dp[MAXN]; using namespace std; int main(){ int n,ans; while(~scanf("%d",&n) && n){ ans = 0; for(int i=1;i<=n;i++){ scanf("%d",&seq[i]); } for(int i=1;i<=n;i++){ dp[i]=1; for(int j=1;j<i;j++){ if(seq[j]<seq[i]){ dp[i] = max(dp[i],dp[j]+1); } } ans=max(ans,dp[i]); } printf("%d\n", ans); } return 0; }
17.619048
53
0.427027
Broduker
27738c3f87e4ddb9851c4797302deea0e3ad4f85
1,889
cpp
C++
test/craps_test.cpp
acc-cosc-1337-spring-2021/acc-spring-2021-final-Hannah-Kim-acc
b710e32b11c29516cbe6c1cf16f89a57bbfd62e2
[ "MIT" ]
null
null
null
test/craps_test.cpp
acc-cosc-1337-spring-2021/acc-spring-2021-final-Hannah-Kim-acc
b710e32b11c29516cbe6c1cf16f89a57bbfd62e2
[ "MIT" ]
null
null
null
test/craps_test.cpp
acc-cosc-1337-spring-2021/acc-spring-2021-final-Hannah-Kim-acc
b710e32b11c29516cbe6c1cf16f89a57bbfd62e2
[ "MIT" ]
null
null
null
#define CATCH_CONFIG_MAIN // This tells Catch to provide a main() - only do this in one cpp file #include "catch.hpp" #include "die.h" #include "roll.h" #include "shooter.h" #include "come_out_phase.h" #include "point_phase.h" TEST_CASE("Verify Test Configuration", "verification") { REQUIRE(true == true); } TEST_CASE("assert die rolls return a value from 1 to 6") { Die die; for (int i = 0; i<10;i++) { die.roll(); REQUIRE(die.rolled_value() < 7); REQUIRE(die.rolled_value() > 0); } } TEST_CASE("assert die rolls return a value from 2 to 12") { Die d1; Die d2; Roll roll(d1, d2); for (int i = 0; i<10;i++) { roll.roll_die(); REQUIRE(roll.roll_value() <= 12); REQUIRE(roll.roll_value() >= 2); } } TEST_CASE("Test that shooter returns a Roll","verify that the roll result has one of the following values: 2-12") { Shooter shooter; Die d1; Die d2; for (int i = 0; i<10;i++) { Roll* roll = shooter.throw_die(d1, d2); REQUIRE(roll->roll_value() <= 12); REQUIRE(roll->roll_value() >= 2); } } TEST_CASE("Test that ComeOutPhase get outcomes returns values RollOutcome::natural, RollOutcome::craps, and RollOutcome::point",,"Test that PointPhase get outcomes returns values RollOutcome::point, RollOutcome::seven_out, and RollOutcome::nopoint ") { Phase* come_out_phase = new ComeOutPhase(); Phase* point_phase = new PointPhase(5); Die d1; Die d2; Roll* roll = new Roll(d1, d2); for (int i = 0; i<10;i++) { RollOutcome come_out_phase_outcome = come_out_phase->get_outcome(roll); RollOutcome point_phase_outcome = point_phase->get_outcome(roll); REQUIRE(come_out_phase_outcome != RollOutcome::nopoint); REQUIRE(come_out_phase_outcome != RollOutcome::seven_out); REQUIRE(point_phase_outcome != RollOutcome::natural); REQUIRE(point_phase_outcome != RollOutcome::craps); } }
26.236111
251
0.678666
acc-cosc-1337-spring-2021
277769b6a0c13366d0471b9ca93017811c07a88b
2,403
cpp
C++
customer.cpp
Rajasuryaa/seven
87a7e1aa801fa330deb585ba859a09da56c22e90
[ "curl" ]
null
null
null
customer.cpp
Rajasuryaa/seven
87a7e1aa801fa330deb585ba859a09da56c22e90
[ "curl" ]
null
null
null
customer.cpp
Rajasuryaa/seven
87a7e1aa801fa330deb585ba859a09da56c22e90
[ "curl" ]
null
null
null
#include <iostream> #include <string.h> #include <fstream> #include <stdlib.h> using namespace std; struct user_details { char name[30]; char email_id[30]; char mobile_no[11]; char doorno[5]; char street_name[30],dummy[2]; char area[20]; unsigned int pin_code; char username[15]; char password[20]; }; char tmp_username[15]; char tmp_password[20]; void get_user_details(struct user_details *user) { cout<<"\tRegistration Form"<<endl; /* cout<<"Name :"; cin.getline(user->name,20,'\n'); cout<<"Email :"; cin>>user->email_id; cin.getline(user->dummy,3,'\n'); cout<<"Mobile :"; cin>>user->mobile_no; cout<<"Door No :"; cin>>user->doorno; cin.getline(user->dummy,1,'\n'); cout<<"Street :"; cin.getline(user->street_name,30,'\n'); cout<<"Area :"; cin.getline(user->area,20,'\n');; cout<<"Pincode :"; cin>>user->pin_code; cout<<"\n\n\tSet Username and Password"; */ cout<<"\nUSERNAME : "; cin>>user->username; cout<<"PASSWORD : "; cin>>user->password; ofstream file ("user.bin", ios::app | ios::binary); file.write((char *)&user,sizeof(user)); file.close(); } void login_form(struct user_details user) { int success; success = 0; system("CLS"); cout<<"USERNAME : "; cin>>tmp_username; cout<<"PASSWORD : "; cin>>tmp_password; ifstream f; f.open("user.bin",ios::in|ios::binary); f.seekg(0); while(f.read((char*)&user,sizeof(user))) { if(strcmp(tmp_username,user.username)==0 && strcmp(tmp_password,user.password)==0) { cout<<"Succesfully Logged in"<<endl; success++; break; } } if(success < 1) cout<<"Invalid User"<<endl; f.close(); } void display_user_details(struct user_details *user) { ifstream f; f.open("user.bin",ios::in|ios::binary); f.seekg(0); while(f.read((char*)&user,sizeof(user))) { if(strcmp(tmp_username,user->username)==0 && strcmp(tmp_password,user->password)==0) { cout<<"\nName :"<<user->name<<endl; cout<<"Email :"<<user->email_id<<endl; cout<<"Mobile :"<<user->mobile_no<<endl; cout<<"Door No :"<<user->doorno<<endl; cout<<"Street :"<<user->street_name<<endl; cout<<"Area :"<<user->area<<endl; cout<<"Pincode :"<<user->pin_code<<endl; } } } int main() { struct user_details user; get_user_details(&user); login_form(user); display_user_details(&user); }
24.773196
88
0.616313
Rajasuryaa
277a8646f5bb7b25a0b3b24f76e259207f43bbaa
312
cc
C++
C++/learncpp/Chapter_6/Unamed_inline/inline_namespace.cc
MaRauder111/Cplusplus
9b18f95b5aee67f67c6e579ba7f3e80d3a3c68a5
[ "MIT" ]
null
null
null
C++/learncpp/Chapter_6/Unamed_inline/inline_namespace.cc
MaRauder111/Cplusplus
9b18f95b5aee67f67c6e579ba7f3e80d3a3c68a5
[ "MIT" ]
null
null
null
C++/learncpp/Chapter_6/Unamed_inline/inline_namespace.cc
MaRauder111/Cplusplus
9b18f95b5aee67f67c6e579ba7f3e80d3a3c68a5
[ "MIT" ]
null
null
null
#include<iostream> inline namespace test1 { void testing() { std::cout << "From test1 namespace\n"; } } namespace test2 { void testing() { std::cout << "From test2 namespace\n"; } } int main(){ test1::testing(); test2::testing(); testing(); return 0; }
12.48
46
0.538462
MaRauder111
277aebd86305eb4880fe1f7d368991ef856b9516
553
cc
C++
test/argon/lang/compiler.cc
ArgonLang/Argon
462d3d8721acd5131894bcbfa0214b0cbcffdf66
[ "Apache-2.0" ]
13
2021-06-24T17:50:20.000Z
2022-03-13T23:00:16.000Z
test/argon/lang/compiler.cc
ArgonLang/Argon
462d3d8721acd5131894bcbfa0214b0cbcffdf66
[ "Apache-2.0" ]
null
null
null
test/argon/lang/compiler.cc
ArgonLang/Argon
462d3d8721acd5131894bcbfa0214b0cbcffdf66
[ "Apache-2.0" ]
1
2022-03-31T22:58:42.000Z
2022-03-31T22:58:42.000Z
// This source file is part of the Argon project. // // Licensed under the Apache License v2.0 #include <gtest/gtest.h> #include <codecvt> #include <lang/scanner/scanner.h> #include <lang/parser/parser.h> #include <lang/compiler/compiler.h> using namespace argon::lang::scanner; using namespace argon::lang::parser; using namespace argon::lang::compiler; TEST(Compiler, Test) { Scanner scanner(R"( switch { case v: } println() )"); Parser parser(&scanner, "<anonymous>"); Compiler compiler; compiler.Compile(parser.Parse()); }
19.068966
49
0.701627
ArgonLang
277e58500532d0fcf1dfe0c8aa131be2637f7d62
2,451
cc
C++
Languages/MalbolgeInterpreter.cc
fuzziqersoftware/equinox
99efb1c5c537149b9448ced43c15ab604fb54463
[ "MIT" ]
null
null
null
Languages/MalbolgeInterpreter.cc
fuzziqersoftware/equinox
99efb1c5c537149b9448ced43c15ab604fb54463
[ "MIT" ]
null
null
null
Languages/MalbolgeInterpreter.cc
fuzziqersoftware/equinox
99efb1c5c537149b9448ced43c15ab604fb54463
[ "MIT" ]
null
null
null
#include "MalbolgeInterpreter.hh" #include <inttypes.h> #include <stdio.h> #include <phosg/Filesystem.hh> #include <phosg/Strings.hh> #include <string> using namespace std; static uint16_t crz(uint16_t x, uint16_t y) { static const uint8_t table[9] = {1, 0, 0, 1, 0, 2, 2, 2, 1}; uint16_t result = 0; for (size_t power = 1; power < 59049; power *= 3) { uint8_t x_trit = (x / power) % 3; uint8_t y_trit = (y / power) % 3; result += table[y_trit * 3 + x_trit] * power; } return result; } void malbolge_interpret(const string& filename) { string program = load_file(filename); u16string memory; memory.reserve(program.size()); for (size_t x = 0; x < program.size(); x++) { char normalized_opcode = (program[x] + x) % 94; if ((normalized_opcode != 4) && (normalized_opcode != 5) && (normalized_opcode != 23) && (normalized_opcode != 39) && (normalized_opcode != 40) && (normalized_opcode != 62) && (normalized_opcode != 68) && (normalized_opcode != 81)) { throw invalid_argument(string_printf("incorrect opcode at position %zu (%c)", x, program[x])); } memory.push_back(program[x]); } size_t a = 0, c = 0, d = 0; for (;;) { if (c >= memory.size()) { throw runtime_error("execution reached the end of memory"); } uint16_t opcode = memory[c]; uint8_t normalized_opcode = (opcode + c) % 94; switch (normalized_opcode) { case 4: c = program[d] - 1; if (c >= memory.size()) { throw runtime_error("jump beyond end of memory"); } opcode = memory[c]; // needed for reencryption later break; case 5: putc(a & 0xFF, stdout); break; case 23: a = getchar(); if (a == EOF) { a = 59048; } break; case 39: a = memory[d]; a = a / 3 + ((a % 3) * (59049 / 3)); memory[d] = a; break; case 40: d = memory[d]; break; case 62: a = crz(a, memory[d]); memory[d] = a; break; case 68: break; case 81: return; } static const char* encoding_table = "5z]&gqtyfr$(we4{WP)H-Zn,[%\\3dL+Q;>U!pJS72FhOA1CB6v^=I_0/8|jsb9m<.TVac`uY*MK\'X~xDl}REokN:#?G\"i@"; if (opcode >= 33 && opcode <= 126) { memory[c] = encoding_table[opcode - 33]; } c = (c + 1) % 59049; d = (d + 1) % 59049; } }
25.8
140
0.541004
fuzziqersoftware
27809e365e89699f3957d50c645b2f3a601a53d7
34,859
cpp
C++
libraries/chain/das33_evaluator.cpp
powerchain-ltd/greenpower-blockchain
ff04c37f2de11677c3a34889fdede1256a3e5e02
[ "MIT" ]
1
2021-07-26T02:42:01.000Z
2021-07-26T02:42:01.000Z
libraries/chain/das33_evaluator.cpp
green-powerchain-ltd/greenpower-blockchain
ff04c37f2de11677c3a34889fdede1256a3e5e02
[ "MIT" ]
null
null
null
libraries/chain/das33_evaluator.cpp
green-powerchain-ltd/greenpower-blockchain
ff04c37f2de11677c3a34889fdede1256a3e5e02
[ "MIT" ]
null
null
null
/* * MIT License * * Copyright (c) 2018 Tech Solutions Malta LTD * * 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 <graphene/chain/das33_evaluator.hpp> #include <graphene/chain/database.hpp> #include <boost/multiprecision/cpp_int.hpp> #include <graphene/chain/market_object.hpp> namespace graphene { namespace chain { // Helper methods: share_type users_total_pledges_in_round(account_id_type user_id, das33_project_id_type project_id, share_type round, const database& d) { share_type sum = 0; const auto& idx = d.get_index_type<das33_pledge_holder_index>().indices().get<by_user>().equal_range(user_id); for( auto it = idx.first; it != idx.second; ++it ) { if (it->project_id == project_id && it->phase_number == round) sum += (it->base_expected.amount); } return sum; } void price_check(const price& price_to_check, asset_id_type first_asset, asset_id_type second_asset) { FC_ASSERT(price_to_check.base.asset_id == first_asset || price_to_check.quote.asset_id == first_asset, "Price must be for ${1}", ("1", first_asset)); FC_ASSERT(price_to_check.base.asset_id == second_asset || price_to_check.quote.asset_id == second_asset, "Price must be for ${1}", ("1", second_asset)); } share_type precision_modifier(asset_object a, asset_object b) { share_type result = 1; if (a.precision > b.precision) { result = std::pow(10, a.precision - b.precision); } return result; } optional<price> calculate_price(asset_id_type asset_id, das33_project_id_type project_id, const database& d) { const auto& project_obj = project_id(d); const auto& price_override_it = project_obj.price_override.find(asset_id); // Check if we are in alliance pay project and HF time ... if (asset_id == d.get_dascoin_asset_id() && project_id == das33_project_id_type{3} && d.head_block_time() > HARDFORK_FIX_PLEDGE_PRICE_START && d.head_block_time() < HARDFORK_FIX_PLEDGE_PRICE_END) { // .. if yes set fixed price to 0.1 We return price{asset{100000, d.get_dascoin_asset_id()}, asset{10, d.get_web_asset_id()}}; } else if (asset_id == d.get_dascoin_asset_id() && project_id == das33_project_id_type{2} && d.head_block_time() > HARDFORK_FIX_PLEDGE_PRICE_START && d.head_block_time() < HARDFORK_FIX_PLEDGE_PRICE_END) { // .. or if we are in Greenstorc and HF time set fixed price to 0.0188 We return price{asset{10000000, d.get_dascoin_asset_id()}, asset{188, d.get_web_asset_id()}}; } else if (price_override_it != project_obj.price_override.end()) { // ... or if we have price override, use that return (*price_override_it).second; } else { // .. otherwise get price from db return d.get_price_in_web_eur(asset_id); } } typedef boost::multiprecision::uint128_t uint128_t; asset asset_price_multiply ( const asset& a, int64_t precision, const price& b, const price& c ) { uint128_t result; if( a.asset_id == b.base.asset_id ) { FC_ASSERT( b.base.amount.value > 0 ); result = (uint128_t(a.amount.value) * precision * b.quote.amount.value)/b.base.amount.value; if (b.quote.asset_id == c.base.asset_id) { FC_ASSERT( c.base.amount.value > 0 ); result = (result * c.quote.amount.value)/c.base.amount.value; result = result / precision; return asset( result.convert_to<int64_t>(), c.quote.asset_id ); } else { FC_ASSERT( c.quote.amount.value > 0 ); result = (result * c.base.amount.value)/c.quote.amount.value; result = result / precision; return asset( result.convert_to<int64_t>(), c.base.asset_id ); } } else if( a.asset_id == b.quote.asset_id ) { FC_ASSERT( b.quote.amount.value > 0 ); result = (uint128_t(a.amount.value) * precision * b.base.amount.value)/b.quote.amount.value; if (b.base.asset_id == c.base.asset_id) { FC_ASSERT( c.base.amount.value > 0 ); result = (result * c.quote.amount.value)/c.base.amount.value; result = result / precision; return asset( result.convert_to<int64_t>(), c.quote.asset_id ); } else { FC_ASSERT( c.quote.amount.value > 0 ); result = (result * c.base.amount.value)/c.quote.amount.value; result = result / precision; return asset( result.convert_to<int64_t>(), c.base.asset_id ); } } FC_THROW_EXCEPTION( fc::assert_exception, "invalid asset * price", ("asset",a)("price",b) ); } // method implementations: void_result das33_project_create_evaluator::do_evaluate( const operation_type& op ) { try { const auto& d = db(); const auto& gpo = d.get_global_properties(); // Check authority const auto& authority_obj = op.authority(d); d.perform_chain_authority_check("das33 authority", gpo.authorities.das33_administrator, authority_obj); // Check that name is unique const auto& idx = d.get_index_type<das33_project_index>().indices().get<by_project_name>(); FC_ASSERT(idx.find(op.name) == idx.end(), "Das33 project called ${1} already exists.", ("1", op.name)); // Check that owner is a wallet const auto& owner_obj = op.owner(d); FC_ASSERT( owner_obj.is_wallet(), "Owner account '${name}' is not a wallet account", ("name", owner_obj.name)); // Check that token exists const auto& token_index = d.get_index_type<asset_index>().indices().get<by_id>(); FC_ASSERT(token_index.find(op.token) != token_index.end(), "Token with id ${1} does not exist", ("1", op.token)); // Check that token has max_supply FC_ASSERT(op.token(d).options.max_supply > 0, "Token must have max_supply > 0"); // Check that token isn't one of the system assets FC_ASSERT(op.token != d.get_core_asset().id && op.token != d.get_web_asset_id() && op.token != d.get_dascoin_asset_id() && op.token != d.get_btc_asset_id() && op.token != d.get_cycle_asset_id(), "Can not create project with system assets"); // Check that token is not used by another project const auto& it = std::find_if(idx.begin(), idx.end(), [op](const das33_project_object& m) -> bool { return m.token_id == op.token; }); FC_ASSERT(it == idx.end(), "Token with id ${1} is already used by another project", ("1", op.token)); // Check that discounts exist FC_ASSERT(op.discounts.size() > 0, "Discounts must be provided. Only assets in discounts can be pledged."); // Check that discounts are in (0,1] range for (auto itr = op.discounts.begin(); itr != op.discounts.end(); itr++) { FC_ASSERT(itr->second > 0, "Discount can not be zero or negative (${name}:${value})", ("name", itr->first) ("value", itr->second)); FC_ASSERT(itr->second <= 1 * BONUS_PRECISION, "Discount can not be larger than 1.00 (${name}:${value})", ("name", itr->first) ("value", itr->second)); } return {}; } FC_CAPTURE_AND_RETHROW((op)) } object_id_type das33_project_create_evaluator::do_apply( const operation_type& op ) { try { auto& d = db(); const asset_object token = op.token(d); const asset max_supply {token.options.max_supply, token.id}; const asset to_collect {op.goal_amount_eur, d.get_web_asset_id()}; const price token_price = to_collect / max_supply; return d.create<das33_project_object>([&](das33_project_object& dpo){ dpo.name = op.name; dpo.owner = op.owner; dpo.token_id = op.token; dpo.goal_amount_eur = op.goal_amount_eur; dpo.discounts = op.discounts; dpo.min_pledge = op.min_pledge; dpo.max_pledge = op.max_pledge; dpo.token_price = token_price; dpo.collected_amount_eur = 0; dpo.tokens_sold = 0; dpo.status = das33_project_status::inactive; dpo.phase_number = 0; dpo.phase_limit = max_supply.amount; dpo.phase_end = time_point_sec::min(); }).id; } FC_CAPTURE_AND_RETHROW((op)) } void_result das33_project_update_evaluator::do_evaluate( const operation_type& op ) { try { const auto& d = db(); const auto& gpo = d.get_global_properties(); // Check authority const auto& authority_obj = op.authority(d); d.perform_chain_authority_check("das33 authority", gpo.authorities.das33_administrator, authority_obj); // Get project const auto& idx = d.get_index_type<das33_project_index>().indices().get<by_id>(); auto project_iterator = idx.find(op.project_id); FC_ASSERT(project_iterator != idx.end(), "Das33 project with id ${1} does not exist.", ("1", op.project_id)); project_to_update = &(*project_iterator); // Check name if (op.name.valid()) { const auto& name_index = d.get_index_type<das33_project_index>().indices().get<by_project_name>(); FC_ASSERT(name_index.find(*op.name) == name_index.end(), "Das33 project called ${1} already exists.", ("1", *op.name)); } // Check owner if (op.owner.valid()) { const auto& owner_obj = (*op.owner)(d); FC_ASSERT( owner_obj.is_wallet(), "Owner account '${name}' is not a wallet account", ("name", owner_obj.name)); } // Check price if (op.token_price.valid()) { price_check(*op.token_price, d.get_web_asset_id(), project_to_update->token_id); } // Check bonuses if (op.discounts.valid()) { // Check that discounts are in (0,1] range for (auto itr = op.discounts->begin(); itr != op.discounts->end(); itr++) { FC_ASSERT(itr->second > 0, "Discount can not be zero or negative (${name}:${value})", ("name", itr->first) ("value", itr->second)); FC_ASSERT(itr->second <= 1 * BONUS_PRECISION, "Discount can not be larger than 1.00 (${name}:${value})", ("name", itr->first) ("value", itr->second)); } } // Check phase number if (op.phase_number.valid()) { FC_ASSERT(*op.phase_number > project_to_update->phase_number, "Phase number can not be decreased"); } // Check phase limit if (op.phase_limit.valid()) { share_type new_limit = *op.phase_limit; asset_object token = project_to_update->token_id(d); // If previous limit is not max supply if (project_to_update->phase_limit != token.options.max_supply ) { // New limit must be more than what is already collected FC_ASSERT(new_limit >= project_to_update->tokens_sold, "New phase limit must be more than already collected"); } FC_ASSERT(new_limit <= token.options.max_supply, "New limit can not be more then max supply of token"); } // Check status if (op.status.valid()) { FC_ASSERT(*op.status < das33_project_status::DAS33_PROJECT_STATUS_COUNT, "Unknown status value"); } return {}; } FC_CAPTURE_AND_RETHROW((op)) } void_result das33_project_update_evaluator::do_apply( const operation_type& op ) { try { auto& d = db(); d.modify<das33_project_object>(*project_to_update, [&](das33_project_object& dpo){ if (op.name) dpo.name = *op.name; if (op.owner) dpo.owner = *op.owner; // token_id: we can't alter if (op.goal_amount) dpo.goal_amount_eur = *op.goal_amount; if (op.discounts) dpo.discounts = *op.discounts; if (op.min_pledge) dpo.min_pledge = *op.min_pledge; if (op.max_pledge) dpo.max_pledge = *op.max_pledge; if (op.token_price) dpo.token_price = *op.token_price; // collected_amount_eur: we can't alter // tokens_sold: we can't alter if (op.status) dpo.status = static_cast<das33_project_status>(*op.status); if (op.phase_number) dpo.phase_number = *op.phase_number; if (op.phase_limit) dpo.phase_limit = *op.phase_limit; if (op.phase_end) dpo.phase_end = *op.phase_end; for (const auto& ext : op.extensions) { ext.visit(das33_project_visitor{dpo.report}); } auto new_price_override_it = std::find_if(op.extensions.begin(), op.extensions.end(), [](const das33_project_update_operation::das33_project_extension& ext){ return ext.which() == das33_project_update_operation::das33_project_extension::tag< map<asset_id_type, price> >::value; }); if (new_price_override_it != op.extensions.end()) { dpo.price_override = (*new_price_override_it).get<map<asset_id_type, price>>(); } }); return {}; } FC_CAPTURE_AND_RETHROW((op)) } void_result das33_project_delete_evaluator::do_evaluate( const operation_type& op ) { try { const auto& d = db(); const auto& gpo = d.get_global_properties(); const auto& authority_obj = op.authority(d); d.perform_chain_authority_check("das33 authority", gpo.authorities.das33_administrator, authority_obj); const auto& idx = d.get_index_type<das33_project_index>().indices().get<by_id>(); auto project_iterator = idx.find(op.project_id); FC_ASSERT(project_iterator != idx.end(), "Das33 project with id ${1} does not exist.", ("1", op.project_id)); project_to_delete = &(*project_iterator); const auto& pledges_idx = d.get_index_type<das33_pledge_holder_index>().indices().get<by_project>().equal_range(op.project_id); //auto pledges_iterator = pledges_idx.begin(); FC_ASSERT(pledges_idx.first == pledges_idx.second, "Project can not be deleted as it has pledges"); return {}; } FC_CAPTURE_AND_RETHROW((op)) } void_result das33_project_delete_evaluator::do_apply( const operation_type& op ) { try { auto& d = db(); d.remove(*project_to_delete); return {}; } FC_CAPTURE_AND_RETHROW((op)) } void_result das33_pledge_asset_evaluator::do_evaluate(const das33_pledge_asset_operation& op) { try { const auto& d = db(); const auto& project_obj = op.project_id(d); const auto& token_obj = project_obj.token_id(d); // Check if pledged asset and project token are different assets FC_ASSERT( op.pledged.asset_id != project_obj.token_id, "Cannot pledge project tokens" ); // Assure target project exists: const auto& idx = d.get_index_type<das33_project_index>().indices().get<by_id>(); FC_ASSERT( idx.find(project_obj.id) != idx.end(), "Bad project id" ); // Check if project is active FC_ASSERT(project_obj.status == das33_project_status::active, "Pladge can only be made to active project"); // Assure we have enough balance to pledge: const auto& balance_obj = d.get_balance_object(op.account_id, op.pledged.asset_id); FC_ASSERT( balance_obj.get_balance() >= op.pledged, "Not enough balance on user account ${a}, left ${l}, needed ${n}", ("a", op.account_id) ("l", d.to_pretty_string(balance_obj.get_balance())) ("n", d.to_pretty_string(op.pledged)) ); // Assure current phase hasn't ended if (project_obj.phase_end != time_point_sec::min()) { FC_ASSERT(d.head_block_time() < project_obj.phase_end, "Can not pledge: new ICO phase hasn;t started yet"); } // Assure that all tokens aren't sold FC_ASSERT(project_obj.tokens_sold < token_obj.options.max_supply, "All tokens for project are sold"); FC_ASSERT(project_obj.tokens_sold < project_obj.phase_limit, "All tokens in this phase are sold"); // Calculate expected amount share_type precision = precision_modifier(op.pledged.asset_id(d), d.get_web_asset_id()(d)); total.asset_id = project_obj.token_id; optional<price> conversion_price = calculate_price(op.pledged.asset_id, op.project_id, d); FC_ASSERT(conversion_price.valid(), "There is no proper price for ${asset}", ("asset", op.pledged.asset_id)); price_at_evaluation = *conversion_price; base = asset_price_multiply(op.pledged, precision.value, price_at_evaluation, project_obj.token_price); // Assure that pledge amount is above minimum if (!(op.pledged.asset_id == d.get_dascoin_asset_id() && op.project_id == das33_project_id_type{2} && d.head_block_time() > HARDFORK_FIX_PLEDGE_PRICE_START && d.head_block_time() < HARDFORK_FIX_PLEDGE_PRICE_END)) { FC_ASSERT(base.amount >= project_obj.min_pledge, "Can not pledge: must buy at least ${min} tokens", ("min", project_obj.min_pledge)); } // Assure that pledge amount is below maximum for current user auto previous_pledges = users_total_pledges_in_round(op.account_id, op.project_id, project_obj.phase_number, d); if (op.pledged.asset_id == d.get_dascoin_asset_id() && op.project_id == das33_project_id_type{3} && d.head_block_time() > HARDFORK_FIX_PLEDGE_PRICE_START && d.head_block_time() < HARDFORK_FIX_PLEDGE_PRICE_END) { FC_ASSERT( previous_pledges + base.amount <= 100000000000000, "Can not buy more then ${max} tokens per phase and you already pledged for ${previous} in this phase.", ("max", project_obj.max_pledge) ("previous", previous_pledges)); } else { FC_ASSERT( previous_pledges + base.amount <= project_obj.max_pledge, "Can not buy more then ${max} tokens per phase and you already pledged for ${previous} in this phase.", ("max", project_obj.max_pledge) ("previous", previous_pledges)); } // Calculate expected amount with discounts auto discount_iterator = project_obj.discounts.find(op.pledged.asset_id); FC_ASSERT( discount_iterator != project_obj.discounts.end(), "This asset can not be used in this project phase" ); discount = discount_iterator->second; total.amount = base.amount * BONUS_PRECISION / discount; // Assure that pledge amount is above zero FC_ASSERT(total.amount > 0, "Cannot pledge because expected amount of ${tok} is ${ex}", ("tok", token_obj.symbol) ("ex", d.to_pretty_string(total)) ); bool total_reduced = false; // Decrease amount if it passes tokens max supply if (project_obj.tokens_sold + total.amount > token_obj.options.max_supply) { total.amount = token_obj.options.max_supply - project_obj.tokens_sold; total_reduced = true; } // Decrease amount if it passes current phase limit if (project_obj.tokens_sold + total.amount > project_obj.phase_limit) { total.amount = project_obj.phase_limit - project_obj.tokens_sold; total_reduced = true; } if (total_reduced) { base = {total.amount * discount / BONUS_PRECISION, total.asset_id}; bonus = total - base; precision = precision_modifier(base.asset_id(d), d.get_web_asset_id()(d)); to_take = asset_price_multiply(base, precision.value, project_obj.token_price, price_at_evaluation); } else { bonus = total - base; to_take = op.pledged; } return {}; } FC_CAPTURE_AND_RETHROW((op)) } object_id_type das33_pledge_asset_evaluator::do_apply(const das33_pledge_asset_operation& op) { try { auto& d = db(); const auto& project_obj = op.project_id(d); // Adjust the balance and spent amount: const auto& balance_obj = d.get_balance_object(op.account_id, op.pledged.asset_id); d.modify(balance_obj, [&](account_balance_object& from){ from.balance -= to_take.amount; from.spent += to_take.amount; }); // Update project d.modify(project_obj, [&](das33_project_object& p){ p.tokens_sold += total.amount; p.collected_amount_eur += (to_take * price_at_evaluation).amount; }); // Create the holder object and return its ID: return d.create<das33_pledge_holder_object>([&](das33_pledge_holder_object& cpho){ cpho.account_id = op.account_id; cpho.pledged = to_take; cpho.pledge_remaining = to_take; cpho.base_remaining = base; cpho.base_expected = base; cpho.bonus_remaining = bonus; cpho.bonus_expected = bonus; cpho.phase_number = project_obj.phase_number; cpho.project_id = op.project_id; cpho.timestamp = d.head_block_time(); }).id; } FC_CAPTURE_AND_RETHROW((op)) } void_result das33_distribute_project_pledges_evaluator::do_evaluate(const das33_distribute_project_pledges_operation& op) { try { auto& d = db(); auto& pro_index = d.get_index_type<das33_project_index>().indices().get<by_id>(); auto pro_itr = pro_index.find(op.project); account_id_type pro_owner; FC_ASSERT(pro_itr != pro_index.end(), "Missing project object with this project_id!"); _pro_owner = pro_itr->owner; return {}; } FC_CAPTURE_AND_RETHROW((op)) } void_result das33_distribute_project_pledges_evaluator::do_apply(const das33_distribute_project_pledges_operation& op) { try { auto& d = db(); std::vector<object_id_type> pledges_to_remove; const auto& index = d.get_index_type<das33_pledge_holder_index>().indices().get<by_project>().equal_range(op.project); auto itr = index.first; while(itr != index.second) { if(op.phase_number.valid() && itr->phase_number != *op.phase_number) { ++itr; continue; } const das33_pledge_holder_object& pho = *itr; // calc amount of token and asset that will be exchanged share_type base = std::round(static_cast<double>(pho.base_expected.amount.value) * op.base_to_pledger.value / BONUS_PRECISION / 100); base = (base < pho.base_remaining.amount) ? base : pho.base_remaining.amount; share_type bonus = std::round(static_cast<double>(pho.bonus_expected.amount.value) * op.bonus_to_pledger.value / BONUS_PRECISION / 100); bonus = (bonus < pho.bonus_remaining.amount) ? bonus : pho.bonus_remaining.amount; share_type pledge = std::round(static_cast<double>(pho.pledged.amount.value) * op.to_escrow.value / BONUS_PRECISION / 100); pledge = (pledge < pho.pledge_remaining.amount) ? pledge : pho.pledge_remaining.amount; // make virtual op for history traking das33_pledge_result_operation pledge_result; pledge_result.funders_account = pho.account_id; pledge_result.account_to_fund = _pro_owner; pledge_result.completed = true; pledge_result.pledged = pledge; pledge_result.received = base + bonus; pledge_result.project_id = op.project; pledge_result.timestamp = d.head_block_time(); d.push_applied_operation(pledge_result); d.adjust_balance(_pro_owner, asset{pledge, pho.pledged.asset_id}, 0 /*reserved_delta*/); // issue balance object if it does not exists if(!d.check_if_balance_object_exists(pho.account_id,pho.base_expected.asset_id)) { d.create<account_balance_object>([&pho](account_balance_object& abo){ abo.owner = pho.account_id; abo.asset_type = pho.base_expected.asset_id; abo.balance = 0; abo.reserved = 0; }); } // issue token asset auto& balance1_obj = d.get_balance_object(pho.account_id, pho.base_expected.asset_id); d.issue_asset(balance1_obj, base + bonus, 0); // update pledge holder object d.modify(pho, [&](das33_pledge_holder_object& p){ p.pledge_remaining.amount -= pledge; p.base_remaining.amount -= base; p.bonus_remaining.amount -= bonus; }); // if everything is distributed remove object if(pho.pledge_remaining.amount + pho.base_remaining.amount + pho.bonus_remaining.amount <= 0) { pledges_to_remove.push_back(pho.id); } itr++; } auto& index1 = d.get_index_type<das33_pledge_holder_index>().indices().get<by_id>(); for(object_id_type id : pledges_to_remove) { auto itr = index1.find(id); if(itr != index1.end()) d.remove(*itr); } return {}; } FC_CAPTURE_AND_RETHROW((op)) } void_result das33_project_reject_evaluator::do_evaluate(const das33_project_reject_operation& op) { try { auto& d = db(); auto& pro_index = d.get_index_type<das33_project_index>().indices().get<by_id>(); auto pro_itr = pro_index.find(op.project); FC_ASSERT(pro_itr != pro_index.end(), "Missing project object with this project_id!"); auto& index = d.get_index_type<das33_pledge_holder_index>().indices().get<by_project>(); auto itr = index.lower_bound(op.project); auto end = index.upper_bound(op.project); while(itr != end) { const das33_pledge_holder_object& pho = *itr; FC_ASSERT(pho.base_expected.amount == pho.base_remaining.amount && pho.bonus_expected.amount == pho.bonus_remaining.amount && pho.pledged.amount == pho.pledge_remaining.amount, "Project already accepted, can't be rejected!"); itr++; } _pro_owner = pro_itr->owner; return {}; } FC_CAPTURE_AND_RETHROW((op)) } void_result das33_project_reject_evaluator::do_apply(const das33_project_reject_operation& op) { try { auto& d = db(); while(true) { auto& index = d.get_index_type<das33_pledge_holder_index>().indices().get<by_project>(); auto itr = index.lower_bound(op.project); auto end = index.upper_bound(op.project); if(itr == end) break; const das33_pledge_holder_object& pho = *itr; das33_pledge_result_operation pledge_result; pledge_result.funders_account = pho.account_id; pledge_result.account_to_fund = _pro_owner; pledge_result.completed = false; pledge_result.pledged = pho.pledged; pledge_result.received = pho.pledged; pledge_result.project_id = op.project; pledge_result.timestamp = d.head_block_time(); d.push_applied_operation(pledge_result); auto& balance_obj = d.get_balance_object(pho.account_id, pho.pledged.asset_id); d.modify(balance_obj, [&](account_balance_object& balance_obj){ balance_obj.balance += pho.pledged.amount; }); d.remove(pho); } return {}; } FC_CAPTURE_AND_RETHROW((op)) } void_result das33_distribute_pledge_evaluator::do_evaluate(const das33_distribute_pledge_operation& op) { try { auto& d = db(); // find pledge object auto& index = d.get_index_type<das33_pledge_holder_index>().indices().get<by_id>(); auto itr = index.find(op.pledge); FC_ASSERT(itr != index.end(),"Missing pledge object with this pledge_id."); auto& pro_index = d.get_index_type<das33_project_index>().indices().get<by_id>(); auto pro_itr = pro_index.find(itr->project_id); account_id_type pro_owner; FC_ASSERT(pro_itr != pro_index.end(), "Missing project object with this project_id!"); _pro_owner = pro_itr->owner; _pledge_holder_ptr = &(*itr); return {}; } FC_CAPTURE_AND_RETHROW((op)) } void_result das33_distribute_pledge_evaluator::do_apply(const das33_distribute_pledge_operation& op) { try { auto& d = db(); const das33_pledge_holder_object& pho = *_pledge_holder_ptr; // calc amount of token and asset that will be exchanged share_type base = std::round(static_cast<double>(pho.base_expected.amount.value) * op.base_to_pledger.value / BONUS_PRECISION / 100); base = (base < pho.base_remaining.amount) ? base : pho.base_remaining.amount; share_type bonus = std::round(static_cast<double>(pho.bonus_expected.amount.value) * op.bonus_to_pledger.value / BONUS_PRECISION / 100); bonus = (bonus < pho.bonus_remaining.amount) ? bonus : pho.bonus_remaining.amount; share_type pledge = std::round(static_cast<double>(pho.pledged.amount.value) * op.to_escrow.value / BONUS_PRECISION / 100); pledge = (pledge < pho.pledge_remaining.amount) ? pledge : pho.pledge_remaining.amount; // make virtual op for history traking das33_pledge_result_operation pledge_result; pledge_result.funders_account = pho.account_id; pledge_result.account_to_fund = _pro_owner; pledge_result.completed = true; pledge_result.pledged = pledge; pledge_result.received = base + bonus; pledge_result.project_id = pho.project_id; pledge_result.timestamp = d.head_block_time(); d.push_applied_operation(pledge_result); d.adjust_balance(_pro_owner, asset{pledge, pho.pledged.asset_id}, 0 /*reserved_delta*/); // issue balance object if it does not exists if(!d.check_if_balance_object_exists(pho.account_id,pho.base_expected.asset_id)) { d.create<account_balance_object>([&pho](account_balance_object& abo){ abo.owner = pho.account_id; abo.asset_type = pho.base_expected.asset_id; abo.balance = 0; abo.reserved = 0; }); } // issue token asset auto& balance1_obj = d.get_balance_object(pho.account_id, pho.base_expected.asset_id); d.issue_asset(balance1_obj, base + bonus, 0); // update pledge holder object d.modify(pho, [&](das33_pledge_holder_object& p){ p.pledge_remaining.amount -= pledge; p.base_remaining.amount -= base; p.bonus_remaining.amount -= bonus; }); // if everything is distributed remove object if(pho.pledge_remaining.amount + pho.base_remaining.amount + pho.bonus_remaining.amount <= 0) { d.remove(pho); } return {}; } FC_CAPTURE_AND_RETHROW((op)) } void_result das33_pledge_reject_evaluator::do_evaluate(const das33_pledge_reject_operation& op) { try { auto& d = db(); // find pledge object auto& index = d.get_index_type<das33_pledge_holder_index>().indices().get<by_id>(); auto itr = index.find(op.pledge); FC_ASSERT(itr != index.end(),"Missing pledge object with this pledge_id."); auto& pro_index = d.get_index_type<das33_project_index>().indices().get<by_id>(); auto pro_itr = pro_index.find(itr->project_id); account_id_type pro_owner; FC_ASSERT(pro_itr != pro_index.end(), "Missing project object with this project_id!"); _pro_owner = pro_itr->owner; _pledge_holder_ptr = &(*itr); const das33_pledge_holder_object& pho = *_pledge_holder_ptr; FC_ASSERT(pho.base_expected.amount == pho.base_remaining.amount && pho.bonus_expected.amount == pho.bonus_remaining.amount && pho.pledged.amount == pho.pledge_remaining.amount, "Project already accepted, can't be rejected!"); return {}; } FC_CAPTURE_AND_RETHROW((op)) } void_result das33_pledge_reject_evaluator::do_apply(const das33_pledge_reject_operation& op) { try { auto& d = db(); // make virtual op for history traking const das33_pledge_holder_object& pho = *_pledge_holder_ptr; // make virtual op for history traking das33_pledge_result_operation pledge_result; pledge_result.funders_account = pho.account_id; pledge_result.account_to_fund = _pro_owner; pledge_result.completed = false; pledge_result.pledged = pho.pledged; pledge_result.received = pho.pledged; pledge_result.project_id = pho.project_id; pledge_result.timestamp = d.head_block_time(); d.push_applied_operation(pledge_result); // give to project owner pledged amount auto& balance_obj = d.get_balance_object(pho.account_id, pho.pledged.asset_id); d.modify(balance_obj, [&](account_balance_object& balance_obj){ balance_obj.balance += pho.pledged.amount; }); d.remove(pho); return {}; } FC_CAPTURE_AND_RETHROW((op)) } void_result das33_set_use_external_btc_price_evaluator::do_evaluate(const operation_type& op) { try { return {}; } FC_CAPTURE_AND_RETHROW((op)) } void_result das33_set_use_external_btc_price_evaluator::do_apply(const operation_type& op) { try { return {}; } FC_CAPTURE_AND_RETHROW((op)) } void_result das33_set_use_market_price_for_token_evaluator::do_evaluate(const operation_type& op) { try { const auto& d = db(); const auto& gpo = d.get_global_properties(); const auto& authority_obj = op.authority(d); d.perform_chain_authority_check("das33 authority", gpo.authorities.das33_administrator, authority_obj); return {}; } FC_CAPTURE_AND_RETHROW((op)) } void_result das33_set_use_market_price_for_token_evaluator::do_apply(const operation_type& op) { try { auto& d = db(); d.modify(d.get_global_properties(), [&](global_property_object& gpo){ gpo.use_market_price_for_token = op.use_market_price_for_token; }); return {}; } FC_CAPTURE_AND_RETHROW((op)) } } } // namespace graphene::chain
39.477916
166
0.654092
powerchain-ltd
278116895e8d48381c414cebd5e2d4ca755c6b44
4,650
cpp
C++
src/caffe/layers/dice_loss_layer.cpp
superxuang/caffe_3d_crf_rnn
a99e99848156a4f3592ab58a89c9aec47dd2aacb
[ "BSD-2-Clause" ]
9
2017-12-05T06:08:31.000Z
2018-09-10T13:49:12.000Z
src/caffe/layers/dice_loss_layer.cpp
superxuang/caffe_3d_crf_rnn
a99e99848156a4f3592ab58a89c9aec47dd2aacb
[ "BSD-2-Clause" ]
3
2018-04-10T08:01:02.000Z
2019-08-21T02:25:47.000Z
src/caffe/layers/dice_loss_layer.cpp
superxuang/caffe_3d_crf_rnn
a99e99848156a4f3592ab58a89c9aec47dd2aacb
[ "BSD-2-Clause" ]
2
2018-04-08T12:28:41.000Z
2021-07-11T11:10:40.000Z
#include <algorithm> #include <vector> #include "caffe/layers/dice_loss_layer.hpp" #include "caffe/util/math_functions.hpp" #include <itkImage.h> #include <itkSmartPointer.h> #include <itkImageFileReader.h> #include <itkImageFileWriter.h> using std::floor; using std::max; using std::min; using std::pow; namespace caffe { template <typename Dtype> void DiceLossLayer<Dtype>::Forward_cpu(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { const Dtype* bottom_data = bottom[0]->cpu_data(); const Dtype* label = bottom[1]->cpu_data(); const int num = bottom[0]->num(); const int channel = bottom[0]->channels(); const int count = bottom[0]->count(); const int cls_num = channel - 1; const int pixel_num = count / num / channel; Dtype* result_buffer = new Dtype[num * channel * pixel_num]; for (int i = 0; i < num; ++i) { for (int k = 0; k < pixel_num; ++k) { double max_score = -1; int max_score_cls = 0; for (int m = 0; m < channel; ++m) { if (max_score < bottom_data[i * channel * pixel_num + m * pixel_num + k]) { max_score = bottom_data[i * channel * pixel_num + m * pixel_num + k]; max_score_cls = m; } } for (int j = 0; j < channel; ++j) { result_buffer[i * channel * pixel_num + j * pixel_num + k] = (max_score_cls == j) ? 1.0 : 0.0; } } } delete[]union_; delete[]intersection_; delete[]class_exist_; union_ = new double[num * channel]; intersection_ = new double[num * channel]; class_exist_ = new bool[num * channel]; int exist_num = 0; for (int i = 0; i < num; ++i) { for (int j = 0; j < channel; ++j) { double result_sum = 0; double label_sum = 0; union_[i * channel + j] = 0; intersection_[i * channel + j] = 0; class_exist_[i * channel + j] = false; for (int k = 0; k < pixel_num; ++k) { double result_value = result_buffer[i * channel * pixel_num + j * pixel_num + k]; double label_value = (label[i * pixel_num + k] == j) ? 1 : 0; union_[i * channel + j] += pow(result_value, 2.0) + pow(label_value, 2.0); intersection_[i * channel + j] += result_value * label_value; if (j > 0) { result_sum += result_value; label_sum += label_value; } } union_[i * channel + j] += 0.00001; if (label_sum > 0) { class_exist_[i * channel + j] = true; exist_num++; } } } Dtype* loss = top[0]->mutable_cpu_data(); loss[0] = 0; for (int i = 0; i < num; ++i) { for (int j = 0; j < channel; ++j) { if (class_exist_[i * channel + j]) { loss[0] += 2 * intersection_[i * channel + j] / union_[i * channel + j]; } } } if (exist_num > 0) { loss[0] = loss[0] / exist_num; } LOG(INFO) << "Average dice = " << loss[0]; delete[]result_buffer; } template <typename Dtype> void DiceLossLayer<Dtype>::Backward_cpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom) { if (propagate_down[1]) { LOG(FATAL) << this->type() << " Layer cannot backpropagate to label inputs."; } if (propagate_down[0]) { const Dtype* bottom_data = bottom[0]->cpu_data(); Dtype* bottom_diff = bottom[0]->mutable_cpu_diff(); const Dtype* label = bottom[1]->cpu_data(); const int num = bottom[0]->num(); const int channel = bottom[0]->channels(); const int count = bottom[0]->count(); const int cls_num = channel - 1; const int pixel_num = count / num / channel; memset(bottom_diff, 0, sizeof(Dtype) * num * channel * pixel_num); for (int i = 0; i < num; ++i) { for (int j = 0; j < pixel_num; ++j) { for (int k = 1; k < channel; ++k) { if (class_exist_[i * channel + k]) { double result_value = bottom_data[i * channel * pixel_num + k * pixel_num + j]; double label_value = (label[i * pixel_num + j] == k) ? 1 : 0; double union_value = union_[i * channel + k]; double intersection_value = intersection_[i * channel + k]; double diff = 2 * (label_value * union_value / (union_value * union_value) - 2 * result_value * intersection_value / (union_value * union_value)); bottom_diff[i * channel * pixel_num + k * pixel_num + j] -= diff; bottom_diff[i * channel * pixel_num + 0 * pixel_num + j] += diff; } } } } } } INSTANTIATE_CLASS(DiceLossLayer); REGISTER_LAYER_CLASS(DiceLoss); } // namespace caffe
32.517483
102
0.575699
superxuang
959836b7bb5d2a6d9ef359b80cadc6dd375bc176
8,235
cpp
C++
SOURCES/f4compress/f4compress.cpp
IsraelyFlightSimulator/Negev-Storm
86de63e195577339f6e4a94198bedd31833a8be8
[ "Unlicense" ]
1
2021-02-19T06:06:31.000Z
2021-02-19T06:06:31.000Z
src/f4compress/f4compress.cpp
markbb1957/FFalconSource
07b12e2c41a93fa3a95b912a2433a8056de5bc4d
[ "BSD-2-Clause" ]
null
null
null
src/f4compress/f4compress.cpp
markbb1957/FFalconSource
07b12e2c41a93fa3a95b912a2433a8056de5bc4d
[ "BSD-2-Clause" ]
2
2019-08-20T13:35:13.000Z
2021-04-24T07:32:04.000Z
// F4Compress.cpp // Miro "Jammer" Torrielli - 12May04 #include <windows.h> #include <stdio.h> #include <stdlib.h> #include "F4Compress.h" #include "F4Thread.h" #include "setup.h" #include "f4find.h" #include "dxtlib.h" #include "nvdxt.h" #include "fartex.h" #include "texbank.h" #include "terrtex.h" #include "dispcfg.h" #include "playerop.h" #include "dispopts.h" #include "otwdrive.h" #include "simfile.h" #include "theaterdef.h" #include "realweather.h" #include "weather.h" #include "resmgr.h" #include "fsound.h" #define FALCON_REGISTRY_KEY "Software\\MicroProse\\Falcon\\4.0" RealWeather *realWeather = NULL; //WeatherClass *TheWeather; extern void LoadTheaterList(); #define ResFOpen fopen #define ResFClose fclose int gLangIDNum = 1; bool bWHOT; DWORD p3DpitHilite; // Cobra - 3D pit high night lighting color DWORD p3DpitLolite; // Cobra - 3D pit low night lighting color //JUNK #ifdef DEBUG int f4AssertsOn=TRUE,f4HardCrashOn=FALSE,shiAssertsOn=TRUE,shiWarningsOn=TRUE,shiHardCrashOn=FALSE; #endif int NumHats = -1; int SimLibErrno = 0; char g_CardDetails[1024]; bool g_bDrawBoundingBox=false; int targetCompressionRatio = 0; class OTWDriverClass OTWDriver; unsigned long vuxGameTime = 0; short NumObjectiveTypes = 0; void ResetLatLong(void) {} void SetLatLong(float,float) {} void GetLatLong (float *,float *) {} OTWDriverClass::OTWDriverClass(void) {} OTWDriverClass::~OTWDriverClass(void) {} void ConstructOrderedSentence (short maxlen,_TCHAR *buffer, _TCHAR *format, ... ) { }; void ReadDTXnFile(unsigned long count, void * buffer) { } void WriteDTXnFile(unsigned long count, void *buffer) { _write(fileout,buffer,count); } extern "C" { int movieInit(int,LPVOID) { return 0; } void movieUnInit(void) {} } extern "C" void F4SoundFXSetPos( int sfxId, int override, float x, float y, float z, float pscale, float volume , int uid) { } LRESULT CALLBACK FalconMessageHandler (HWND hwnd,UINT message,WPARAM wParam,LPARAM lParam){ return 0; } int FindBestResolution(void) { if (DisplayOptions.DispWidth>1280) return 1600; if (DisplayOptions.DispWidth>1024) return 1280; if (DisplayOptions.DispWidth>800) return 1024; if (DisplayOptions.DispWidth>640) return 800; return 640; } FILE* OpenCampFile (char *filename, char *ext, char *mode) { char fullname[MAX_PATH],path[MAX_PATH]; char buffer[MAX_PATH]; FILE *fp; sprintf (buffer, "OpenCampFile %s.%s %s\n", filename, ext, mode); // MonoPrint (buffer); // OutputDebugString (buffer); if (strcmp(ext,"cmp") == 0) sprintf(path,FalconCampUserSaveDirectory); else if (stricmp(ext,"obj") == 0) sprintf(path,FalconCampUserSaveDirectory); else if (stricmp(ext,"obd") == 0) sprintf(path,FalconCampUserSaveDirectory); else if (stricmp(ext,"uni") == 0) sprintf(path,FalconCampUserSaveDirectory); else if (stricmp(ext,"tea") == 0) sprintf(path,FalconCampUserSaveDirectory); else if (stricmp(ext,"wth") == 0) sprintf(path,FalconCampUserSaveDirectory); else if (stricmp(ext,"plt") == 0) sprintf(path,FalconCampUserSaveDirectory); else if (stricmp(ext,"mil") == 0) sprintf(path,FalconCampUserSaveDirectory); else if (stricmp(ext,"tri") == 0) sprintf(path,FalconCampUserSaveDirectory); else if (stricmp(ext,"evl") == 0) sprintf(path,FalconCampUserSaveDirectory); else if (stricmp(ext,"smd") == 0) sprintf(path,FalconCampUserSaveDirectory); else if (stricmp(ext,"sqd") == 0) sprintf(path,FalconCampUserSaveDirectory); else if (stricmp(ext,"pol") == 0) sprintf(path,FalconCampUserSaveDirectory); else if (stricmp(ext,"ct") == 0) sprintf(path,FalconObjectDataDir); else if (stricmp(ext,"ini") == 0) sprintf(path,FalconObjectDataDir); else if (stricmp(ext,"ucd") == 0) sprintf(path,FalconObjectDataDir); else if (stricmp(ext,"ocd") == 0) sprintf(path,FalconObjectDataDir); else if (stricmp(ext,"fcd") == 0) sprintf(path,FalconObjectDataDir); else if (stricmp(ext,"vcd") == 0) sprintf(path,FalconObjectDataDir); else if (stricmp(ext,"wcd") == 0) sprintf(path,FalconObjectDataDir); else if (stricmp(ext,"rcd") == 0) sprintf(path,FalconObjectDataDir); else if (stricmp(ext,"icd") == 0) sprintf(path,FalconObjectDataDir); else if (stricmp(ext,"rwd") == 0) sprintf(path,FalconObjectDataDir); else if (stricmp(ext,"vsd") == 0) sprintf(path,FalconObjectDataDir); else if (stricmp(ext,"swd") == 0) sprintf(path,FalconObjectDataDir); else if (stricmp(ext,"acd") == 0) sprintf(path,FalconObjectDataDir); else if (stricmp(ext,"wld") == 0) sprintf(path,FalconObjectDataDir); else if (stricmp(ext,"phd") == 0) sprintf(path,FalconObjectDataDir); else if (stricmp(ext,"pd") == 0) sprintf(path,FalconObjectDataDir); else if (stricmp(ext,"fed") == 0) sprintf(path,FalconObjectDataDir); else if (stricmp(ext,"ssd") == 0) sprintf(path,FalconObjectDataDir); else if (stricmp(ext,"rkt") == 0) // 2001-11-05 Added by M.N. sprintf(path,FalconObjectDataDir); else if (stricmp(ext,"ddp") == 0) // 2002-04-20 Added by M.N. sprintf(path,FalconObjectDataDir); else sprintf(path,FalconCampaignSaveDirectory); // Outdated by resmgr: // if (!ResExistFile(filename)) // ResAddPath(path, FALSE); sprintf(fullname,"%s\\%s.%s",path,filename,ext); fp = fopen(fullname,mode); return fp; } void CloseCampFile (FILE *fp) { if (fp) { fclose (fp); } } int main(int argc, char* argv[]) { HKEY theKey; TheaterDef *td; DWORD type,size; int retval, season; BOOL bAuto = FALSE; BOOL bForce = TRUE; char tmpPath[_MAX_PATH]; HRESULT hr = CoInitialize(NULL); _controlfp(_RC_CHOP,MCW_RC); _controlfp(_PC_24,MCW_PC); SetCurrentDirectory(FalconDataDirectory); size = sizeof(FalconDataDirectory); RegOpenKeyEx(HKEY_LOCAL_MACHINE,FALCON_REGISTRY_KEY,0,KEY_ALL_ACCESS,&theKey); RegQueryValueEx(theKey,"baseDir",0,&type,(LPBYTE)&FalconDataDirectory,&size); size = sizeof(FalconTerrainDataDir); RegQueryValueEx(theKey,"theaterDir",0,&type,(LPBYTE)FalconTerrainDataDir,&size); size = sizeof (FalconObjectDataDir); RegQueryValueEx(theKey,"objectDir",0,&type,(LPBYTE)FalconObjectDataDir,&size); strcpy(Falcon3DDataDir,FalconObjectDataDir); size = sizeof (FalconMiscTexDataDir); RegQueryValueEx(theKey,"misctexDir",0,&type,(LPBYTE)FalconMiscTexDataDir,&size); //realWeather = new WeatherClass(); //TheWeather = new WeatherClass(); ResInit(NULL); ResCreatePath(FalconDataDirectory,FALSE); ResAddPath(FalconCampaignSaveDirectory,FALSE); sprintf(tmpPath,"%s\\Zips",FalconDataDirectory); ResAddPath(tmpPath,FALSE); sprintf(tmpPath,"%s\\Config",FalconDataDirectory); ResAddPath(tmpPath,FALSE); sprintf(tmpPath,"%s\\Art",FalconDataDirectory); ResAddPath(tmpPath,TRUE); sprintf(tmpPath,"%s\\sim",FalconDataDirectory); ResAddPath(tmpPath,TRUE); ResSetDirectory(FalconDataDirectory); LoadTheaterList(); if(td = g_theaters.GetCurrentTheater()) g_theaters.SetNewTheater(td); if(argc > 1) if(!stricmp(argv[1],"-auto")) bAuto = TRUE; #ifndef F4SEASONSWITCH if(!bAuto) { retval = MessageBox( NULL, "Do you wish to recompress all textures? Selecting yes will overwrite all existing dds textures.", "Recompress?", MB_YESNO | MB_ICONEXCLAMATION); if(retval == IDNO) bForce = FALSE; } #endif DeviceIndependentGraphicsSetup(FalconTerrainDataDir,Falcon3DDataDir,FalconMiscTexDataDir); //F4CompressGraphicsSetup(&FalconDisplay.theDisplayDevice,bForce); #ifdef F4SEASONSWITCH printf("One of the following seasons will be applied to terrain during compression:\n"); printf("0)Summer, 1)Autumn, 2)Winter, 3)Spring\n"); printf("Please select one of the above: "); char ch = getchar(); season = min(max(atoi(&ch),0),3); TheTerrTextures.SyncDDSTextures(TRUE); TheTerrTextures.Cleanup(); TheFarTextures.SyncDDSTextures(TRUE); TheFarTextures.Cleanup(); #else if(bAuto) { TheTerrTextures.SyncDDSTextures(TRUE); TheTerrTextures.Cleanup(); TheFarTextures.SyncDDSTextures(TRUE); TheFarTextures.Cleanup(); } TheTextureBank.SyncDDSTextures(bForce); TheTextureBank.Cleanup(); #endif if(!bAuto) MessageBox( NULL, "All operations completed successfully.", "F4Compress", MB_OK); //SAFE_DELETE(TheWeather); //if (realWeather != NULL) //delete ((WeatherClass*)realWeather); return 1; }
27.178218
103
0.729326
IsraelyFlightSimulator
959a5325d288d1a44510774065188038773ed876
771
hpp
C++
core/include/giygas/RenderPass.hpp
galaxgames/giygas
af0147d737f5fea6a4653f98df44594f55d76d58
[ "Apache-2.0" ]
1
2017-08-29T17:09:30.000Z
2017-08-29T17:09:30.000Z
core/include/giygas/RenderPass.hpp
galaxgames/giygas
af0147d737f5fea6a4653f98df44594f55d76d58
[ "Apache-2.0" ]
null
null
null
core/include/giygas/RenderPass.hpp
galaxgames/giygas
af0147d737f5fea6a4653f98df44594f55d76d58
[ "Apache-2.0" ]
null
null
null
#pragma once #include <cstddef> #include "AttachmentPurpose.hpp" #include "RenderTarget.hpp" namespace giygas { class RenderPassAttachment { public: AttachmentPurpose purpose; const RenderTarget *target; }; class RenderPassCreateParameters { public: uint32_t attachment_count; const RenderPassAttachment *attachments; }; class RenderPass { public: virtual ~RenderPass() = default; virtual RendererType renderer_type() const = 0; virtual void create(const RenderPassCreateParameters &params) = 0; virtual bool is_valid() const = 0; virtual uint32_t attachment_count() const = 0; virtual const AttachmentPurpose *attachment_purposes() const = 0; }; }
24.870968
74
0.670558
galaxgames
959c58d6d25c6fae6c9a78930f7371845eb3733b
270
cc
C++
string.cc
garryFromGermany/shared_with_phil
fea4b0243d3c9f559cab0b8864472743851630c5
[ "MIT" ]
null
null
null
string.cc
garryFromGermany/shared_with_phil
fea4b0243d3c9f559cab0b8864472743851630c5
[ "MIT" ]
null
null
null
string.cc
garryFromGermany/shared_with_phil
fea4b0243d3c9f559cab0b8864472743851630c5
[ "MIT" ]
null
null
null
#include<iostream> #include<string> using namespace std; //ohne das funktioniert string nicht! int main(int argc, char const *argv[]) { string hallo = "hallo"; string _welt = " Welt"; string botschaft = hallo + _welt; std::cout << botschaft << '\n'; return 0; }
18
60
0.674074
garryFromGermany
95a416c4b0b02741af8f1d632eced45893801dfe
474
cpp
C++
CAX/gm_cloudauthx/bootil/src/Bootil/File/System.cpp
kurozael/project-archive
dcac1a9a8dee65c11f4a631ec08d6eef320f5ad0
[ "MIT" ]
13
2021-06-30T15:47:33.000Z
2021-09-18T15:44:34.000Z
lib/GWEN-master/gwen/src/Bootil/File/System.cpp
mpavlinsky/bobsgame
dd4c0713828594ef601c61785164b3fa41e27e2a
[ "Unlicense" ]
null
null
null
lib/GWEN-master/gwen/src/Bootil/File/System.cpp
mpavlinsky/bobsgame
dd4c0713828594ef601c61785164b3fa41e27e2a
[ "Unlicense" ]
7
2021-06-30T17:14:41.000Z
2021-10-14T01:41:18.000Z
#include "Bootil/Bootil.h" namespace Bootil { BOOTIL_EXPORT File::System FileSystem( "" ); namespace File { System::System() { } System::System( BString strInitalPath ) { AddPath( strInitalPath ); } void System::AddPath( BString strPath ) { // Clean Path strPath = File::RelativeToAbsolute( strPath ); String::Util::TrimRight( strPath, "/" ); String::Util::TrimRight( strPath, "\\" ); m_Paths.push_back( strPath + "/" ); } } }
15.290323
49
0.624473
kurozael
95a76c4340c52efd3aa26ea52e35f606abe5f3df
706
hpp
C++
meta/include/mgs/meta/concepts/equality_comparable.hpp
theodelrieu/mgs
965a95e3d539447cc482e915f9c44b3439168a4e
[ "BSL-1.0" ]
24
2020-07-01T13:45:50.000Z
2021-11-04T19:54:47.000Z
meta/include/mgs/meta/concepts/equality_comparable.hpp
theodelrieu/mgs
965a95e3d539447cc482e915f9c44b3439168a4e
[ "BSL-1.0" ]
null
null
null
meta/include/mgs/meta/concepts/equality_comparable.hpp
theodelrieu/mgs
965a95e3d539447cc482e915f9c44b3439168a4e
[ "BSL-1.0" ]
null
null
null
#pragma once #include <tuple> #include <type_traits> #include <mgs/meta/concepts/weakly_equality_comparable_with.hpp> namespace mgs { namespace meta { template <typename T> struct is_equality_comparable : is_weakly_equality_comparable_with<T, T> { using requirements = std::tuple<>; static constexpr int trigger_static_asserts() { static_assert(is_equality_comparable::value, "T does not model meta::equality_comparable"); return 1; } }; template <typename T> constexpr auto is_equality_comparable_v = is_equality_comparable<T>::value; template <typename T, typename = std::enable_if_t<is_equality_comparable<T>::value>> using equality_comparable = T; } }
21.393939
75
0.74221
theodelrieu
95a857c5e72e53b07287cb36ae32db8f5a01a644
307
cpp
C++
aoj/volume0/n0013/Main.cpp
KoKumagai/exercises
256b226d3e094f9f67352d75619b392a168eb4d1
[ "MIT" ]
null
null
null
aoj/volume0/n0013/Main.cpp
KoKumagai/exercises
256b226d3e094f9f67352d75619b392a168eb4d1
[ "MIT" ]
null
null
null
aoj/volume0/n0013/Main.cpp
KoKumagai/exercises
256b226d3e094f9f67352d75619b392a168eb4d1
[ "MIT" ]
null
null
null
#include <iostream> #include <stack> using namespace std; int main() { stack<int> stack; int num; while (cin >> num) { if (num == 0) { cout << stack.top() << endl; stack.pop(); } else { stack.push(num); } } return 0; }
12.28
40
0.436482
KoKumagai
95b308f9a7b9c2c544e4ee5538f492d7d5ecd25a
627
cpp
C++
src/entity.cpp
Necrys/ecs
e5805f08adf82fb716650c56a0debd035ccb9719
[ "MIT" ]
null
null
null
src/entity.cpp
Necrys/ecs
e5805f08adf82fb716650c56a0debd035ccb9719
[ "MIT" ]
null
null
null
src/entity.cpp
Necrys/ecs
e5805f08adf82fb716650c56a0debd035ccb9719
[ "MIT" ]
null
null
null
#include "entity.h" namespace ecs { entity::entity( const eid_t id, registry* owner ): m_owner( owner ), m_id( id ) { } entity::entity( const entity& e ): m_owner( e.m_owner ), m_id( e.m_id ) { } entity::entity( entity&& e ): m_owner( e.m_owner ), m_id( e.m_id ) { } entity& entity::operator=( const entity& e ) { m_owner = e.m_owner; m_id = e.m_id; return *this; } entity& entity::operator=( entity&& e ) { m_owner = e.m_owner; m_id = e.m_id; return *this; } eid_t entity::id() const { return m_id; } registry* entity::owner() { return m_owner; } }
15.292683
51
0.572568
Necrys
95b774c9b5927e837ff8d4de0dff1a6289970ec2
651
hpp
C++
core/include/giygas/Vector2.hpp
galaxgames/giygas
af0147d737f5fea6a4653f98df44594f55d76d58
[ "Apache-2.0" ]
1
2017-08-29T17:09:30.000Z
2017-08-29T17:09:30.000Z
core/include/giygas/Vector2.hpp
galaxgames/giygas
af0147d737f5fea6a4653f98df44594f55d76d58
[ "Apache-2.0" ]
null
null
null
core/include/giygas/Vector2.hpp
galaxgames/giygas
af0147d737f5fea6a4653f98df44594f55d76d58
[ "Apache-2.0" ]
null
null
null
#pragma once #include <giygas/export.h> namespace giygas { class GIYGAS_EXPORT Vector2 { public: float x, y; Vector2() = default; // Default in header to allow default value initialization Vector2(float x, float y); Vector2 operator+(const Vector2 &other) const; Vector2 &operator+=(const Vector2 &other); Vector2 operator-(const Vector2 &other) const; Vector2 &operator-=(const Vector2 &other); Vector2 operator-() const; Vector2 operator*(float scalar) const; Vector2 &operator*=(float scalar); Vector2 scale(const Vector2 &other) const; }; }
28.304348
88
0.634409
galaxgames
95c55c159b6f0382184069739e893e44d0bdb1e7
657
cpp
C++
luogu/1353.cpp
swwind/code
25c4c5ca2f8578ba792b44cbdf44286d39dfb7e0
[ "WTFPL" ]
3
2017-09-17T09:12:50.000Z
2018-04-06T01:18:17.000Z
luogu/1353.cpp
swwind/code
25c4c5ca2f8578ba792b44cbdf44286d39dfb7e0
[ "WTFPL" ]
null
null
null
luogu/1353.cpp
swwind/code
25c4c5ca2f8578ba792b44cbdf44286d39dfb7e0
[ "WTFPL" ]
null
null
null
#include <bits/stdc++.h> #define N 10020 #define ll long long using namespace std; inline int read(){ int x=0,f=1;char ch=getchar(); while(ch>'9'||ch<'0')ch=='-'&&(f=0)||(ch=getchar()); while(ch<='9'&&ch>='0')x=(x<<3)+(x<<1)+ch-'0',ch=getchar(); return f?x:-x; } int d[N], f[N][520]; int main(int argc, char const *argv[]) { // freopen("test.in", "r", stdin); int n = read(), m = read(); for (int i = 1; i <= n; i++) d[i] = read(); for (int i = 1; i <= n; i++) { f[i][0] = f[i-1][0]; for (int j = 1; j <= m; j++) { if (i-j > 0) f[i][0] = max(f[i-j][j], f[i][0]); f[i][j] = f[i-1][j-1]+d[i]; } } printf("%d\n", f[n][0]); return 0; }
24.333333
60
0.480974
swwind
95cb4bc38f61158f67c6779d526c38da45b8ecc4
5,108
cc
C++
Sources/OpenGL sb6/Chapter12/_1214_bumpmap.cc
liliilli/SH-GraphicsStudy
314af5ad6ec04b91ec86978c60cc2f96db6a1d7c
[ "Unlicense" ]
3
2019-11-23T16:37:22.000Z
2021-05-02T20:43:27.000Z
Sources/OpenGL sb6/Chapter12/_1214_bumpmap.cc
liliilli/SH-GraphicsStudy
314af5ad6ec04b91ec86978c60cc2f96db6a1d7c
[ "Unlicense" ]
3
2018-05-01T04:52:39.000Z
2018-05-10T02:14:46.000Z
Sources/OpenGL sb6/Chapter12/_1214_bumpmap.cc
liliilli/GraphicsStudy
314af5ad6ec04b91ec86978c60cc2f96db6a1d7c
[ "Unlicense" ]
2
2019-11-23T16:37:38.000Z
2022-03-29T10:33:32.000Z
#include <sb6.h> #include <vmath.h> #include <object.h> #include <sb6ktx.h> #include <shader.h> #include <cstdio> class BumpMapping final : public sb6::application { protected: void init() override final { application::init(); constexpr char title[] = "OpenGL SuperBible - Bump Mapping"; memcpy(info.title, title, sizeof(title)); } void startup() override final { LoadShaders(); using sb6::ktx::file::load; glActiveTexture(GL_TEXTURE0); textures.color = load("media/textures/ladybug_co.ktx"); glActiveTexture(GL_TEXTURE1); textures.normals = load("media/textures/ladybug_nm.ktx"); object.load("media/objects/ladybug.sbm"); proj_matrix = vmath::perspective(50.0f, (float)info.windowWidth / (float)info.windowHeight, 0.1f, 1000.0f); } void render(double currentTime) override final { static const GLfloat zeros[] = { 0.0f, 0.0f, 0.0f, 0.0f }; static const GLfloat gray[] = { 0.1f, 0.1f, 0.1f, 0.0f }; static const GLfloat ones[] = { 1.0f }; static double last_time = 0.0; static double total_time = 0.0; if (!paused) total_time += (currentTime - last_time); last_time = currentTime; glClearBufferfv(GL_COLOR, 0, gray); glClearBufferfv(GL_DEPTH, 0, ones); glViewport(0, 0, info.windowWidth, info.windowHeight); glEnable(GL_DEPTH_TEST); glUseProgram(program); glUniformMatrix4fv(uniforms.proj_matrix, 1, GL_FALSE, proj_matrix); vmath::mat4 mv_matrix = vmath::translate(0.0f, -0.2f, -5.5f) * vmath::rotate(14.5f, 1.0f, 0.0f, 0.0f) * vmath::rotate(-20.0f, 0.0f, 1.0f, 0.0f) * vmath::mat4::identity(); glUniformMatrix4fv(uniforms.mv_matrix, 1, GL_FALSE, mv_matrix); const auto f = static_cast<float>(total_time); glUniform3fv(uniforms.light_pos, 1, vmath::vec3(40.0f * sinf(f), 30.0f + 20.0f * cosf(f), 40.0f)); object.render(); } void onKey(int key, int action) override final { if (action) { switch (key) { case 'R': LoadShaders(); break; case 'S': MakeScreenshot(); break; case 'P': paused = !paused; break; default: break; } } } void LoadShaders() { auto vs = sb6::shader::load("media/shaders/bumpmapping/bumpmapping.vs.glsl", GL_VERTEX_SHADER); auto fs = sb6::shader::load("media/shaders/bumpmapping/bumpmapping.fs.glsl", GL_FRAGMENT_SHADER); if (program) glDeleteProgram(program); program = glCreateProgram(); glAttachShader(program, vs); glAttachShader(program, fs); glLinkProgram(program); uniforms.mv_matrix = glGetUniformLocation(program, "mv_matrix"); uniforms.proj_matrix = glGetUniformLocation(program, "proj_matrix"); uniforms.light_pos = glGetUniformLocation(program, "light_pos"); } void MakeScreenshot(); vmath::mat4 proj_matrix; GLuint program{}; struct { GLuint color; GLuint normals; } textures; struct { GLint mv_matrix; GLint proj_matrix; GLint light_pos; } uniforms; bool paused{ false }; sb6::object object; }; void BumpMapping::MakeScreenshot() { int row_size = ((info.windowWidth * 3 + 3) & ~3); int data_size = row_size * info.windowHeight; unsigned char * data = new unsigned char [data_size]; #pragma pack (push, 1) struct { unsigned char identsize; // Size of following ID field unsigned char cmaptype; // Color map type 0 = none unsigned char imagetype; // Image type 2 = rgb short cmapstart; // First entry in palette short cmapsize; // Fumber of entries in palette unsigned char cmapbpp; // Number of bits per palette entry short xorigin; // X origin short yorigin; // Y origin short width; // Width in pixels short height; // Height in pixels unsigned char bpp; // Bits per pixel unsigned char descriptor; // Descriptor bits } tga_header; #pragma pack (pop) glReadPixels(0, 0, // Origin info.windowWidth, info.windowHeight, // Size GL_BGR, GL_UNSIGNED_BYTE, // Format, type data); // Data memset(&tga_header, 0, sizeof(tga_header)); tga_header.imagetype = 2; tga_header.width = (short)info.windowWidth; tga_header.height = (short)info.windowHeight; tga_header.bpp = 24; FILE * f_out = fopen("screenshot.tga", "wb"); fwrite(&tga_header, sizeof(tga_header), 1, f_out); fwrite(data, data_size, 1, f_out); fclose(f_out); delete [] data; } DECLARE_MAIN(BumpMapping)
33.385621
115
0.575959
liliilli
95d10dd36caaa19a16a1b66676be84296154bb23
1,540
cpp
C++
tests/userio_vadd_prbs_test/src_pers/PersPrbsTx_prim.cpp
TonyBrewer/OpenHT
63898397de4d303ba514d88b621cc91367ffe2a6
[ "BSD-3-Clause" ]
13
2015-02-26T22:46:18.000Z
2020-03-24T11:53:06.000Z
tests/userio_vadd_prbs_test/src_pers/PersPrbsTx_prim.cpp
PacificBiosciences/OpenHT
63898397de4d303ba514d88b621cc91367ffe2a6
[ "BSD-3-Clause" ]
5
2016-02-25T17:08:19.000Z
2018-01-20T15:24:36.000Z
tests/userio_vadd_prbs_test/src_pers/PersPrbsTx_prim.cpp
TonyBrewer/OpenHT
63898397de4d303ba514d88b621cc91367ffe2a6
[ "BSD-3-Clause" ]
12
2015-04-13T21:39:54.000Z
2021-01-15T01:00:13.000Z
#include "Ht.h" #include "PersPrbsTx_prim.h" ht_prim ht_clk("clk") void prbs_gen ( bool const & rst, bool const & i_req, bool & o_rdy, bool & o_vld, ht_uint64 & o_res_lower, ht_uint64 & o_res_upper, prbs_gen_prm_state &s) { #ifndef _HTV // NOTE! This does not accurately model the verilog. // This cheats and does a much less strenous sequence // Modeling the PRBS pattern in SystemC was deemed not critical for (int i = 1; i > 0; i--) { s.rnd_upper[i] = (rst) ? (ht_uint64)0x0123456789ABCDEFLL : s.rnd_upper[i - 1]; s.rnd_lower[i] = (rst) ? (ht_uint64)0xFEDCBA9876543210LL : s.rnd_lower[i - 1]; } // Shift Operation (only advance with request) ht_uint64 newUpper, newLower; newUpper = (ht_uint64)( (s.rnd_upper[1] << 1) | (s.rnd_lower[1] >> 63) & 0x1LL ); newLower = (ht_uint64)( (s.rnd_lower[1] << 1) | ( ((s.rnd_upper[1] >> 63) & 0x1) ^ ((s.rnd_upper[1] >> 61) & 0x1) ^ ((s.rnd_upper[1] >> 36) & 0x1) ^ ((s.rnd_upper[1] >> 34) & 0x1) ) ); // Inputs are valid on the inital input stage - (Stage 1) // Output is valid 1 cycles later - (Stage 2) // p is valid on Stage 2 o_rdy = !rst; o_vld = s.vld[0]; o_res_lower = s.res_lower[0]; o_res_upper = s.res_upper[0]; if (i_req) { s.res_lower[0] = s.rnd_lower[0]; s.res_upper[0] = s.rnd_upper[0]; s.rnd_lower[0] = newLower; s.rnd_upper[0] = newUpper; } else { s.rnd_lower[0] = s.rnd_lower[1]; s.rnd_upper[0] = s.rnd_upper[1]; } s.vld[0] = i_req; #endif }
24.0625
80
0.604545
TonyBrewer
95d401c3b53c01ad8110a4d8e7d1f987e889a3b0
1,046
cpp
C++
YorozuyaGSLib/source/si_effect.cpp
lemkova/Yorozuya
f445d800078d9aba5de28f122cedfa03f26a38e4
[ "MIT" ]
29
2017-07-01T23:08:31.000Z
2022-02-19T10:22:45.000Z
YorozuyaGSLib/source/si_effect.cpp
kotopes/Yorozuya
605c97d3a627a8f6545cc09f2a1b0a8afdedd33a
[ "MIT" ]
90
2017-10-18T21:24:51.000Z
2019-06-06T02:30:33.000Z
YorozuyaGSLib/source/si_effect.cpp
kotopes/Yorozuya
605c97d3a627a8f6545cc09f2a1b0a8afdedd33a
[ "MIT" ]
44
2017-12-19T08:02:59.000Z
2022-02-24T23:15:01.000Z
#include <si_effect.hpp> START_ATF_NAMESPACE char si_effect::GetCountOfEffect() { using org_ptr = char (WINAPIV*)(struct si_effect*); return (org_ptr(0x1402e3c90L))(this); }; char si_effect::GetCountOfItem() { using org_ptr = char (WINAPIV*)(struct si_effect*); return (org_ptr(0x1402e3c00L))(this); }; void si_effect::init() { using org_ptr = void (WINAPIV*)(struct si_effect*); (org_ptr(0x1402e3690L))(this); }; void si_effect::set_effect_count_info(char byCountOfItem, char byCountOfEffect) { using org_ptr = void (WINAPIV*)(struct si_effect*, char, char); (org_ptr(0x1402e3b30L))(this, byCountOfItem, byCountOfEffect); }; si_effect::si_effect() { using org_ptr = void (WINAPIV*)(struct si_effect*); (org_ptr(0x1402e3640L))(this); }; void si_effect::ctor_si_effect() { using org_ptr = void (WINAPIV*)(struct si_effect*); (org_ptr(0x1402e3640L))(this); }; END_ATF_NAMESPACE
29.055556
83
0.628107
lemkova
95eb7755a67419b34ccfc95eff5645104063a4da
5,050
cpp
C++
LibSharpPhysX/Generated/PxVec2.cpp
Alan-FGR/SharpPhysX
9b6b49d34c94e2fd165ff50795ae36b32149751b
[ "MIT" ]
23
2019-03-17T17:35:06.000Z
2022-01-12T01:54:43.000Z
LibSharpPhysX/Generated/PxVec2.cpp
Alan-FGR/SharpPhysX
9b6b49d34c94e2fd165ff50795ae36b32149751b
[ "MIT" ]
1
2019-05-10T22:14:33.000Z
2019-05-10T22:48:29.000Z
LibSharpPhysX/Generated/PxVec2.cpp
Alan-FGR/SharpPhysX
9b6b49d34c94e2fd165ff50795ae36b32149751b
[ "MIT" ]
5
2019-03-17T17:36:03.000Z
2021-08-06T06:42:58.000Z
// Generated by minBND 5.1.94.90 - © github.com/Alan-FGR ES void PxVec2_operator_Ptr_Star_float_PxVec2_(physx::PxVec2* nRetRef, float wrp_f, physx::PxVec2* wrp_v){ *nRetRef = ::physx::operator*(wrp_f, *wrp_v); } ES void void_PxVec2_PxVec2Ptr_Ctor(physx::PxVec2* wrp_this){ *wrp_this = ::physx::PxVec2::PxVec2(); } ES void void_PxVec2_PxVec2Ptr_Ctor_PxZERO_(physx::PxVec2* wrp_this, physx::PxZERO wrp_r){ *wrp_this = ::physx::PxVec2::PxVec2(wrp_r); } ES void void_PxVec2_PxVec2Ptr_Ctor_float_(physx::PxVec2* wrp_this, float wrp_a){ *wrp_this = ::physx::PxVec2::PxVec2(wrp_a); } ES void void_PxVec2_PxVec2Ptr_Ctor_float_float_(physx::PxVec2* wrp_this, float wrp_nx, float wrp_ny){ *wrp_this = ::physx::PxVec2::PxVec2(wrp_nx, wrp_ny); } ES void void_PxVec2_PxVec2Ptr_Ctor_PxVec2_(physx::PxVec2* wrp_this, physx::PxVec2* wrp_v){ *wrp_this = ::physx::PxVec2::PxVec2(*wrp_v); } ES physx::PxVec2* PxVec2_PxVec2_operator_Ptr_Equal_PxVec2_(physx::PxVec2* wrp_lhs, physx::PxVec2* wrp_p){ return (physx::PxVec2*) &wrp_lhs->::physx::PxVec2::operator=(*wrp_p); } ES float* float_PxVec2_operator_Ptr_Subscript_int_(physx::PxVec2* wrp_lhs, int wrp_index){ return (float*) &wrp_lhs->::physx::PxVec2::operator[](wrp_index); } ES float* float_const_PxVec2_operator_Ptr_Subscript_int_(physx::PxVec2* wrp_lhs, int wrp_index){ return (float*) &wrp_lhs->::physx::PxVec2::operator[](wrp_index); } ES bool bool_const_PxVec2_operator_Ptr_EqualEqual_PxVec2_(physx::PxVec2* wrp_lhs, physx::PxVec2* wrp_v){ return (bool) wrp_lhs->::physx::PxVec2::operator==(*wrp_v); } ES bool bool_const_PxVec2_operator_Ptr_ExclaimEqual_PxVec2_(physx::PxVec2* wrp_lhs, physx::PxVec2* wrp_v){ return (bool) wrp_lhs->::physx::PxVec2::operator!=(*wrp_v); } ES bool bool_const_PxVec2_isZeroPtr(physx::PxVec2* wrp_this){ return (bool) wrp_this->isZero(); } ES bool bool_const_PxVec2_isFinitePtr(physx::PxVec2* wrp_this){ return (bool) wrp_this->isFinite(); } ES bool bool_const_PxVec2_isNormalizedPtr(physx::PxVec2* wrp_this){ return (bool) wrp_this->isNormalized(); } ES float float_const_PxVec2_magnitudeSquaredPtr(physx::PxVec2* wrp_this){ return (float) wrp_this->magnitudeSquared(); } ES float float_const_PxVec2_magnitudePtr(physx::PxVec2* wrp_this){ return (float) wrp_this->magnitude(); } ES void PxVec2_const_PxVec2_operator_Ptr_Minus(physx::PxVec2* nRetRef, physx::PxVec2* wrp_lhs){ *nRetRef = wrp_lhs->::physx::PxVec2::operator-(); } ES void PxVec2_const_PxVec2_operator_Ptr_Plus_PxVec2_(physx::PxVec2* nRetRef, physx::PxVec2* wrp_lhs, physx::PxVec2* wrp_v){ *nRetRef = wrp_lhs->::physx::PxVec2::operator+(*wrp_v); } ES void PxVec2_const_PxVec2_operator_Ptr_Minus_PxVec2_(physx::PxVec2* nRetRef, physx::PxVec2* wrp_lhs, physx::PxVec2* wrp_v){ *nRetRef = wrp_lhs->::physx::PxVec2::operator-(*wrp_v); } ES void PxVec2_const_PxVec2_operator_Ptr_Star_float_(physx::PxVec2* nRetRef, physx::PxVec2* wrp_lhs, float wrp_f){ *nRetRef = wrp_lhs->::physx::PxVec2::operator*(wrp_f); } ES void PxVec2_const_PxVec2_operator_Ptr_Slash_float_(physx::PxVec2* nRetRef, physx::PxVec2* wrp_lhs, float wrp_f){ *nRetRef = wrp_lhs->::physx::PxVec2::operator/(wrp_f); } ES physx::PxVec2* PxVec2_PxVec2_operator_Ptr_PlusEqual_PxVec2_(physx::PxVec2* wrp_lhs, physx::PxVec2* wrp_v){ return (physx::PxVec2*) &wrp_lhs->::physx::PxVec2::operator+=(*wrp_v); } ES physx::PxVec2* PxVec2_PxVec2_operator_Ptr_MinusEqual_PxVec2_(physx::PxVec2* wrp_lhs, physx::PxVec2* wrp_v){ return (physx::PxVec2*) &wrp_lhs->::physx::PxVec2::operator-=(*wrp_v); } ES physx::PxVec2* PxVec2_PxVec2_operator_Ptr_StarEqual_float_(physx::PxVec2* wrp_lhs, float wrp_f){ return (physx::PxVec2*) &wrp_lhs->::physx::PxVec2::operator*=(wrp_f); } ES physx::PxVec2* PxVec2_PxVec2_operator_Ptr_SlashEqual_float_(physx::PxVec2* wrp_lhs, float wrp_f){ return (physx::PxVec2*) &wrp_lhs->::physx::PxVec2::operator/=(wrp_f); } ES float float_const_PxVec2_dotPtr_PxVec2_(physx::PxVec2* wrp_this, physx::PxVec2* wrp_v){ return (float) wrp_this->dot(*wrp_v); } ES void PxVec2_const_PxVec2_getNormalizedPtr(physx::PxVec2* nRetRef, physx::PxVec2* wrp_this){ *nRetRef = wrp_this->getNormalized(); } ES float float_PxVec2_normalizePtr(physx::PxVec2* wrp_this){ return (float) wrp_this->normalize(); } ES void PxVec2_const_PxVec2_multiplyPtr_PxVec2_(physx::PxVec2* nRetRef, physx::PxVec2* wrp_this, physx::PxVec2* wrp_a){ *nRetRef = wrp_this->multiply(*wrp_a); } ES void PxVec2_const_PxVec2_minimumPtr_PxVec2_(physx::PxVec2* nRetRef, physx::PxVec2* wrp_this, physx::PxVec2* wrp_v){ *nRetRef = wrp_this->minimum(*wrp_v); } ES float float_const_PxVec2_minElementPtr(physx::PxVec2* wrp_this){ return (float) wrp_this->minElement(); } ES void PxVec2_const_PxVec2_maximumPtr_PxVec2_(physx::PxVec2* nRetRef, physx::PxVec2* wrp_this, physx::PxVec2* wrp_v){ *nRetRef = wrp_this->maximum(*wrp_v); } ES float float_const_PxVec2_maxElementPtr(physx::PxVec2* wrp_this){ return (float) wrp_this->maxElement(); }
37.407407
125
0.749703
Alan-FGR
95f9155a89c822ebf1eea86e6a52bcdec8cca45f
2,007
cpp
C++
win32-OpenGL/Math/MyMath.cpp
Peanoquio/fuzzy-logic-demo
100a64094adb2d5274c32761ed4ede15b912dd90
[ "MIT" ]
null
null
null
win32-OpenGL/Math/MyMath.cpp
Peanoquio/fuzzy-logic-demo
100a64094adb2d5274c32761ed4ede15b912dd90
[ "MIT" ]
null
null
null
win32-OpenGL/Math/MyMath.cpp
Peanoquio/fuzzy-logic-demo
100a64094adb2d5274c32761ed4ede15b912dd90
[ "MIT" ]
null
null
null
/******************************************************************************/ /*! \file MyMath.cpp \author Oliver Ryan Chong \par email: oliver.chong\@digipen.edu \par oliver.chong 900863 \par Course: CS1250 \par Project #01 \date 12/12/2011 \brief This contains general math functions such as converting degree to radians and vice-versa Copyright (C) 2011 DigiPen Institute of Technology Singapore */ /******************************************************************************/ #include "MyMath.h" namespace Math { /******************************************************************************/ /*! \brief Converts an angle from degrees to radians \param value the value in degrees \return */ /******************************************************************************/ float DegreeToRadian(float value) { return value * PI / 180.0F; } /******************************************************************************/ /*! \brief Converts an angle from radians to degrees \param value the value in radians \return */ /******************************************************************************/ float RadianToDegree(float value) { return value * 180.0F / PI; } /******************************************************************************/ /*! \brief Compares whether two floating point values are similar \param lhsValue the floating point value \param rhsValue the floating point value \return */ /******************************************************************************/ const bool FloatValueSame( const float lhsValue, const float rhsValue ) { float differenceVal = lhsValue - rhsValue; //get the positive values of the difference if ( differenceVal < 0.0F ) { differenceVal *= -1.0F; } //validate the difference against the Epsilon value that will allow a certain margin of difference if ( differenceVal > Math::EPSILON ) { return false; } else { return true; } } } //end namespace Math
23.337209
100
0.476831
Peanoquio
95fbbfdc15a491fb2611c6246bdd215a3e5bc6fe
723
hpp
C++
includes/function.hpp
ggjulio/ft_containers
77e221965e9c0813a4e20673d82eaa84814fe369
[ "MIT" ]
null
null
null
includes/function.hpp
ggjulio/ft_containers
77e221965e9c0813a4e20673d82eaa84814fe369
[ "MIT" ]
null
null
null
includes/function.hpp
ggjulio/ft_containers
77e221965e9c0813a4e20673d82eaa84814fe369
[ "MIT" ]
null
null
null
#ifndef FUNCTION_HPP #define FUNCTION_HPP namespace ft { template <typename T> struct _Identity : public std::unary_function<T, T> { T &operator()(T &__x) const { return __x; } const T &operator()(const T &__x) const { return __x; } }; // Partial specialization, avoids confusing errors in e.g. std::set<const T>. template <typename T> struct _Identity<const T> : _Identity<T> {}; template <typename Pair> struct _Select1st : public std::unary_function<Pair, typename Pair::first_type> { typename Pair::first_type & operator()(Pair &__x) const { return __x.first; } const typename Pair::first_type & operator()(const Pair &__x) const { return __x.first;} }; } /* namespace ft */ #endif /* FUNCTION_HPP */
24.1
77
0.704011
ggjulio
95fbf95f5c0018f113b5ae5e3df3964b94ed1255
3,380
cpp
C++
src/ros_node.cpp
pcdangio/ros-interface_quad_encoder
af2cc49acbde8f5684a65b16a18f50d54d0cdc87
[ "MIT" ]
null
null
null
src/ros_node.cpp
pcdangio/ros-interface_quad_encoder
af2cc49acbde8f5684a65b16a18f50d54d0cdc87
[ "MIT" ]
1
2019-05-26T18:25:43.000Z
2019-05-26T18:25:43.000Z
src/ros_node.cpp
pcdangio/ros-interface_quad_encoder
af2cc49acbde8f5684a65b16a18f50d54d0cdc87
[ "MIT" ]
null
null
null
#include "ros_node.h" #include <sensor_msgs_ext/axis_state.h> // CONSTRUCTORS ros_node::ros_node(const std::shared_ptr<driver>& device_driver) { // Store the device driver. ros_node::m_driver = device_driver; // Read parameters. ros::NodeHandle private_node("~"); int param_gpio_a = private_node.param<int>("gpio_pin_a", 0); int param_gpio_b = private_node.param<int>("gpio_pin_b", 0); int param_ppr = private_node.param<int>("ppr", 200); ros_node::p_publish_rate = private_node.param<double>("publish_rate", 30); // Set up the publishers. ros_node::m_publisher_position = ros_node::m_node.advertise<sensor_msgs_ext::axis_state>("axis_state", 1); // Set up the services. ros_node::m_service_set_home = private_node.advertiseService("set_home", &ros_node::service_set_home, this); // Initialize the driver. try { ros_node::m_driver->initialize(static_cast<unsigned int>(param_gpio_a), static_cast<unsigned int>(param_gpio_b), static_cast<unsigned int>(param_ppr)); ROS_INFO_STREAM("encoder initialized successfully on pins " << param_gpio_a << " and " << param_gpio_b << "."); } catch (std::exception& e) { ROS_FATAL_STREAM("failed to initialize driver (" << e.what() << ")"); ros::shutdown(); } } // METHODS void ros_node::spin() { // Set up loop rate. ros::Rate loop_rate(ros_node::p_publish_rate); // Set up tracking for velocity/accleration calculations. ros_node::m_prior_time = ros::Time::now(); ros_node::m_prior_position = 0; ros_node::m_prior_velocity = 0; // Monitor changes in missed pulses for logging. uint64_t n_missed_pulses = 0; // Loop. while(ros::ok()) { // Create output axis state message. sensor_msgs_ext::axis_state message; // Calculate delta time since last measurement. ros::Time current_time = ros::Time::now(); double_t dt = (current_time - ros_node::m_prior_time).toSec(); // Get the position measurement from the driver. message.position = ros_node::m_driver->get_position(); // Calculate velocity and acceleration. message.velocity = (message.position - ros_node::m_prior_position) / dt; message.acceleration = (message.velocity - ros_node::m_prior_velocity) / dt; // Update priors. ros_node::m_prior_time = current_time; ros_node::m_prior_position = message.position; ros_node::m_prior_velocity = message.velocity; // Publish the message. ros_node::m_publisher_position.publish(message); // Log any missed pulses. if(n_missed_pulses != ros_node::m_driver->pulses_missed()) { ROS_WARN_STREAM("missed " << ros_node::m_driver->pulses_missed() - n_missed_pulses << " pulses"); // Update the last known pulses missed. n_missed_pulses = ros_node::m_driver->pulses_missed(); } // Sleep until next time iteration. loop_rate.sleep(); } } bool ros_node::service_set_home(sensor_msgs_ext::set_axis_homeRequest &request, sensor_msgs_ext::set_axis_homeResponse &response) { // Set the driver's home position. ros_node::m_driver->set_home(); // Reset the prior position to zero to avoid velocity jump. ros_node::m_prior_position = 0; return true; }
34.489796
159
0.667456
pcdangio
95ff7abd8b0480ae9ce37be998e132d94adee237
149,925
cpp
C++
SU2-Quantum/Common/src/geometry/CGeometry.cpp
Agony5757/SU2-Quantum
16e7708371a597511e1242f3a7581e8c4187f5b2
[ "Apache-2.0" ]
null
null
null
SU2-Quantum/Common/src/geometry/CGeometry.cpp
Agony5757/SU2-Quantum
16e7708371a597511e1242f3a7581e8c4187f5b2
[ "Apache-2.0" ]
null
null
null
SU2-Quantum/Common/src/geometry/CGeometry.cpp
Agony5757/SU2-Quantum
16e7708371a597511e1242f3a7581e8c4187f5b2
[ "Apache-2.0" ]
1
2021-12-03T06:40:08.000Z
2021-12-03T06:40:08.000Z
/*! * \file CGeometry.cpp * \brief Implementation of the base geometry class. * \author F. Palacios, T. Economon * \version 7.0.6 "Blackbird" * * SU2 Project Website: https://su2code.github.io * * The SU2 Project is maintained by the SU2 Foundation * (http://su2foundation.org) * * Copyright 2012-2020, SU2 Contributors (cf. AUTHORS.md) * * SU2 is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * SU2 is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with SU2. If not, see <http://www.gnu.org/licenses/>. */ #include "../../include/geometry/CGeometry.hpp" #include "../../include/geometry/elements/CElement.hpp" #include "../../include/omp_structure.hpp" /*--- Cross product ---*/ #define CROSS(dest,v1,v2) \ (dest)[0] = (v1)[1]*(v2)[2] - (v1)[2]*(v2)[1]; \ (dest)[1] = (v1)[2]*(v2)[0] - (v1)[0]*(v2)[2]; \ (dest)[2] = (v1)[0]*(v2)[1] - (v1)[1]*(v2)[0]; /*--- Cross product ---*/ #define DOT(v1,v2) ((v1)[0]*(v2)[0] + (v1)[1]*(v2)[1] + (v1)[2]*(v2)[2]); /*--- a = b - c ---*/ #define SUB(dest,v1,v2) \ (dest)[0] = (v1)[0] - (v2)[0]; \ (dest)[1] = (v1)[1] - (v2)[1]; \ (dest)[2] = (v1)[2] - (v2)[2]; CGeometry::CGeometry(void) : size(SU2_MPI::GetSize()), rank(SU2_MPI::GetRank()) { } CGeometry::~CGeometry(void) { unsigned long iElem, iElem_Bound, iFace, iVertex; unsigned short iMarker; if (elem != nullptr) { for (iElem = 0; iElem < nElem; iElem++) delete elem[iElem]; delete[] elem; } if (bound != nullptr) { for (iMarker = 0; iMarker < nMarker; iMarker++) { for (iElem_Bound = 0; iElem_Bound < nElem_Bound[iMarker]; iElem_Bound++) { delete bound[iMarker][iElem_Bound]; } delete [] bound[iMarker]; } delete [] bound; } if (face != nullptr) { for (iFace = 0; iFace < nFace; iFace ++) delete face[iFace]; delete[] face; } delete nodes; delete edges; if (vertex != nullptr) { for (iMarker = 0; iMarker < nMarker; iMarker++) { for (iVertex = 0; iVertex < nVertex[iMarker]; iVertex++) { delete vertex[iMarker][iVertex]; } delete [] vertex[iMarker]; } delete [] vertex; } delete [] nElem_Bound; delete [] nVertex; delete [] Marker_All_SendRecv; delete [] Tag_to_Marker; delete [] beg_node; delete [] end_node; delete [] nPointLinear; delete [] nPointCumulative; if(CustomBoundaryHeatFlux != nullptr){ for(iMarker=0; iMarker < nMarker; iMarker++){ delete [] CustomBoundaryHeatFlux[iMarker]; } delete [] CustomBoundaryHeatFlux; } if(CustomBoundaryTemperature != nullptr){ for(iMarker=0; iMarker < nMarker; iMarker++){ delete [] CustomBoundaryTemperature[iMarker]; } delete [] CustomBoundaryTemperature; } /*--- Delete structures for MPI point-to-point communication. ---*/ delete [] bufD_P2PRecv; delete [] bufD_P2PSend; delete [] bufS_P2PRecv; delete [] bufS_P2PSend; delete [] req_P2PSend; delete [] req_P2PRecv; delete [] nPoint_P2PRecv; delete [] nPoint_P2PSend; delete [] Neighbors_P2PSend; delete [] Neighbors_P2PRecv; delete [] Local_Point_P2PSend; delete [] Local_Point_P2PRecv; /*--- Delete structures for MPI periodic communication. ---*/ delete [] bufD_PeriodicRecv; delete [] bufD_PeriodicSend; delete [] bufS_PeriodicRecv; delete [] bufS_PeriodicSend; delete [] req_PeriodicSend; delete [] req_PeriodicRecv; delete [] nPoint_PeriodicRecv; delete [] nPoint_PeriodicSend; delete [] Neighbors_PeriodicSend; delete [] Neighbors_PeriodicRecv; delete [] Local_Point_PeriodicSend; delete [] Local_Point_PeriodicRecv; delete [] Local_Marker_PeriodicSend; delete [] Local_Marker_PeriodicRecv; } void CGeometry::PreprocessP2PComms(CGeometry *geometry, CConfig *config) { /*--- We start with the send and receive lists already available in the form of SEND_RECEIVE boundary markers. We will loop through these markers and establish the neighboring ranks and number of send/recv points per pair. We will store this information and set up persistent data structures so that we can reuse them throughout the calculation for any point-to-point communications. The goal is to break the non-blocking comms into InitiateComms() and CompleteComms() in separate routines so that we can overlap the communication and computation to hide the communication latency. ---*/ /*--- Local variables. ---*/ unsigned short iMarker; unsigned long nVertexS, nVertexR, iVertex, MarkerS, MarkerR; int iRank, iSend, iRecv, count; /*--- Create some temporary structures for tracking sends/recvs. ---*/ int *nPoint_Send_All = new int[size+1]; nPoint_Send_All[0] = 0; int *nPoint_Recv_All = new int[size+1]; nPoint_Recv_All[0] = 0; int *nPoint_Flag = new int[size]; for (iRank = 0; iRank < size; iRank++) { nPoint_Send_All[iRank] = 0; nPoint_Recv_All[iRank] = 0; nPoint_Flag[iRank]= -1; } nPoint_Send_All[size] = 0; nPoint_Recv_All[size] = 0; /*--- Loop through all of our SEND_RECEIVE markers and track our sends with each rank. ---*/ for (iMarker = 0; iMarker < config->GetnMarker_All(); iMarker++) { if ((config->GetMarker_All_KindBC(iMarker) == SEND_RECEIVE) && (config->GetMarker_All_SendRecv(iMarker) > 0)) { /*--- Get the destination rank and number of points to send. ---*/ iRank = config->GetMarker_All_SendRecv(iMarker)-1; nVertexS = geometry->nVertex[iMarker]; /*--- If we have not visited this element yet, increment our number of elements that must be sent to a particular proc. ---*/ if ((nPoint_Flag[iRank] != (int)iMarker)) { nPoint_Flag[iRank] = (int)iMarker; nPoint_Send_All[iRank+1] += nVertexS; } } } delete [] nPoint_Flag; /*--- Communicate the number of points to be sent/recv'd amongst all processors. After this communication, each proc knows how many cells it will receive from each other processor. ---*/ SU2_MPI::Alltoall(&(nPoint_Send_All[1]), 1, MPI_INT, &(nPoint_Recv_All[1]), 1, MPI_INT, MPI_COMM_WORLD); /*--- Prepare to send connectivities. First check how many messages we will be sending and receiving. Here we also put the counters into cumulative storage format to make the communications simpler. ---*/ nP2PSend = 0; nP2PRecv = 0; for (iRank = 0; iRank < size; iRank++) { if ((iRank != rank) && (nPoint_Send_All[iRank+1] > 0)) nP2PSend++; if ((iRank != rank) && (nPoint_Recv_All[iRank+1] > 0)) nP2PRecv++; nPoint_Send_All[iRank+1] += nPoint_Send_All[iRank]; nPoint_Recv_All[iRank+1] += nPoint_Recv_All[iRank]; } /*--- Allocate only as much memory as we need for the P2P neighbors. ---*/ nPoint_P2PSend = new int[nP2PSend+1]; nPoint_P2PSend[0] = 0; nPoint_P2PRecv = new int[nP2PRecv+1]; nPoint_P2PRecv[0] = 0; Neighbors_P2PSend = new int[nP2PSend]; Neighbors_P2PRecv = new int[nP2PRecv]; iSend = 0; iRecv = 0; for (iRank = 0; iRank < size; iRank++) { if ((nPoint_Send_All[iRank+1] > nPoint_Send_All[iRank]) && (iRank != rank)) { Neighbors_P2PSend[iSend] = iRank; nPoint_P2PSend[iSend+1] = nPoint_Send_All[iRank+1]; iSend++; } if ((nPoint_Recv_All[iRank+1] > nPoint_Recv_All[iRank]) && (iRank != rank)) { Neighbors_P2PRecv[iRecv] = iRank; nPoint_P2PRecv[iRecv+1] = nPoint_Recv_All[iRank+1]; iRecv++; } } /*--- Create a reverse mapping of the message to the rank so that we can quickly access the correct data in the buffers when receiving messages dynamically. ---*/ P2PSend2Neighbor.clear(); for (iSend = 0; iSend < nP2PSend; iSend++) P2PSend2Neighbor[Neighbors_P2PSend[iSend]] = iSend; P2PRecv2Neighbor.clear(); for (iRecv = 0; iRecv < nP2PRecv; iRecv++) P2PRecv2Neighbor[Neighbors_P2PRecv[iRecv]] = iRecv; delete [] nPoint_Send_All; delete [] nPoint_Recv_All; /*--- Allocate the memory that we need for receiving the conn values and then cue up the non-blocking receives. Note that we do not include our own rank in the communications. We will directly copy our own data later. ---*/ Local_Point_P2PSend = nullptr; Local_Point_P2PSend = new unsigned long[nPoint_P2PSend[nP2PSend]]; for (iSend = 0; iSend < nPoint_P2PSend[nP2PSend]; iSend++) Local_Point_P2PSend[iSend] = 0; Local_Point_P2PRecv = nullptr; Local_Point_P2PRecv = new unsigned long[nPoint_P2PRecv[nP2PRecv]]; for (iRecv = 0; iRecv < nPoint_P2PRecv[nP2PRecv]; iRecv++) Local_Point_P2PRecv[iRecv] = 0; /*--- We allocate the memory for communicating values in a later step once we know the maximum packet size that we need to communicate. This memory is deallocated and reallocated automatically in the case that the previously allocated memory is not sufficient. ---*/ bufD_P2PSend = nullptr; bufD_P2PRecv = nullptr; bufS_P2PSend = nullptr; bufS_P2PRecv = nullptr; /*--- Allocate memory for the MPI requests if we need to communicate. ---*/ if (nP2PSend > 0) { req_P2PSend = new SU2_MPI::Request[nP2PSend]; } if (nP2PRecv > 0) { req_P2PRecv = new SU2_MPI::Request[nP2PRecv]; } /*--- Build lists of local index values for send. ---*/ count = 0; for (iSend = 0; iSend < nP2PSend; iSend++) { for (iMarker = 0; iMarker < config->GetnMarker_All(); iMarker++) { if ((config->GetMarker_All_KindBC(iMarker) == SEND_RECEIVE) && (config->GetMarker_All_SendRecv(iMarker) > 0)) { MarkerS = iMarker; nVertexS = geometry->nVertex[MarkerS]; iRank = config->GetMarker_All_SendRecv(MarkerS)-1; if (iRank == Neighbors_P2PSend[iSend]) { for (iVertex = 0; iVertex < nVertexS; iVertex++) { Local_Point_P2PSend[count] = geometry->vertex[MarkerS][iVertex]->GetNode(); count++; } } } } } /*--- Build lists of local index values for receive. ---*/ count = 0; for (iRecv = 0; iRecv < nP2PRecv; iRecv++) { for (iMarker = 0; iMarker < config->GetnMarker_All(); iMarker++) { if ((config->GetMarker_All_KindBC(iMarker) == SEND_RECEIVE) && (config->GetMarker_All_SendRecv(iMarker) > 0)) { MarkerR = iMarker+1; nVertexR = geometry->nVertex[MarkerR]; iRank = abs(config->GetMarker_All_SendRecv(MarkerR))-1; if (iRank == Neighbors_P2PRecv[iRecv]) { for (iVertex = 0; iVertex < nVertexR; iVertex++) { Local_Point_P2PRecv[count] = geometry->vertex[MarkerR][iVertex]->GetNode(); count++; } } } } } /*--- In the future, some additional data structures could be created here to separate the interior and boundary nodes in order to help further overlap computation and communication. ---*/ } void CGeometry::AllocateP2PComms(unsigned short countPerPoint) { /*--- This routine is activated whenever we attempt to perform a point-to-point MPI communication with our neighbors but the memory buffer allocated is not large enough for the packet size. Therefore, we deallocate the previously allocated space and reallocate a large enough array. Note that after the first set communications, this routine will not need to be called again. ---*/ if (countPerPoint <= maxCountPerPoint) return; SU2_OMP_BARRIER SU2_OMP_MASTER { /*--- Store the larger packet size to the class data. ---*/ maxCountPerPoint = countPerPoint; /*-- Deallocate and reallocate our su2double cummunication memory. ---*/ delete [] bufD_P2PSend; bufD_P2PSend = new su2double[maxCountPerPoint*nPoint_P2PSend[nP2PSend]] (); delete [] bufD_P2PRecv; bufD_P2PRecv = new su2double[maxCountPerPoint*nPoint_P2PRecv[nP2PRecv]] (); delete [] bufS_P2PSend; bufS_P2PSend = new unsigned short[maxCountPerPoint*nPoint_P2PSend[nP2PSend]] (); delete [] bufS_P2PRecv; bufS_P2PRecv = new unsigned short[maxCountPerPoint*nPoint_P2PRecv[nP2PRecv]] (); } SU2_OMP_BARRIER } void CGeometry::PostP2PRecvs(CGeometry *geometry, const CConfig *config, unsigned short commType, unsigned short countPerPoint, bool val_reverse) const { /*--- Launch the non-blocking recv's first. Note that we have stored the counts and sources, so we can launch these before we even load the data and send from the neighbor ranks. ---*/ SU2_OMP_MASTER for (int iRecv = 0; iRecv < nP2PRecv; iRecv++) { const auto iMessage = iRecv; /*--- In some instances related to the adjoint solver, we need to reverse the direction of communications such that the normal send nodes become the recv nodes and vice-versa. ---*/ if (val_reverse) { /*--- Compute our location in the buffer using the send data structure since we are reversing the comms. ---*/ auto offset = countPerPoint*nPoint_P2PSend[iRecv]; /*--- Take advantage of cumulative storage format to get the number of elems that we need to recv. Note again that we select the send points here as the recv points. ---*/ auto nPointP2P = nPoint_P2PSend[iRecv+1] - nPoint_P2PSend[iRecv]; /*--- Total count can include multiple pieces of data per element. ---*/ auto count = countPerPoint*nPointP2P; /*--- Get the rank from which we receive the message. Note again that we use the send rank as the source instead of the recv rank. ---*/ auto source = Neighbors_P2PSend[iRecv]; auto tag = source + 1; /*--- Post non-blocking recv for this proc. Note that we use the send buffer here too. This is important to make sure the arrays are the correct size. ---*/ switch (commType) { case COMM_TYPE_DOUBLE: SU2_MPI::Irecv(&(bufD_P2PSend[offset]), count, MPI_DOUBLE, source, tag, MPI_COMM_WORLD, &(req_P2PRecv[iRecv])); break; case COMM_TYPE_UNSIGNED_SHORT: SU2_MPI::Irecv(&(bufS_P2PSend[offset]), count, MPI_UNSIGNED_SHORT, source, tag, MPI_COMM_WORLD, &(req_P2PRecv[iRecv])); break; default: SU2_MPI::Error("Unrecognized data type for point-to-point MPI comms.", CURRENT_FUNCTION); break; } } else { /*--- Compute our location in the recv buffer. ---*/ auto offset = countPerPoint*nPoint_P2PRecv[iRecv]; /*--- Take advantage of cumulative storage format to get the number of elems that we need to recv. ---*/ auto nPointP2P = nPoint_P2PRecv[iRecv+1] - nPoint_P2PRecv[iRecv]; /*--- Total count can include multiple pieces of data per element. ---*/ auto count = countPerPoint*nPointP2P; /*--- Get the rank from which we receive the message. ---*/ auto source = Neighbors_P2PRecv[iRecv]; auto tag = source + 1; /*--- Post non-blocking recv for this proc. ---*/ switch (commType) { case COMM_TYPE_DOUBLE: SU2_MPI::Irecv(&(bufD_P2PRecv[offset]), count, MPI_DOUBLE, source, tag, MPI_COMM_WORLD, &(req_P2PRecv[iMessage])); break; case COMM_TYPE_UNSIGNED_SHORT: SU2_MPI::Irecv(&(bufS_P2PRecv[offset]), count, MPI_UNSIGNED_SHORT, source, tag, MPI_COMM_WORLD, &(req_P2PRecv[iMessage])); break; default: SU2_MPI::Error("Unrecognized data type for point-to-point MPI comms.", CURRENT_FUNCTION); break; } } } } void CGeometry::PostP2PSends(CGeometry *geometry, const CConfig *config, unsigned short commType, unsigned short countPerPoint, int val_iSend, bool val_reverse) const { /*--- Post the non-blocking send as soon as the buffer is loaded. ---*/ /*--- In some instances related to the adjoint solver, we need to reverse the direction of communications such that the normal send nodes become the recv nodes and vice-versa. ---*/ SU2_OMP_MASTER if (val_reverse) { /*--- Compute our location in the buffer using the recv data structure since we are reversing the comms. ---*/ auto offset = countPerPoint*nPoint_P2PRecv[val_iSend]; /*--- Take advantage of cumulative storage format to get the number of points that we need to send. Note again that we select the recv points here as the send points. ---*/ auto nPointP2P = nPoint_P2PRecv[val_iSend+1] - nPoint_P2PRecv[val_iSend]; /*--- Total count can include multiple pieces of data per element. ---*/ auto count = countPerPoint*nPointP2P; /*--- Get the rank to which we send the message. Note again that we use the recv rank as the dest instead of the send rank. ---*/ auto dest = Neighbors_P2PRecv[val_iSend]; auto tag = rank + 1; /*--- Post non-blocking send for this proc. Note that we use the send buffer here too. This is important to make sure the arrays are the correct size. ---*/ switch (commType) { case COMM_TYPE_DOUBLE: SU2_MPI::Isend(&(bufD_P2PRecv[offset]), count, MPI_DOUBLE, dest, tag, MPI_COMM_WORLD, &(req_P2PSend[val_iSend])); break; case COMM_TYPE_UNSIGNED_SHORT: SU2_MPI::Isend(&(bufS_P2PRecv[offset]), count, MPI_UNSIGNED_SHORT, dest, tag, MPI_COMM_WORLD, &(req_P2PSend[val_iSend])); break; default: SU2_MPI::Error("Unrecognized data type for point-to-point MPI comms.", CURRENT_FUNCTION); break; } } else { /*--- Compute our location in the send buffer. ---*/ auto offset = countPerPoint*nPoint_P2PSend[val_iSend]; /*--- Take advantage of cumulative storage format to get the number of points that we need to send. ---*/ auto nPointP2P = nPoint_P2PSend[val_iSend+1] - nPoint_P2PSend[val_iSend]; /*--- Total count can include multiple pieces of data per element. ---*/ auto count = countPerPoint*nPointP2P; /*--- Get the rank to which we send the message. ---*/ auto dest = Neighbors_P2PSend[val_iSend]; auto tag = rank + 1; /*--- Post non-blocking send for this proc. ---*/ switch (commType) { case COMM_TYPE_DOUBLE: SU2_MPI::Isend(&(bufD_P2PSend[offset]), count, MPI_DOUBLE, dest, tag, MPI_COMM_WORLD, &(req_P2PSend[val_iSend])); break; case COMM_TYPE_UNSIGNED_SHORT: SU2_MPI::Isend(&(bufS_P2PSend[offset]), count, MPI_UNSIGNED_SHORT, dest, tag, MPI_COMM_WORLD, &(req_P2PSend[val_iSend])); break; default: SU2_MPI::Error("Unrecognized data type for point-to-point MPI comms.", CURRENT_FUNCTION); break; } } } void CGeometry::GetCommCountAndType(const CConfig* config, unsigned short commType, unsigned short &COUNT_PER_POINT, unsigned short &MPI_TYPE) const { switch (commType) { case COORDINATES: COUNT_PER_POINT = nDim; MPI_TYPE = COMM_TYPE_DOUBLE; break; case GRID_VELOCITY: COUNT_PER_POINT = nDim; MPI_TYPE = COMM_TYPE_DOUBLE; break; case COORDINATES_OLD: if (config->GetTime_Marching() == DT_STEPPING_2ND) COUNT_PER_POINT = nDim*2; else COUNT_PER_POINT = nDim; MPI_TYPE = COMM_TYPE_DOUBLE; break; case MAX_LENGTH: COUNT_PER_POINT = 1; MPI_TYPE = COMM_TYPE_DOUBLE; break; case NEIGHBORS: COUNT_PER_POINT = 1; MPI_TYPE = COMM_TYPE_UNSIGNED_SHORT; break; default: SU2_MPI::Error("Unrecognized quantity for point-to-point MPI comms.", CURRENT_FUNCTION); break; } } void CGeometry::InitiateComms(CGeometry *geometry, const CConfig *config, unsigned short commType) const { if (nP2PSend == 0) return; /*--- Local variables ---*/ unsigned short iDim; unsigned short COUNT_PER_POINT = 0; unsigned short MPI_TYPE = 0; unsigned long iPoint, msg_offset, buf_offset; int iMessage, iSend, nSend; /*--- Set the size of the data packet and type depending on quantity. ---*/ GetCommCountAndType(config, commType, COUNT_PER_POINT, MPI_TYPE); /*--- Check to make sure we have created a large enough buffer for these comms during preprocessing. This is only for the su2double buffer. It will be reallocated whenever we find a larger count per point. After the first cycle of comms, this should be inactive. ---*/ geometry->AllocateP2PComms(COUNT_PER_POINT); /*--- Set some local pointers to make access simpler. ---*/ su2double *bufDSend = geometry->bufD_P2PSend; unsigned short *bufSSend = geometry->bufS_P2PSend; su2double *vector = nullptr; /*--- Load the specified quantity from the solver into the generic communication buffer in the geometry class. ---*/ /*--- Post all non-blocking recvs first before sends. ---*/ geometry->PostP2PRecvs(geometry, config, MPI_TYPE, COUNT_PER_POINT, false); for (iMessage = 0; iMessage < nP2PSend; iMessage++) { /*--- Get the offset in the buffer for the start of this message. ---*/ msg_offset = nPoint_P2PSend[iMessage]; /*--- Total count can include multiple pieces of data per element. ---*/ nSend = (nPoint_P2PSend[iMessage+1] - nPoint_P2PSend[iMessage]); SU2_OMP_FOR_STAT(OMP_MIN_SIZE) for (iSend = 0; iSend < nSend; iSend++) { /*--- Get the local index for this communicated data. ---*/ iPoint = geometry->Local_Point_P2PSend[msg_offset + iSend]; /*--- Compute the offset in the recv buffer for this point. ---*/ buf_offset = (msg_offset + iSend)*COUNT_PER_POINT; switch (commType) { case COORDINATES: vector = nodes->GetCoord(iPoint); for (iDim = 0; iDim < nDim; iDim++) bufDSend[buf_offset+iDim] = vector[iDim]; break; case GRID_VELOCITY: vector = nodes->GetGridVel(iPoint); for (iDim = 0; iDim < nDim; iDim++) bufDSend[buf_offset+iDim] = vector[iDim]; break; case COORDINATES_OLD: vector = nodes->GetCoord_n(iPoint); for (iDim = 0; iDim < nDim; iDim++) { bufDSend[buf_offset+iDim] = vector[iDim]; } if (config->GetTime_Marching() == DT_STEPPING_2ND) { vector = nodes->GetCoord_n1(iPoint); for (iDim = 0; iDim < nDim; iDim++) { bufDSend[buf_offset+nDim+iDim] = vector[iDim]; } } break; case MAX_LENGTH: bufDSend[buf_offset] = nodes->GetMaxLength(iPoint); break; case NEIGHBORS: bufSSend[buf_offset] = geometry->nodes->GetnNeighbor(iPoint); break; default: SU2_MPI::Error("Unrecognized quantity for point-to-point MPI comms.", CURRENT_FUNCTION); break; } } /*--- Launch the point-to-point MPI send for this message. ---*/ geometry->PostP2PSends(geometry, config, MPI_TYPE, COUNT_PER_POINT, iMessage, false); } } void CGeometry::CompleteComms(CGeometry *geometry, const CConfig *config, unsigned short commType) { if (nP2PRecv == 0) return; /*--- Local variables ---*/ unsigned short iDim, COUNT_PER_POINT = 0, MPI_TYPE = 0; unsigned long iPoint, iRecv, nRecv, msg_offset, buf_offset; int ind, source, iMessage, jRecv; /*--- Global status so all threads can see the result of Waitany. ---*/ static SU2_MPI::Status status; /*--- Set the size of the data packet and type depending on quantity. ---*/ GetCommCountAndType(config, commType, COUNT_PER_POINT, MPI_TYPE); /*--- Set some local pointers to make access simpler. ---*/ const su2double *bufDRecv = geometry->bufD_P2PRecv; const unsigned short *bufSRecv = geometry->bufS_P2PRecv; /*--- Store the data that was communicated into the appropriate location within the local class data structures. Note that we recv and store the data in any order to take advantage of the non-blocking comms. ---*/ for (iMessage = 0; iMessage < nP2PRecv; iMessage++) { /*--- For efficiency, recv the messages dynamically based on the order they arrive. ---*/ SU2_OMP_MASTER SU2_MPI::Waitany(nP2PRecv, req_P2PRecv, &ind, &status); SU2_OMP_BARRIER /*--- Once we have recv'd a message, get the source rank. ---*/ source = status.MPI_SOURCE; /*--- We know the offsets based on the source rank. ---*/ jRecv = P2PRecv2Neighbor[source]; /*--- Get the offset in the buffer for the start of this message. ---*/ msg_offset = nPoint_P2PRecv[jRecv]; /*--- Get the number of packets to be received in this message. ---*/ nRecv = nPoint_P2PRecv[jRecv+1] - nPoint_P2PRecv[jRecv]; SU2_OMP_FOR_STAT(OMP_MIN_SIZE) for (iRecv = 0; iRecv < nRecv; iRecv++) { /*--- Get the local index for this communicated data. ---*/ iPoint = geometry->Local_Point_P2PRecv[msg_offset + iRecv]; /*--- Compute the total offset in the recv buffer for this point. ---*/ buf_offset = (msg_offset + iRecv)*COUNT_PER_POINT; /*--- Store the data correctly depending on the quantity. ---*/ switch (commType) { case COORDINATES: for (iDim = 0; iDim < nDim; iDim++) nodes->SetCoord(iPoint, iDim, bufDRecv[buf_offset+iDim]); break; case GRID_VELOCITY: for (iDim = 0; iDim < nDim; iDim++) nodes->SetGridVel(iPoint, iDim, bufDRecv[buf_offset+iDim]); break; case COORDINATES_OLD: nodes->SetCoord_n(iPoint, &bufDRecv[buf_offset]); if (config->GetTime_Marching() == DT_STEPPING_2ND) nodes->SetCoord_n1(iPoint, &bufDRecv[buf_offset+nDim]); break; case MAX_LENGTH: nodes->SetMaxLength(iPoint, bufDRecv[buf_offset]); break; case NEIGHBORS: nodes->SetnNeighbor(iPoint, bufSRecv[buf_offset]); break; default: SU2_MPI::Error("Unrecognized quantity for point-to-point MPI comms.", CURRENT_FUNCTION); break; } } } /*--- Verify that all non-blocking point-to-point sends have finished. Note that this should be satisfied, as we have received all of the data in the loop above at this point. ---*/ #ifdef HAVE_MPI SU2_OMP_MASTER SU2_MPI::Waitall(nP2PSend, req_P2PSend, MPI_STATUS_IGNORE); #endif SU2_OMP_BARRIER } void CGeometry::PreprocessPeriodicComms(CGeometry *geometry, CConfig *config) { /*--- We start with the send and receive lists already available in the form of stored periodic point-donor pairs. We will loop through these markers and establish the neighboring ranks and number of send/recv points per pair. We will store this information and set up persistent data structures so that we can reuse them throughout the calculation for any periodic boundary communications. The goal is to break the non-blocking comms into InitiatePeriodicComms() and CompletePeriodicComms() in separate routines so that we can overlap the communication and computation to hide the communication latency. ---*/ /*--- Local variables. ---*/ unsigned short iMarker; unsigned long iPoint, iVertex, iPeriodic; int iRank, iSend, iRecv, ii, jj; /*--- Create some temporary structures for tracking sends/recvs. ---*/ int *nPoint_Send_All = new int[size+1]; nPoint_Send_All[0] = 0; int *nPoint_Recv_All = new int[size+1]; nPoint_Recv_All[0] = 0; int *nPoint_Flag = new int[size]; for (iRank = 0; iRank < size; iRank++) { nPoint_Send_All[iRank] = 0; nPoint_Recv_All[iRank] = 0; nPoint_Flag[iRank]= -1; } nPoint_Send_All[size] = 0; nPoint_Recv_All[size] = 0; /*--- Loop through all of our periodic markers and track our sends with each rank. ---*/ for (iMarker = 0; iMarker < config->GetnMarker_All(); iMarker++) { if (config->GetMarker_All_KindBC(iMarker) == PERIODIC_BOUNDARY) { iPeriodic = config->GetMarker_All_PerBound(iMarker); for (iVertex = 0; iVertex < geometry->nVertex[iMarker]; iVertex++) { /*--- Get the current periodic point index. We only communicate the owned nodes on a rank, as the MPI comms will take care of the halos after completing the periodic comms. ---*/ iPoint = geometry->vertex[iMarker][iVertex]->GetNode(); if (geometry->nodes->GetDomain(iPoint)) { /*--- Get the rank that holds the matching periodic point on the other marker in the periodic pair. ---*/ iRank = (int)geometry->vertex[iMarker][iVertex]->GetDonorProcessor(); /*--- If we have not visited this point last, increment our number of points that must be sent to a particular proc. ---*/ if ((nPoint_Flag[iRank] != (int)iPoint)) { nPoint_Flag[iRank] = (int)iPoint; nPoint_Send_All[iRank+1] += 1; } } } } } delete [] nPoint_Flag; /*--- Communicate the number of points to be sent/recv'd amongst all processors. After this communication, each proc knows how many periodic points it will receive from each other processor. ---*/ SU2_MPI::Alltoall(&(nPoint_Send_All[1]), 1, MPI_INT, &(nPoint_Recv_All[1]), 1, MPI_INT, MPI_COMM_WORLD); /*--- Check how many messages we will be sending and receiving. Here we also put the counters into cumulative storage format to make the communications simpler. Note that we are allowing each rank to communicate to themselves in these counters, although it will not be done through MPI. ---*/ nPeriodicSend = 0; nPeriodicRecv = 0; for (iRank = 0; iRank < size; iRank++) { if ((nPoint_Send_All[iRank+1] > 0)) nPeriodicSend++; if ((nPoint_Recv_All[iRank+1] > 0)) nPeriodicRecv++; nPoint_Send_All[iRank+1] += nPoint_Send_All[iRank]; nPoint_Recv_All[iRank+1] += nPoint_Recv_All[iRank]; } /*--- Allocate only as much memory as needed for the periodic neighbors. ---*/ nPoint_PeriodicSend = new int[nPeriodicSend+1]; nPoint_PeriodicSend[0] = 0; nPoint_PeriodicRecv = new int[nPeriodicRecv+1]; nPoint_PeriodicRecv[0] = 0; Neighbors_PeriodicSend = new int[nPeriodicSend]; Neighbors_PeriodicRecv = new int[nPeriodicRecv]; iSend = 0; iRecv = 0; for (iRank = 0; iRank < size; iRank++) { if ((nPoint_Send_All[iRank+1] > nPoint_Send_All[iRank])) { Neighbors_PeriodicSend[iSend] = iRank; nPoint_PeriodicSend[iSend+1] = nPoint_Send_All[iRank+1]; iSend++; } if ((nPoint_Recv_All[iRank+1] > nPoint_Recv_All[iRank])) { Neighbors_PeriodicRecv[iRecv] = iRank; nPoint_PeriodicRecv[iRecv+1] = nPoint_Recv_All[iRank+1]; iRecv++; } } /*--- Create a reverse mapping of the message to the rank so that we can quickly access the correct data in the buffers when receiving messages dynamically later during the iterations. ---*/ PeriodicSend2Neighbor.clear(); for (iSend = 0; iSend < nPeriodicSend; iSend++) PeriodicSend2Neighbor[Neighbors_PeriodicSend[iSend]] = iSend; PeriodicRecv2Neighbor.clear(); for (iRecv = 0; iRecv < nPeriodicRecv; iRecv++) PeriodicRecv2Neighbor[Neighbors_PeriodicRecv[iRecv]] = iRecv; delete [] nPoint_Send_All; delete [] nPoint_Recv_All; /*--- Allocate the memory to store the local index values for both the send and receive periodic points and periodic index. ---*/ Local_Point_PeriodicSend = nullptr; Local_Point_PeriodicSend = new unsigned long[nPoint_PeriodicSend[nPeriodicSend]]; for (iSend = 0; iSend < nPoint_PeriodicSend[nPeriodicSend]; iSend++) Local_Point_PeriodicSend[iSend] = 0; Local_Marker_PeriodicSend = nullptr; Local_Marker_PeriodicSend = new unsigned long[nPoint_PeriodicSend[nPeriodicSend]]; for (iSend = 0; iSend < nPoint_PeriodicSend[nPeriodicSend]; iSend++) Local_Marker_PeriodicSend[iSend] = 0; Local_Point_PeriodicRecv = nullptr; Local_Point_PeriodicRecv = new unsigned long[nPoint_PeriodicRecv[nPeriodicRecv]]; for (iRecv = 0; iRecv < nPoint_PeriodicRecv[nPeriodicRecv]; iRecv++) Local_Point_PeriodicRecv[iRecv] = 0; Local_Marker_PeriodicRecv = nullptr; Local_Marker_PeriodicRecv = new unsigned long[nPoint_PeriodicRecv[nPeriodicRecv]]; for (iRecv = 0; iRecv < nPoint_PeriodicRecv[nPeriodicRecv]; iRecv++) Local_Marker_PeriodicRecv[iRecv] = 0; /*--- We allocate the buffers for communicating values in a later step once we know the maximum packet size that we need to communicate. This memory is deallocated and reallocated automatically in the case that the previously allocated memory is not sufficient. ---*/ bufD_PeriodicSend = nullptr; bufD_PeriodicRecv = nullptr; bufS_PeriodicSend = nullptr; bufS_PeriodicRecv = nullptr; /*--- Allocate memory for the MPI requests if we need to communicate. ---*/ if (nPeriodicSend > 0) { req_PeriodicSend = new SU2_MPI::Request[nPeriodicSend]; } if (nPeriodicRecv > 0) { req_PeriodicRecv = new SU2_MPI::Request[nPeriodicRecv]; } /*--- Allocate arrays for sending the periodic point index and marker index to the recv rank so that it can store the local values. Therefore, the recv rank can quickly loop through the buffers to unpack the data. ---*/ unsigned short nPackets = 2; unsigned long *idSend = new unsigned long[nPoint_PeriodicSend[nPeriodicSend]*nPackets]; for (iSend = 0; iSend < nPoint_PeriodicSend[nPeriodicSend]*nPackets; iSend++) idSend[iSend] = 0; /*--- Build the lists of local index and periodic marker index values. ---*/ ii = 0; jj = 0; for (iSend = 0; iSend < nPeriodicSend; iSend++) { for (iMarker = 0; iMarker < config->GetnMarker_All(); iMarker++) { if (config->GetMarker_All_KindBC(iMarker) == PERIODIC_BOUNDARY) { iPeriodic = config->GetMarker_All_PerBound(iMarker); for (iVertex = 0; iVertex < geometry->nVertex[iMarker]; iVertex++) { /*--- Get the current periodic point index. We only communicate the owned nodes on a rank, as the MPI comms will take care of the halos after completing the periodic comms. ---*/ iPoint = geometry->vertex[iMarker][iVertex]->GetNode(); if (geometry->nodes->GetDomain(iPoint)) { /*--- Get the rank that holds the matching periodic point on the other marker in the periodic pair. ---*/ iRank = (int)geometry->vertex[iMarker][iVertex]->GetDonorProcessor(); /*--- If the rank for the current periodic point matches the rank of the current send message, then store the local point index on the matching periodic point and the periodic marker index to be communicated to the recv rank. ---*/ if (iRank == Neighbors_PeriodicSend[iSend]) { Local_Point_PeriodicSend[ii] = iPoint; Local_Marker_PeriodicSend[ii] = (unsigned long)iMarker; jj = ii*nPackets; idSend[jj] = geometry->vertex[iMarker][iVertex]->GetDonorPoint(); jj++; idSend[jj] = (unsigned long)iPeriodic; ii++; } } } } } } /*--- Allocate arrays for receiving the periodic point index and marker index to the recv rank so that it can store the local values. ---*/ unsigned long *idRecv = new unsigned long[nPoint_PeriodicRecv[nPeriodicRecv]*nPackets]; for (iRecv = 0; iRecv < nPoint_PeriodicRecv[nPeriodicRecv]*nPackets; iRecv++) idRecv[iRecv] = 0; #ifdef HAVE_MPI int iMessage, offset, count, source, dest, tag; /*--- Launch the non-blocking recv's first. Note that we have stored the counts and sources, so we can launch these before we even load the data and send from the periodically matching ranks. ---*/ iMessage = 0; for (iRecv = 0; iRecv < nPeriodicRecv; iRecv++) { /*--- Compute our location in the recv buffer. ---*/ offset = nPackets*nPoint_PeriodicRecv[iRecv]; /*--- Take advantage of cumulative storage format to get the number of elems that we need to recv. ---*/ count = nPackets*(nPoint_PeriodicRecv[iRecv+1] - nPoint_PeriodicRecv[iRecv]); /*--- Get the rank from which we receive the message. ---*/ source = Neighbors_PeriodicRecv[iRecv]; tag = source + 1; /*--- Post non-blocking recv for this proc. ---*/ SU2_MPI::Irecv(&(static_cast<unsigned long*>(idRecv)[offset]), count, MPI_UNSIGNED_LONG, source, tag, MPI_COMM_WORLD, &(req_PeriodicRecv[iMessage])); /*--- Increment message counter. ---*/ iMessage++; } /*--- Post the non-blocking sends. ---*/ iMessage = 0; for (iSend = 0; iSend < nPeriodicSend; iSend++) { /*--- Compute our location in the send buffer. ---*/ offset = nPackets*nPoint_PeriodicSend[iSend]; /*--- Take advantage of cumulative storage format to get the number of points that we need to send. ---*/ count = nPackets*(nPoint_PeriodicSend[iSend+1] - nPoint_PeriodicSend[iSend]); /*--- Get the rank to which we send the message. ---*/ dest = Neighbors_PeriodicSend[iSend]; tag = rank + 1; /*--- Post non-blocking send for this proc. ---*/ SU2_MPI::Isend(&(static_cast<unsigned long*>(idSend)[offset]), count, MPI_UNSIGNED_LONG, dest, tag, MPI_COMM_WORLD, &(req_PeriodicSend[iMessage])); /*--- Increment message counter. ---*/ iMessage++; } /*--- Wait for the non-blocking comms to complete. ---*/ SU2_MPI::Waitall(nPeriodicSend, req_PeriodicSend, MPI_STATUS_IGNORE); SU2_MPI::Waitall(nPeriodicRecv, req_PeriodicRecv, MPI_STATUS_IGNORE); #else /*--- Copy my own rank's data into the recv buffer directly in serial. ---*/ int myStart, myFinal; for (int val_iSend = 0; val_iSend < nPeriodicSend; val_iSend++) { iRank = geometry->PeriodicRecv2Neighbor[rank]; iRecv = geometry->nPoint_PeriodicRecv[iRank]*nPackets; myStart = nPoint_PeriodicSend[val_iSend]*nPackets; myFinal = nPoint_PeriodicSend[val_iSend+1]*nPackets; for (iSend = myStart; iSend < myFinal; iSend++) { idRecv[iRecv] = idSend[iSend]; iRecv++; } } #endif /*--- Store the local periodic point and marker index values in our data structures so we can quickly unpack data during the iterations. ---*/ ii = 0; for (iRecv = 0; iRecv < nPoint_PeriodicRecv[nPeriodicRecv]; iRecv++) { Local_Point_PeriodicRecv[iRecv] = idRecv[ii]; ii++; Local_Marker_PeriodicRecv[iRecv] = idRecv[ii]; ii++; } delete [] idSend; delete [] idRecv; } void CGeometry::AllocatePeriodicComms(unsigned short countPerPeriodicPoint) { /*--- This routine is activated whenever we attempt to perform a periodic MPI communication with our neighbors but the memory buffer allocated is not large enough for the packet size. Therefore, we deallocate the previously allocated arrays and reallocate a large enough array. Note that after the first set communications, this routine will not need to be called again. ---*/ if (countPerPeriodicPoint <= maxCountPerPeriodicPoint) return; SU2_OMP_BARRIER SU2_OMP_MASTER { /*--- Store the larger packet size to the class data. ---*/ maxCountPerPeriodicPoint = countPerPeriodicPoint; /*--- Store the total size of the send/recv arrays for clarity. ---*/ auto nSend = countPerPeriodicPoint*nPoint_PeriodicSend[nPeriodicSend]; auto nRecv = countPerPeriodicPoint*nPoint_PeriodicRecv[nPeriodicRecv]; /*-- Deallocate and reallocate our cummunication memory. ---*/ delete [] bufD_PeriodicSend; bufD_PeriodicSend = new su2double[nSend] (); delete [] bufD_PeriodicRecv; bufD_PeriodicRecv = new su2double[nRecv] (); delete [] bufS_PeriodicSend; bufS_PeriodicSend = new unsigned short[nSend] (); delete [] bufS_PeriodicRecv; bufS_PeriodicRecv = new unsigned short[nRecv] (); } SU2_OMP_BARRIER } void CGeometry::PostPeriodicRecvs(CGeometry *geometry, const CConfig *config, unsigned short commType, unsigned short countPerPeriodicPoint) { /*--- In parallel, communicate the data with non-blocking send/recv. ---*/ #ifdef HAVE_MPI /*--- Launch the non-blocking recv's first. Note that we have stored the counts and sources, so we can launch these before we even load the data and send from the neighbor ranks. ---*/ SU2_OMP_MASTER for (int iRecv = 0; iRecv < nPeriodicRecv; iRecv++) { /*--- Compute our location in the recv buffer. ---*/ auto offset = countPerPeriodicPoint*nPoint_PeriodicRecv[iRecv]; /*--- Take advantage of cumulative storage format to get the number of elems that we need to recv. ---*/ auto nPointPeriodic = nPoint_PeriodicRecv[iRecv+1] - nPoint_PeriodicRecv[iRecv]; /*--- Total count can include multiple pieces of data per element. ---*/ auto count = countPerPeriodicPoint*nPointPeriodic; /*--- Get the rank from which we receive the message. ---*/ auto source = Neighbors_PeriodicRecv[iRecv]; auto tag = source + 1; /*--- Post non-blocking recv for this proc. ---*/ switch (commType) { case COMM_TYPE_DOUBLE: SU2_MPI::Irecv(&(static_cast<su2double*>(bufD_PeriodicRecv)[offset]), count, MPI_DOUBLE, source, tag, MPI_COMM_WORLD, &(req_PeriodicRecv[iRecv])); break; case COMM_TYPE_UNSIGNED_SHORT: SU2_MPI::Irecv(&(static_cast<unsigned short*>(bufS_PeriodicRecv)[offset]), count, MPI_UNSIGNED_SHORT, source, tag, MPI_COMM_WORLD, &(req_PeriodicRecv[iRecv])); break; default: SU2_MPI::Error("Unrecognized data type for periodic MPI comms.", CURRENT_FUNCTION); break; } } #endif } void CGeometry::PostPeriodicSends(CGeometry *geometry, const CConfig *config, unsigned short commType, unsigned short countPerPeriodicPoint, int val_iSend) const { /*--- In parallel, communicate the data with non-blocking send/recv. ---*/ #ifdef HAVE_MPI SU2_OMP_MASTER { /*--- Post the non-blocking send as soon as the buffer is loaded. ---*/ /*--- Compute our location in the send buffer. ---*/ auto offset = countPerPeriodicPoint*nPoint_PeriodicSend[val_iSend]; /*--- Take advantage of cumulative storage format to get the number of points that we need to send. ---*/ auto nPointPeriodic = (nPoint_PeriodicSend[val_iSend+1] - nPoint_PeriodicSend[val_iSend]); /*--- Total count can include multiple pieces of data per element. ---*/ auto count = countPerPeriodicPoint*nPointPeriodic; /*--- Get the rank to which we send the message. ---*/ auto dest = Neighbors_PeriodicSend[val_iSend]; auto tag = rank + 1; /*--- Post non-blocking send for this proc. ---*/ switch (commType) { case COMM_TYPE_DOUBLE: SU2_MPI::Isend(&(static_cast<su2double*>(bufD_PeriodicSend)[offset]), count, MPI_DOUBLE, dest, tag, MPI_COMM_WORLD, &(req_PeriodicSend[val_iSend])); break; case COMM_TYPE_UNSIGNED_SHORT: SU2_MPI::Isend(&(static_cast<unsigned short*>(bufS_PeriodicSend)[offset]), count, MPI_UNSIGNED_SHORT, dest, tag, MPI_COMM_WORLD, &(req_PeriodicSend[val_iSend])); break; default: SU2_MPI::Error("Unrecognized data type for periodic MPI comms.", CURRENT_FUNCTION); break; } } // end master #else /*--- Copy my own rank's data into the recv buffer directly in serial. ---*/ int myStart, myFinal, iRecv, iRank; iRank = geometry->PeriodicRecv2Neighbor[rank]; iRecv = geometry->nPoint_PeriodicRecv[iRank]*countPerPeriodicPoint; myStart = nPoint_PeriodicSend[val_iSend]*countPerPeriodicPoint; myFinal = nPoint_PeriodicSend[val_iSend+1]*countPerPeriodicPoint; switch (commType) { case COMM_TYPE_DOUBLE: parallelCopy(myFinal-myStart, &bufD_PeriodicSend[myStart], &bufD_PeriodicRecv[iRecv]); break; case COMM_TYPE_UNSIGNED_SHORT: parallelCopy(myFinal-myStart, &bufS_PeriodicSend[myStart], &bufS_PeriodicRecv[iRecv]); break; default: SU2_MPI::Error("Unrecognized data type for periodic MPI comms.", CURRENT_FUNCTION); break; } #endif } su2double CGeometry::Point2Plane_Distance(const su2double *Coord, const su2double *iCoord, const su2double *jCoord, const su2double *kCoord) { su2double CrossProduct[3], iVector[3], jVector[3], distance, modulus; unsigned short iDim; for (iDim = 0; iDim < 3; iDim ++) { iVector[iDim] = jCoord[iDim] - iCoord[iDim]; jVector[iDim] = kCoord[iDim] - iCoord[iDim]; } CrossProduct[0] = iVector[1]*jVector[2] - iVector[2]*jVector[1]; CrossProduct[1] = iVector[2]*jVector[0] - iVector[0]*jVector[2]; CrossProduct[2] = iVector[0]*jVector[1] - iVector[1]*jVector[0]; modulus = sqrt(CrossProduct[0]*CrossProduct[0]+CrossProduct[1]*CrossProduct[1]+CrossProduct[2]*CrossProduct[2]); distance = 0.0; for (iDim = 0; iDim < 3; iDim ++) distance += CrossProduct[iDim]*(Coord[iDim]-iCoord[iDim]); distance /= modulus; return distance; } long CGeometry::FindEdge(unsigned long first_point, unsigned long second_point) const { for (unsigned short iNode = 0; iNode < nodes->GetnPoint(first_point); iNode++) { auto iPoint = nodes->GetPoint(first_point, iNode); if (iPoint == second_point) return nodes->GetEdge(first_point, iNode); } char buf[100]; SPRINTF(buf, "Can't find the edge that connects %lu and %lu.", first_point, second_point); SU2_MPI::Error(buf, CURRENT_FUNCTION); return 0; } bool CGeometry::CheckEdge(unsigned long first_point, unsigned long second_point) const { for (unsigned short iNode = 0; iNode < nodes->GetnPoint(first_point); iNode++) { auto iPoint = nodes->GetPoint(first_point, iNode); if (iPoint == second_point) return true; } return false; } void CGeometry::SetEdges(void) { nEdge = 0; for (auto iPoint = 0ul; iPoint < nPoint; iPoint++) { for (auto iNode = 0u; iNode < nodes->GetnPoint(iPoint); iNode++) { auto jPoint = nodes->GetPoint(iPoint, iNode); for (auto jNode = 0u; jNode < nodes->GetnPoint(jPoint); jNode++) { if (nodes->GetPoint(jPoint, jNode) == iPoint) { auto TestEdge = nodes->GetEdge(jPoint, jNode); if (TestEdge == -1) { nodes->SetEdge(iPoint, nEdge, iNode); nodes->SetEdge(jPoint, nEdge, jNode); nEdge++; } break; } } } } edges = new CEdge(nEdge,nDim); for (auto iPoint = 0ul; iPoint < nPoint; iPoint++) { for (auto iNode = 0u; iNode < nodes->GetnPoint(iPoint); iNode++) { auto jPoint = nodes->GetPoint(iPoint, iNode); if (iPoint < jPoint) { auto iEdge = FindEdge(iPoint, jPoint); edges->SetNodes(iEdge, iPoint, jPoint); } } } } void CGeometry::SetFaces(void) { // unsigned long iPoint, jPoint, iFace; // unsigned short jNode, iNode; // long TestFace = 0; // // nFace = 0; // for (iPoint = 0; iPoint < nPoint; iPoint++) // for (iNode = 0; iNode < nodes->GetnPoint(iPoint); iNode++) { // jPoint = nodes->GetPoint(iPoint, iNode); // for (jNode = 0; jNode < nodes->GetnPoint(jPoint); jNode++) // if (nodes->GetPoint(jPoint, jNode) == iPoint) { // TestFace = nodes->GetFace(jPoint, jNode); // break; // } // if (TestFace == -1) { // nodes->SetFace(iPoint, nFace, iNode); // nodes->SetFace(jPoint, nFace, jNode); // nFace++; // } // } // // face = new CFace*[nFace]; // // for (iPoint = 0; iPoint < nPoint; iPoint++) // for (iNode = 0; iNode < nodes->GetnPoint(iPoint); iNode++) { // jPoint = nodes->GetPoint(iPoint, iNode); // iFace = FindFace(iPoint, jPoint); // if (iPoint < jPoint) face[iFace] = new CFace(iPoint, jPoint, nDim); // } } void CGeometry::TestGeometry(void) const { ofstream para_file; para_file.open("test_geometry.dat", ios::out); su2double *Normal = new su2double[nDim]; for (unsigned long iEdge = 0; iEdge < nEdge; iEdge++) { para_file << "Edge index: " << iEdge << endl; para_file << " Point index: " << edges->GetNode(iEdge,0) << "\t" << edges->GetNode(iEdge,1) << endl; edges->GetNormal(iEdge,Normal); para_file << " Face normal : "; for (unsigned short iDim = 0; iDim < nDim; iDim++) para_file << Normal[iDim] << "\t"; para_file << endl; } para_file << endl; para_file << endl; para_file << endl; para_file << endl; for (unsigned short iMarker =0; iMarker < nMarker; iMarker++) { para_file << "Marker index: " << iMarker << endl; for (unsigned long iVertex = 0; iVertex < nVertex[iMarker]; iVertex++) { para_file << " Vertex index: " << iVertex << endl; para_file << " Point index: " << vertex[iMarker][iVertex]->GetNode() << endl; para_file << " Point coordinates : "; for (unsigned short iDim = 0; iDim < nDim; iDim++) { para_file << nodes->GetCoord(vertex[iMarker][iVertex]->GetNode(), iDim) << "\t";} para_file << endl; vertex[iMarker][iVertex]->GetNormal(Normal); para_file << " Face normal : "; for (unsigned short iDim = 0; iDim < nDim; iDim++) para_file << Normal[iDim] << "\t"; para_file << endl; } } delete [] Normal; } void CGeometry::SetSpline(vector<su2double> &x, vector<su2double> &y, unsigned long n, su2double yp1, su2double ypn, vector<su2double> &y2) { unsigned long i, k; su2double p, qn, sig, un, *u; u = new su2double [n]; if (yp1 > 0.99e30) // The lower boundary condition is set either to be "nat y2[0]=u[0]=0.0; // -ural" else { // or else to have a specified first derivative. y2[0] = -0.5; u[0]=(3.0/(x[1]-x[0]))*((y[1]-y[0])/(x[1]-x[0])-yp1); } for (i=2; i<=n-1; i++) { // This is the decomposition loop of the tridiagonal al- sig=(x[i-1]-x[i-2])/(x[i]-x[i-2]); // gorithm. y2 and u are used for tem- p=sig*y2[i-2]+2.0; // porary storage of the decomposed y2[i-1]=(sig-1.0)/p; // factors. su2double a1 = (y[i]-y[i-1])/(x[i]-x[i-1]); if (x[i] == x[i-1]) a1 = 1.0; su2double a2 = (y[i-1]-y[i-2])/(x[i-1]-x[i-2]); if (x[i-1] == x[i-2]) a2 = 1.0; u[i-1]= a1 - a2; u[i-1]=(6.0*u[i-1]/(x[i]-x[i-2])-sig*u[i-2])/p; } if (ypn > 0.99e30) // The upper boundary condition is set either to be qn=un=0.0; // "natural" else { // or else to have a specified first derivative. qn=0.5; un=(3.0/(x[n-1]-x[n-2]))*(ypn-(y[n-1]-y[n-2])/(x[n-1]-x[n-2])); } y2[n-1]=(un-qn*u[n-2])/(qn*y2[n-2]+1.0); for (k=n-1; k>=1; k--) // This is the backsubstitution loop of the tridiagonal algorithm. y2[k-1]=y2[k-1]*y2[k]+u[k-1]; delete[] u; } su2double CGeometry::GetSpline(vector<su2double>&xa, vector<su2double>&ya, vector<su2double>&y2a, unsigned long n, su2double x) { unsigned long klo, khi, k; su2double h, b, a, y; if (x < xa[0]) x = xa[0]; // Clip max and min values if (x > xa[n-1]) x = xa[n-1]; klo = 1; // We will find the right place in the table by means of khi = n; // bisection. This is optimal if sequential calls to this while (khi-klo > 1) { // routine are at random values of x. If sequential calls k = (khi+klo) >> 1; // are in order, and closely spaced, one would do better if (xa[k-1] > x) khi = k; // to store previous values of klo and khi and test if else klo=k; // they remain appropriate on the next call. } // klo and khi now bracket the input value of x h = xa[khi-1] - xa[klo-1]; if (h == 0.0) h = EPS; // cout << "Bad xa input to routine splint" << endl; // The xa?s must be distinct. a = (xa[khi-1]-x)/h; b = (x-xa[klo-1])/h; // Cubic spline polynomial is now evaluated. y = a*ya[klo-1]+b*ya[khi-1]+((a*a*a-a)*y2a[klo-1]+(b*b*b-b)*y2a[khi-1])*(h*h)/6.0; return y; } bool CGeometry::SegmentIntersectsPlane(const su2double *Segment_P0, const su2double *Segment_P1, su2double Variable_P0, su2double Variable_P1, const su2double *Plane_P0, const su2double *Plane_Normal, su2double *Intersection, su2double &Variable_Interp) { su2double u[3], v[3], Denominator, Numerator, Aux, ModU; su2double epsilon = 1E-6; // An epsilon is added to eliminate, as much as possible, the posibility of a line that intersects a point unsigned short iDim; for (iDim = 0; iDim < 3; iDim++) { u[iDim] = Segment_P1[iDim] - Segment_P0[iDim]; v[iDim] = (Plane_P0[iDim]+epsilon) - Segment_P0[iDim]; } ModU = sqrt(u[0]*u[0]+u[1]*u[1]+u[2]*u[2]); Numerator = (Plane_Normal[0]+epsilon)*v[0] + (Plane_Normal[1]+epsilon)*v[1] + (Plane_Normal[2]+epsilon)*v[2]; Denominator = (Plane_Normal[0]+epsilon)*u[0] + (Plane_Normal[1]+epsilon)*u[1] + (Plane_Normal[2]+epsilon)*u[2]; if (fabs(Denominator) <= 0.0) return (false); // No intersection. Aux = Numerator / Denominator; if (Aux < 0.0 || Aux > 1.0) return (false); // No intersection. for (iDim = 0; iDim < 3; iDim++) Intersection[iDim] = Segment_P0[iDim] + Aux * u[iDim]; /*--- Check that the intersection is in the segment ---*/ for (iDim = 0; iDim < 3; iDim++) { u[iDim] = Segment_P0[iDim] - Intersection[iDim]; v[iDim] = Segment_P1[iDim] - Intersection[iDim]; } Variable_Interp = Variable_P0 + (Variable_P1 - Variable_P0)*sqrt(u[0]*u[0]+u[1]*u[1]+u[2]*u[2])/ModU; Denominator = (Plane_Normal[0]+epsilon)*u[0] + (Plane_Normal[1]+epsilon)*u[1] + (Plane_Normal[2]+epsilon)*u[2]; Numerator = (Plane_Normal[0]+epsilon)*v[0] + (Plane_Normal[1]+epsilon)*v[1] + (Plane_Normal[2]+epsilon)*v[2]; Aux = Numerator * Denominator; if (Aux > 0.0) return (false); // Intersection outside the segment. return (true); } bool CGeometry::RayIntersectsTriangle(const su2double orig[3], const su2double dir[3], const su2double vert0[3], const su2double vert1[3], const su2double vert2[3], su2double *intersect) { const passivedouble epsilon = 0.000001; su2double edge1[3], edge2[3], tvec[3], pvec[3], qvec[3]; su2double det, inv_det, t, u, v; /*--- Find vectors for two edges sharing vert0 ---*/ SUB(edge1, vert1, vert0); SUB(edge2, vert2, vert0); /*--- Begin calculating determinant - also used to calculate U parameter ---*/ CROSS(pvec, dir, edge2); /*--- If determinant is near zero, ray lies in plane of triangle ---*/ det = DOT(edge1, pvec); if (fabs(det) < epsilon) return(false); inv_det = 1.0 / det; /*--- Calculate distance from vert0 to ray origin ---*/ SUB(tvec, orig, vert0); /*--- Calculate U parameter and test bounds ---*/ u = inv_det * DOT(tvec, pvec); if (u < 0.0 || u > 1.0) return(false); /*--- prepare to test V parameter ---*/ CROSS(qvec, tvec, edge1); /*--- Calculate V parameter and test bounds ---*/ v = inv_det * DOT(dir, qvec); if (v < 0.0 || u + v > 1.0) return(false); /*--- Calculate t, ray intersects triangle ---*/ t = inv_det * DOT(edge2, qvec); /*--- Compute the intersection point in cartesian coordinates ---*/ intersect[0] = orig[0] + (t * dir[0]); intersect[1] = orig[1] + (t * dir[1]); intersect[2] = orig[2] + (t * dir[2]); return (true); } bool CGeometry::SegmentIntersectsLine(const su2double point0[2], const su2double point1[2], const su2double vert0[2], const su2double vert1[2]) { su2double det, diff0_A, diff0_B, diff1_A, diff1_B, intersect[2]; diff0_A = point0[0] - point1[0]; diff1_A = point0[1] - point1[1]; diff0_B = vert0[0] - vert1[0]; diff1_B = vert0[1] - vert1[1]; det = (diff0_A)*(diff1_B) - (diff1_A)*(diff0_B); if (det == 0) return false; /*--- Compute point of intersection ---*/ intersect[0] = ((point0[0]*point1[1] - point0[1]*point1[0])*diff0_B -(vert0[0]* vert1[1] - vert0[1]* vert1[0])*diff0_A)/det; intersect[1] = ((point0[0]*point1[1] - point0[1]*point1[0])*diff1_B -(vert0[0]* vert1[1] - vert0[1]* vert1[0])*diff1_A)/det; /*--- Check that the point is between the two surface points ---*/ su2double dist0, dist1, length; dist0 = (intersect[0] - point0[0])*(intersect[0] - point0[0]) +(intersect[1] - point0[1])*(intersect[1] - point0[1]); dist1 = (intersect[0] - point1[0])*(intersect[0] - point1[0]) +(intersect[1] - point1[1])*(intersect[1] - point1[1]); length = diff0_A*diff0_A +diff1_A*diff1_A; if ( (dist0 > length) || (dist1 > length) ) { return false; } return true; } bool CGeometry::SegmentIntersectsTriangle(su2double point0[3], const su2double point1[3], su2double vert0[3], su2double vert1[3], su2double vert2[3]) { su2double dir[3], intersect[3], u[3], v[3], edge1[3], edge2[3], Plane_Normal[3], Denominator, Numerator, Aux; SUB(dir, point1, point0); if (RayIntersectsTriangle(point0, dir, vert0, vert1, vert2, intersect)) { /*--- Check that the intersection is in the segment ---*/ SUB(u, point0, intersect); SUB(v, point1, intersect); SUB(edge1, vert1, vert0); SUB(edge2, vert2, vert0); CROSS(Plane_Normal, edge1, edge2); Denominator = DOT(Plane_Normal, u); Numerator = DOT(Plane_Normal, v); Aux = Numerator * Denominator; /*--- Intersection outside the segment ---*/ if (Aux > 0.0) return (false); } else { /*--- No intersection with the ray ---*/ return (false); } /*--- Intersection inside the segment ---*/ return (true); } void CGeometry::ComputeAirfoil_Section(su2double *Plane_P0, su2double *Plane_Normal, su2double MinXCoord, su2double MaxXCoord, su2double MinYCoord, su2double MaxYCoord, su2double MinZCoord, su2double MaxZCoord, const su2double *FlowVariable, vector<su2double> &Xcoord_Airfoil, vector<su2double> &Ycoord_Airfoil, vector<su2double> &Zcoord_Airfoil, vector<su2double> &Variable_Airfoil, bool original_surface, CConfig *config) { const bool wasActive = AD::BeginPassive(); unsigned short iMarker, iNode, jNode, iDim, Index = 0; bool intersect; long Next_Edge = 0; unsigned long iPoint, jPoint, iElem, Trailing_Point, Airfoil_Point, iVertex, iEdge, PointIndex, jEdge; su2double Segment_P0[3] = {0.0, 0.0, 0.0}, Segment_P1[3] = {0.0, 0.0, 0.0}, Variable_P0 = 0.0, Variable_P1 = 0.0, Intersection[3] = {0.0, 0.0, 0.0}, Trailing_Coord, *VarCoord = nullptr, Variable_Interp, v1[3] = {0.0, 0.0, 0.0}, v3[3] = {0.0, 0.0, 0.0}, CrossProduct = 1.0; bool Found_Edge; passivedouble Dist_Value; vector<su2double> Xcoord_Index0, Ycoord_Index0, Zcoord_Index0, Variable_Index0, Xcoord_Index1, Ycoord_Index1, Zcoord_Index1, Variable_Index1; vector<unsigned long> IGlobalID_Index0, JGlobalID_Index0, IGlobalID_Index1, JGlobalID_Index1, IGlobalID_Airfoil, JGlobalID_Airfoil; vector<unsigned short> Conection_Index0, Conection_Index1; vector<unsigned long> Duplicate; vector<unsigned long>::iterator it; su2double **Coord_Variation = nullptr; vector<su2double> XcoordExtra, YcoordExtra, ZcoordExtra, VariableExtra; vector<unsigned long> IGlobalIDExtra, JGlobalIDExtra; vector<bool> AddExtra; unsigned long EdgeDonor; bool FoundEdge; #ifdef HAVE_MPI unsigned long nLocalEdge, MaxLocalEdge, *Buffer_Send_nEdge, *Buffer_Receive_nEdge, nBuffer_Coord, nBuffer_Variable, nBuffer_GlobalID; int nProcessor, iProcessor; su2double *Buffer_Send_Coord, *Buffer_Receive_Coord; su2double *Buffer_Send_Variable, *Buffer_Receive_Variable; unsigned long *Buffer_Send_GlobalID, *Buffer_Receive_GlobalID; #endif Xcoord_Airfoil.clear(); Ycoord_Airfoil.clear(); Zcoord_Airfoil.clear(); Variable_Airfoil.clear(); IGlobalID_Airfoil.clear(); JGlobalID_Airfoil.clear(); /*--- Set the right plane in 2D (note the change in Y-Z plane) ---*/ if (nDim == 2) { Plane_P0[0] = 0.0; Plane_P0[1] = 0.0; Plane_P0[2] = 0.0; Plane_Normal[0] = 0.0; Plane_Normal[1] = 1.0; Plane_Normal[2] = 0.0; } /*--- Grid movement is stored using a vertices information, we should go from vertex to points ---*/ if (original_surface == false) { Coord_Variation = new su2double *[nPoint]; for (iPoint = 0; iPoint < nPoint; iPoint++) Coord_Variation[iPoint] = new su2double [nDim]; for (iMarker = 0; iMarker < config->GetnMarker_All(); iMarker++) { if (config->GetMarker_All_GeoEval(iMarker) == YES) { for (iVertex = 0; iVertex < nVertex[iMarker]; iVertex++) { VarCoord = vertex[iMarker][iVertex]->GetVarCoord(); iPoint = vertex[iMarker][iVertex]->GetNode(); for (iDim = 0; iDim < nDim; iDim++) Coord_Variation[iPoint][iDim] = VarCoord[iDim]; } } } } for (iMarker = 0; iMarker < nMarker; iMarker++) { if (config->GetMarker_All_GeoEval(iMarker) == YES) { for (iElem = 0; iElem < nElem_Bound[iMarker]; iElem++) { PointIndex=0; /*--- To decide if an element is going to be used or not should be done element based, The first step is to compute and average coordinate for the element ---*/ su2double AveXCoord = 0.0; su2double AveYCoord = 0.0; su2double AveZCoord = 0.0; for (iNode = 0; iNode < bound[iMarker][iElem]->GetnNodes(); iNode++) { iPoint = bound[iMarker][iElem]->GetNode(iNode); AveXCoord += nodes->GetCoord(iPoint, 0); AveYCoord += nodes->GetCoord(iPoint, 1); if (nDim == 3) AveZCoord += nodes->GetCoord(iPoint, 2); } AveXCoord /= su2double(bound[iMarker][iElem]->GetnNodes()); AveYCoord /= su2double(bound[iMarker][iElem]->GetnNodes()); AveZCoord /= su2double(bound[iMarker][iElem]->GetnNodes()); /*--- To only cut one part of the nacelle based on the cross product of the normal to the plane and a vector that connect the point with the center line ---*/ CrossProduct = 1.0; if (config->GetGeo_Description() == NACELLE) { su2double Tilt_Angle = config->GetNacelleLocation(3)*PI_NUMBER/180; su2double Toe_Angle = config->GetNacelleLocation(4)*PI_NUMBER/180; /*--- Translate to the origin ---*/ su2double XCoord_Trans = AveXCoord - config->GetNacelleLocation(0); su2double YCoord_Trans = AveYCoord - config->GetNacelleLocation(1); su2double ZCoord_Trans = AveZCoord - config->GetNacelleLocation(2); /*--- Apply tilt angle ---*/ su2double XCoord_Trans_Tilt = XCoord_Trans*cos(Tilt_Angle) + ZCoord_Trans*sin(Tilt_Angle); su2double YCoord_Trans_Tilt = YCoord_Trans; su2double ZCoord_Trans_Tilt = ZCoord_Trans*cos(Tilt_Angle) - XCoord_Trans*sin(Tilt_Angle); /*--- Apply toe angle ---*/ su2double YCoord_Trans_Tilt_Toe = XCoord_Trans_Tilt*sin(Toe_Angle) + YCoord_Trans_Tilt*cos(Toe_Angle); su2double ZCoord_Trans_Tilt_Toe = ZCoord_Trans_Tilt; /*--- Undo plane rotation, we have already rotated the nacelle ---*/ /*--- Undo tilt angle ---*/ su2double XPlane_Normal_Tilt = Plane_Normal[0]*cos(-Tilt_Angle) + Plane_Normal[2]*sin(-Tilt_Angle); su2double YPlane_Normal_Tilt = Plane_Normal[1]; su2double ZPlane_Normal_Tilt = Plane_Normal[2]*cos(-Tilt_Angle) - Plane_Normal[0]*sin(-Tilt_Angle); /*--- Undo toe angle ---*/ su2double YPlane_Normal_Tilt_Toe = XPlane_Normal_Tilt*sin(-Toe_Angle) + YPlane_Normal_Tilt*cos(-Toe_Angle); su2double ZPlane_Normal_Tilt_Toe = ZPlane_Normal_Tilt; v1[1] = YCoord_Trans_Tilt_Toe - 0.0; v1[2] = ZCoord_Trans_Tilt_Toe - 0.0; v3[0] = v1[1]*ZPlane_Normal_Tilt_Toe-v1[2]*YPlane_Normal_Tilt_Toe; CrossProduct = v3[0] * 1.0; } for (unsigned short iFace = 0; iFace < bound[iMarker][iElem]->GetnFaces(); iFace++){ iNode = bound[iMarker][iElem]->GetFaces(iFace,0); jNode = bound[iMarker][iElem]->GetFaces(iFace,1); iPoint = bound[iMarker][iElem]->GetNode(iNode); jPoint = bound[iMarker][iElem]->GetNode(jNode); if ((CrossProduct >= 0.0) && ((AveXCoord > MinXCoord) && (AveXCoord < MaxXCoord)) && ((AveYCoord > MinYCoord) && (AveYCoord < MaxYCoord)) && ((AveZCoord > MinZCoord) && (AveZCoord < MaxZCoord))) { Segment_P0[0] = 0.0; Segment_P0[1] = 0.0; Segment_P0[2] = 0.0; Variable_P0 = 0.0; Segment_P1[0] = 0.0; Segment_P1[1] = 0.0; Segment_P1[2] = 0.0; Variable_P1 = 0.0; for (iDim = 0; iDim < nDim; iDim++) { if (original_surface == true) { Segment_P0[iDim] = nodes->GetCoord(iPoint, iDim); Segment_P1[iDim] = nodes->GetCoord(jPoint, iDim); } else { Segment_P0[iDim] = nodes->GetCoord(iPoint, iDim) + Coord_Variation[iPoint][iDim]; Segment_P1[iDim] = nodes->GetCoord(jPoint, iDim) + Coord_Variation[jPoint][iDim]; } } if (FlowVariable != nullptr) { Variable_P0 = FlowVariable[iPoint]; Variable_P1 = FlowVariable[jPoint]; } /*--- In 2D add the points directly (note the change between Y and Z coordinate) ---*/ if (nDim == 2) { Xcoord_Index0.push_back(Segment_P0[0]); Xcoord_Index1.push_back(Segment_P1[0]); Ycoord_Index0.push_back(Segment_P0[2]); Ycoord_Index1.push_back(Segment_P1[2]); Zcoord_Index0.push_back(Segment_P0[1]); Zcoord_Index1.push_back(Segment_P1[1]); Variable_Index0.push_back(Variable_P0); Variable_Index1.push_back(Variable_P1); IGlobalID_Index0.push_back(nodes->GetGlobalIndex(iPoint)); IGlobalID_Index1.push_back(nodes->GetGlobalIndex(jPoint)); JGlobalID_Index0.push_back(nodes->GetGlobalIndex(iPoint)); JGlobalID_Index1.push_back(nodes->GetGlobalIndex(jPoint)); PointIndex++; } /*--- In 3D compute the intersection ---*/ else if (nDim == 3) { intersect = SegmentIntersectsPlane(Segment_P0, Segment_P1, Variable_P0, Variable_P1, Plane_P0, Plane_Normal, Intersection, Variable_Interp); if (intersect == true) { if (PointIndex == 0) { Xcoord_Index0.push_back(Intersection[0]); Ycoord_Index0.push_back(Intersection[1]); Zcoord_Index0.push_back(Intersection[2]); Variable_Index0.push_back(Variable_Interp); IGlobalID_Index0.push_back(nodes->GetGlobalIndex(iPoint)); JGlobalID_Index0.push_back(nodes->GetGlobalIndex(jPoint)); } if (PointIndex == 1) { Xcoord_Index1.push_back(Intersection[0]); Ycoord_Index1.push_back(Intersection[1]); Zcoord_Index1.push_back(Intersection[2]); Variable_Index1.push_back(Variable_Interp); IGlobalID_Index1.push_back(nodes->GetGlobalIndex(iPoint)); JGlobalID_Index1.push_back(nodes->GetGlobalIndex(jPoint)); } PointIndex++; } } } } } } } if (original_surface == false) { for (iPoint = 0; iPoint < nPoint; iPoint++) delete [] Coord_Variation[iPoint]; delete [] Coord_Variation; } #ifdef HAVE_MPI /*--- Copy the coordinates of all the points in the plane to the master node ---*/ nLocalEdge = 0, MaxLocalEdge = 0; nProcessor = size; Buffer_Send_nEdge = new unsigned long [1]; Buffer_Receive_nEdge = new unsigned long [nProcessor]; nLocalEdge = Xcoord_Index0.size(); Buffer_Send_nEdge[0] = nLocalEdge; SU2_MPI::Allreduce(&nLocalEdge, &MaxLocalEdge, 1, MPI_UNSIGNED_LONG, MPI_MAX, MPI_COMM_WORLD); SU2_MPI::Allgather(Buffer_Send_nEdge, 1, MPI_UNSIGNED_LONG, Buffer_Receive_nEdge, 1, MPI_UNSIGNED_LONG, MPI_COMM_WORLD); Buffer_Send_Coord = new su2double [MaxLocalEdge*6]; Buffer_Receive_Coord = new su2double [nProcessor*MaxLocalEdge*6]; Buffer_Send_Variable = new su2double [MaxLocalEdge*2]; Buffer_Receive_Variable = new su2double [nProcessor*MaxLocalEdge*2]; Buffer_Send_GlobalID = new unsigned long [MaxLocalEdge*4]; Buffer_Receive_GlobalID = new unsigned long [nProcessor*MaxLocalEdge*4]; nBuffer_Coord = MaxLocalEdge*6; nBuffer_Variable = MaxLocalEdge*2; nBuffer_GlobalID = MaxLocalEdge*4; for (iEdge = 0; iEdge < nLocalEdge; iEdge++) { Buffer_Send_Coord[iEdge*6 + 0] = Xcoord_Index0[iEdge]; Buffer_Send_Coord[iEdge*6 + 1] = Ycoord_Index0[iEdge]; Buffer_Send_Coord[iEdge*6 + 2] = Zcoord_Index0[iEdge]; Buffer_Send_Coord[iEdge*6 + 3] = Xcoord_Index1[iEdge]; Buffer_Send_Coord[iEdge*6 + 4] = Ycoord_Index1[iEdge]; Buffer_Send_Coord[iEdge*6 + 5] = Zcoord_Index1[iEdge]; Buffer_Send_Variable[iEdge*2 + 0] = Variable_Index0[iEdge]; Buffer_Send_Variable[iEdge*2 + 1] = Variable_Index1[iEdge]; Buffer_Send_GlobalID[iEdge*4 + 0] = IGlobalID_Index0[iEdge]; Buffer_Send_GlobalID[iEdge*4 + 1] = JGlobalID_Index0[iEdge]; Buffer_Send_GlobalID[iEdge*4 + 2] = IGlobalID_Index1[iEdge]; Buffer_Send_GlobalID[iEdge*4 + 3] = JGlobalID_Index1[iEdge]; } SU2_MPI::Allgather(Buffer_Send_Coord, nBuffer_Coord, MPI_DOUBLE, Buffer_Receive_Coord, nBuffer_Coord, MPI_DOUBLE, MPI_COMM_WORLD); SU2_MPI::Allgather(Buffer_Send_Variable, nBuffer_Variable, MPI_DOUBLE, Buffer_Receive_Variable, nBuffer_Variable, MPI_DOUBLE, MPI_COMM_WORLD); SU2_MPI::Allgather(Buffer_Send_GlobalID, nBuffer_GlobalID, MPI_UNSIGNED_LONG, Buffer_Receive_GlobalID, nBuffer_GlobalID, MPI_UNSIGNED_LONG, MPI_COMM_WORLD); /*--- Clean the vectors before adding the new vertices only to the master node ---*/ Xcoord_Index0.clear(); Xcoord_Index1.clear(); Ycoord_Index0.clear(); Ycoord_Index1.clear(); Zcoord_Index0.clear(); Zcoord_Index1.clear(); Variable_Index0.clear(); Variable_Index1.clear(); IGlobalID_Index0.clear(); IGlobalID_Index1.clear(); JGlobalID_Index0.clear(); JGlobalID_Index1.clear(); /*--- Copy the boundary to the master node vectors ---*/ if (rank == MASTER_NODE) { for (iProcessor = 0; iProcessor < nProcessor; iProcessor++) { for (iEdge = 0; iEdge < Buffer_Receive_nEdge[iProcessor]; iEdge++) { Xcoord_Index0.push_back( Buffer_Receive_Coord[ iProcessor*MaxLocalEdge*6 + iEdge*6 + 0] ); Ycoord_Index0.push_back( Buffer_Receive_Coord[ iProcessor*MaxLocalEdge*6 + iEdge*6 + 1] ); Zcoord_Index0.push_back( Buffer_Receive_Coord[ iProcessor*MaxLocalEdge*6 + iEdge*6 + 2] ); Xcoord_Index1.push_back( Buffer_Receive_Coord[ iProcessor*MaxLocalEdge*6 + iEdge*6 + 3] ); Ycoord_Index1.push_back( Buffer_Receive_Coord[ iProcessor*MaxLocalEdge*6 + iEdge*6 + 4] ); Zcoord_Index1.push_back( Buffer_Receive_Coord[ iProcessor*MaxLocalEdge*6 + iEdge*6 + 5] ); Variable_Index0.push_back( Buffer_Receive_Variable[ iProcessor*MaxLocalEdge*2 + iEdge*2 + 0] ); Variable_Index1.push_back( Buffer_Receive_Variable[ iProcessor*MaxLocalEdge*2 + iEdge*2 + 1] ); IGlobalID_Index0.push_back( Buffer_Receive_GlobalID[ iProcessor*MaxLocalEdge*4 + iEdge*4 + 0] ); JGlobalID_Index0.push_back( Buffer_Receive_GlobalID[ iProcessor*MaxLocalEdge*4 + iEdge*4 + 1] ); IGlobalID_Index1.push_back( Buffer_Receive_GlobalID[ iProcessor*MaxLocalEdge*4 + iEdge*4 + 2] ); JGlobalID_Index1.push_back( Buffer_Receive_GlobalID[ iProcessor*MaxLocalEdge*4 + iEdge*4 + 3] ); } } } delete[] Buffer_Send_Coord; delete[] Buffer_Receive_Coord; delete[] Buffer_Send_Variable; delete[] Buffer_Receive_Variable; delete[] Buffer_Send_GlobalID; delete[] Buffer_Receive_GlobalID; delete[] Buffer_Send_nEdge; delete[] Buffer_Receive_nEdge; #endif if ((rank == MASTER_NODE) && (Xcoord_Index0.size() != 0)) { /*--- Remove singular edges ---*/ bool Remove; do { Remove = false; for (iEdge = 0; iEdge < Xcoord_Index0.size(); iEdge++) { if (((IGlobalID_Index0[iEdge] == IGlobalID_Index1[iEdge]) && (JGlobalID_Index0[iEdge] == JGlobalID_Index1[iEdge])) || ((IGlobalID_Index0[iEdge] == JGlobalID_Index1[iEdge]) && (JGlobalID_Index0[iEdge] == IGlobalID_Index1[iEdge]))) { Xcoord_Index0.erase (Xcoord_Index0.begin() + iEdge); Ycoord_Index0.erase (Ycoord_Index0.begin() + iEdge); Zcoord_Index0.erase (Zcoord_Index0.begin() + iEdge); Variable_Index0.erase (Variable_Index0.begin() + iEdge); IGlobalID_Index0.erase (IGlobalID_Index0.begin() + iEdge); JGlobalID_Index0.erase (JGlobalID_Index0.begin() + iEdge); Xcoord_Index1.erase (Xcoord_Index1.begin() + iEdge); Ycoord_Index1.erase (Ycoord_Index1.begin() + iEdge); Zcoord_Index1.erase (Zcoord_Index1.begin() + iEdge); Variable_Index1.erase (Variable_Index1.begin() + iEdge); IGlobalID_Index1.erase (IGlobalID_Index1.begin() + iEdge); JGlobalID_Index1.erase (JGlobalID_Index1.begin() + iEdge); Remove = true; break; } if (Remove) break; } } while (Remove == true); /*--- Remove repeated edges computing distance, this could happend because the MPI ---*/ do { Remove = false; for (iEdge = 0; iEdge < Xcoord_Index0.size()-1; iEdge++) { for (jEdge = iEdge+1; jEdge < Xcoord_Index0.size(); jEdge++) { /*--- Edges with the same orientation ---*/ if ((((IGlobalID_Index0[iEdge] == IGlobalID_Index0[jEdge]) && (JGlobalID_Index0[iEdge] == JGlobalID_Index0[jEdge])) || ((IGlobalID_Index0[iEdge] == JGlobalID_Index0[jEdge]) && (JGlobalID_Index0[iEdge] == IGlobalID_Index0[jEdge]))) && (((IGlobalID_Index1[iEdge] == IGlobalID_Index1[jEdge]) && (JGlobalID_Index1[iEdge] == JGlobalID_Index1[jEdge])) || ((IGlobalID_Index1[iEdge] == JGlobalID_Index1[jEdge]) && (JGlobalID_Index1[iEdge] == IGlobalID_Index1[jEdge])))) { Xcoord_Index0.erase (Xcoord_Index0.begin() + jEdge); Ycoord_Index0.erase (Ycoord_Index0.begin() + jEdge); Zcoord_Index0.erase (Zcoord_Index0.begin() + jEdge); Variable_Index0.erase (Variable_Index0.begin() + jEdge); IGlobalID_Index0.erase (IGlobalID_Index0.begin() + jEdge); JGlobalID_Index0.erase (JGlobalID_Index0.begin() + jEdge); Xcoord_Index1.erase (Xcoord_Index1.begin() + jEdge); Ycoord_Index1.erase (Ycoord_Index1.begin() + jEdge); Zcoord_Index1.erase (Zcoord_Index1.begin() + jEdge); Variable_Index1.erase (Variable_Index1.begin() + jEdge); IGlobalID_Index1.erase (IGlobalID_Index1.begin() + jEdge); JGlobalID_Index1.erase (JGlobalID_Index1.begin() + jEdge); Remove = true; break; } /*--- Edges with oposite orientation ---*/ if ((((IGlobalID_Index0[iEdge] == IGlobalID_Index1[jEdge]) && (JGlobalID_Index0[iEdge] == JGlobalID_Index1[jEdge])) || ((IGlobalID_Index0[iEdge] == JGlobalID_Index1[jEdge]) && (JGlobalID_Index0[iEdge] == IGlobalID_Index1[jEdge]))) && (((IGlobalID_Index1[iEdge] == IGlobalID_Index0[jEdge]) && (JGlobalID_Index1[iEdge] == JGlobalID_Index0[jEdge])) || ((IGlobalID_Index1[iEdge] == JGlobalID_Index0[jEdge]) && (JGlobalID_Index1[iEdge] == IGlobalID_Index0[jEdge])))) { Xcoord_Index0.erase (Xcoord_Index0.begin() + jEdge); Ycoord_Index0.erase (Ycoord_Index0.begin() + jEdge); Zcoord_Index0.erase (Zcoord_Index0.begin() + jEdge); Variable_Index0.erase (Variable_Index0.begin() + jEdge); IGlobalID_Index0.erase (IGlobalID_Index0.begin() + jEdge); JGlobalID_Index0.erase (JGlobalID_Index0.begin() + jEdge); Xcoord_Index1.erase (Xcoord_Index1.begin() + jEdge); Ycoord_Index1.erase (Ycoord_Index1.begin() + jEdge); Zcoord_Index1.erase (Zcoord_Index1.begin() + jEdge); Variable_Index1.erase (Variable_Index1.begin() + jEdge); IGlobalID_Index1.erase (IGlobalID_Index1.begin() + jEdge); JGlobalID_Index1.erase (JGlobalID_Index1.begin() + jEdge); Remove = true; break; } if (Remove) break; } if (Remove) break; } } while (Remove == true); if (Xcoord_Index0.size() != 1) { /*--- Rotate from the Y-Z plane to the X-Z plane to reuse the rest of subroutines ---*/ if (config->GetGeo_Description() == FUSELAGE) { su2double Angle = -0.5*PI_NUMBER; for (iEdge = 0; iEdge < Xcoord_Index0.size(); iEdge++) { su2double XCoord = Xcoord_Index0[iEdge]*cos(Angle) - Ycoord_Index0[iEdge]*sin(Angle); su2double YCoord = Ycoord_Index0[iEdge]*cos(Angle) + Xcoord_Index0[iEdge]*sin(Angle); su2double ZCoord = Zcoord_Index0[iEdge]; Xcoord_Index0[iEdge] = XCoord; Ycoord_Index0[iEdge] = YCoord; Zcoord_Index0[iEdge] = ZCoord; XCoord = Xcoord_Index1[iEdge]*cos(Angle) - Ycoord_Index1[iEdge]*sin(Angle); YCoord = Ycoord_Index1[iEdge]*cos(Angle) + Xcoord_Index1[iEdge]*sin(Angle); ZCoord = Zcoord_Index1[iEdge]; Xcoord_Index1[iEdge] = XCoord; Ycoord_Index1[iEdge] = YCoord; Zcoord_Index1[iEdge] = ZCoord; } } /*--- Rotate nacelle secction to a X-Z plane to reuse the rest of subroutines ---*/ if (config->GetGeo_Description() == NACELLE) { su2double Tilt_Angle = config->GetNacelleLocation(3)*PI_NUMBER/180; su2double Toe_Angle = config->GetNacelleLocation(4)*PI_NUMBER/180; su2double Theta_deg = atan2(Plane_Normal[1],-Plane_Normal[2])/PI_NUMBER*180 + 180; su2double Roll_Angle = 0.5*PI_NUMBER - Theta_deg*PI_NUMBER/180; su2double XCoord_Trans, YCoord_Trans, ZCoord_Trans, XCoord_Trans_Tilt, YCoord_Trans_Tilt, ZCoord_Trans_Tilt, XCoord_Trans_Tilt_Toe, YCoord_Trans_Tilt_Toe, ZCoord_Trans_Tilt_Toe, XCoord, YCoord, ZCoord; for (iEdge = 0; iEdge < Xcoord_Index0.size(); iEdge++) { /*--- First point of the edge ---*/ /*--- Translate to the origin ---*/ XCoord_Trans = Xcoord_Index0[iEdge] - config->GetNacelleLocation(0); YCoord_Trans = Ycoord_Index0[iEdge] - config->GetNacelleLocation(1); ZCoord_Trans = Zcoord_Index0[iEdge] - config->GetNacelleLocation(2); /*--- Apply tilt angle ---*/ XCoord_Trans_Tilt = XCoord_Trans*cos(Tilt_Angle) + ZCoord_Trans*sin(Tilt_Angle); YCoord_Trans_Tilt = YCoord_Trans; ZCoord_Trans_Tilt = ZCoord_Trans*cos(Tilt_Angle) - XCoord_Trans*sin(Tilt_Angle); /*--- Apply toe angle ---*/ XCoord_Trans_Tilt_Toe = XCoord_Trans_Tilt*cos(Toe_Angle) - YCoord_Trans_Tilt*sin(Toe_Angle); YCoord_Trans_Tilt_Toe = XCoord_Trans_Tilt*sin(Toe_Angle) + YCoord_Trans_Tilt*cos(Toe_Angle); ZCoord_Trans_Tilt_Toe = ZCoord_Trans_Tilt; /*--- Rotate to X-Z plane (roll) ---*/ XCoord = XCoord_Trans_Tilt_Toe; YCoord = YCoord_Trans_Tilt_Toe*cos(Roll_Angle) - ZCoord_Trans_Tilt_Toe*sin(Roll_Angle); ZCoord = YCoord_Trans_Tilt_Toe*sin(Roll_Angle) + ZCoord_Trans_Tilt_Toe*cos(Roll_Angle); /*--- Update coordinates ---*/ Xcoord_Index0[iEdge] = XCoord; Ycoord_Index0[iEdge] = YCoord; Zcoord_Index0[iEdge] = ZCoord; /*--- Second point of the edge ---*/ /*--- Translate to the origin ---*/ XCoord_Trans = Xcoord_Index1[iEdge] - config->GetNacelleLocation(0); YCoord_Trans = Ycoord_Index1[iEdge] - config->GetNacelleLocation(1); ZCoord_Trans = Zcoord_Index1[iEdge] - config->GetNacelleLocation(2); /*--- Apply tilt angle ---*/ XCoord_Trans_Tilt = XCoord_Trans*cos(Tilt_Angle) + ZCoord_Trans*sin(Tilt_Angle); YCoord_Trans_Tilt = YCoord_Trans; ZCoord_Trans_Tilt = ZCoord_Trans*cos(Tilt_Angle) - XCoord_Trans*sin(Tilt_Angle); /*--- Apply toe angle ---*/ XCoord_Trans_Tilt_Toe = XCoord_Trans_Tilt*cos(Toe_Angle) - YCoord_Trans_Tilt*sin(Toe_Angle); YCoord_Trans_Tilt_Toe = XCoord_Trans_Tilt*sin(Toe_Angle) + YCoord_Trans_Tilt*cos(Toe_Angle); ZCoord_Trans_Tilt_Toe = ZCoord_Trans_Tilt; /*--- Rotate to X-Z plane (roll) ---*/ XCoord = XCoord_Trans_Tilt_Toe; YCoord = YCoord_Trans_Tilt_Toe*cos(Roll_Angle) - ZCoord_Trans_Tilt_Toe*sin(Roll_Angle); ZCoord = YCoord_Trans_Tilt_Toe*sin(Roll_Angle) + ZCoord_Trans_Tilt_Toe*cos(Roll_Angle); /*--- Update coordinates ---*/ Xcoord_Index1[iEdge] = XCoord; Ycoord_Index1[iEdge] = YCoord; Zcoord_Index1[iEdge] = ZCoord; } } /*--- Identify the extreme of the curve and close it ---*/ Conection_Index0.reserve(Xcoord_Index0.size()+1); Conection_Index1.reserve(Xcoord_Index0.size()+1); for (iEdge = 0; iEdge < Xcoord_Index0.size(); iEdge++) { Conection_Index0[iEdge] = 0; Conection_Index1[iEdge] = 0; } for (iEdge = 0; iEdge < Xcoord_Index0.size()-1; iEdge++) { for (jEdge = iEdge+1; jEdge < Xcoord_Index0.size(); jEdge++) { if (((IGlobalID_Index0[iEdge] == IGlobalID_Index0[jEdge]) && (JGlobalID_Index0[iEdge] == JGlobalID_Index0[jEdge])) || ((IGlobalID_Index0[iEdge] == JGlobalID_Index0[jEdge]) && (JGlobalID_Index0[iEdge] == IGlobalID_Index0[jEdge]))) { Conection_Index0[iEdge]++; Conection_Index0[jEdge]++; } if (((IGlobalID_Index0[iEdge] == IGlobalID_Index1[jEdge]) && (JGlobalID_Index0[iEdge] == JGlobalID_Index1[jEdge])) || ((IGlobalID_Index0[iEdge] == JGlobalID_Index1[jEdge]) && (JGlobalID_Index0[iEdge] == IGlobalID_Index1[jEdge]))) { Conection_Index0[iEdge]++; Conection_Index1[jEdge]++; } if (((IGlobalID_Index1[iEdge] == IGlobalID_Index0[jEdge]) && (JGlobalID_Index1[iEdge] == JGlobalID_Index0[jEdge])) || ((IGlobalID_Index1[iEdge] == JGlobalID_Index0[jEdge]) && (JGlobalID_Index1[iEdge] == IGlobalID_Index0[jEdge]))) { Conection_Index1[iEdge]++; Conection_Index0[jEdge]++; } if (((IGlobalID_Index1[iEdge] == IGlobalID_Index1[jEdge]) && (JGlobalID_Index1[iEdge] == JGlobalID_Index1[jEdge])) || ((IGlobalID_Index1[iEdge] == JGlobalID_Index1[jEdge]) && (JGlobalID_Index1[iEdge] == IGlobalID_Index1[jEdge]))) { Conection_Index1[iEdge]++; Conection_Index1[jEdge]++; } } } /*--- Connect extremes of the curves ---*/ /*--- First: Identify the extremes of the curve in the extra vector ---*/ for (iEdge = 0; iEdge < Xcoord_Index0.size(); iEdge++) { if (Conection_Index0[iEdge] == 0) { XcoordExtra.push_back(Xcoord_Index0[iEdge]); YcoordExtra.push_back(Ycoord_Index0[iEdge]); ZcoordExtra.push_back(Zcoord_Index0[iEdge]); VariableExtra.push_back(Variable_Index0[iEdge]); IGlobalIDExtra.push_back(IGlobalID_Index0[iEdge]); JGlobalIDExtra.push_back(JGlobalID_Index0[iEdge]); AddExtra.push_back(true); } if (Conection_Index1[iEdge] == 0) { XcoordExtra.push_back(Xcoord_Index1[iEdge]); YcoordExtra.push_back(Ycoord_Index1[iEdge]); ZcoordExtra.push_back(Zcoord_Index1[iEdge]); VariableExtra.push_back(Variable_Index1[iEdge]); IGlobalIDExtra.push_back(IGlobalID_Index1[iEdge]); JGlobalIDExtra.push_back(JGlobalID_Index1[iEdge]); AddExtra.push_back(true); } } /*--- Second, if it is an open curve then find the closest point to an extreme to close it ---*/ if (XcoordExtra.size() > 1) { for (iEdge = 0; iEdge < XcoordExtra.size()-1; iEdge++) { su2double MinDist = 1E6; FoundEdge = false; EdgeDonor = 0; for (jEdge = iEdge+1; jEdge < XcoordExtra.size(); jEdge++) { Dist_Value = sqrt(pow(SU2_TYPE::GetValue(XcoordExtra[iEdge])-SU2_TYPE::GetValue(XcoordExtra[jEdge]), 2.0)); if ((Dist_Value < MinDist) && (AddExtra[iEdge]) && (AddExtra[jEdge])) { EdgeDonor = jEdge; FoundEdge = true; } } if (FoundEdge) { /*--- Add first point of the new edge ---*/ Xcoord_Index0.push_back (XcoordExtra[iEdge]); Ycoord_Index0.push_back (YcoordExtra[iEdge]); Zcoord_Index0.push_back (ZcoordExtra[iEdge]); Variable_Index0.push_back (VariableExtra[iEdge]); IGlobalID_Index0.push_back (IGlobalIDExtra[iEdge]); JGlobalID_Index0.push_back (JGlobalIDExtra[iEdge]); AddExtra[iEdge] = false; /*--- Add second (closest) point of the new edge ---*/ Xcoord_Index1.push_back (XcoordExtra[EdgeDonor]); Ycoord_Index1.push_back (YcoordExtra[EdgeDonor]); Zcoord_Index1.push_back (ZcoordExtra[EdgeDonor]); Variable_Index1.push_back (VariableExtra[EdgeDonor]); IGlobalID_Index1.push_back (IGlobalIDExtra[EdgeDonor]); JGlobalID_Index1.push_back (JGlobalIDExtra[EdgeDonor]); AddExtra[EdgeDonor] = false; } } } else if (XcoordExtra.size() == 1) { cout <<"There cutting system has failed, there is an incomplete curve (not used)." << endl; } /*--- Find and add the trailing edge to to the list and the contect the first point to the trailing edge ---*/ Trailing_Point = 0; Trailing_Coord = Xcoord_Index0[0]; for (iEdge = 1; iEdge < Xcoord_Index0.size(); iEdge++) { if (Xcoord_Index0[iEdge] > Trailing_Coord) { Trailing_Point = iEdge; Trailing_Coord = Xcoord_Index0[iEdge]; } } Xcoord_Airfoil.push_back(Xcoord_Index0[Trailing_Point]); Ycoord_Airfoil.push_back(Ycoord_Index0[Trailing_Point]); Zcoord_Airfoil.push_back(Zcoord_Index0[Trailing_Point]); Variable_Airfoil.push_back(Variable_Index0[Trailing_Point]); IGlobalID_Airfoil.push_back(IGlobalID_Index0[Trailing_Point]); JGlobalID_Airfoil.push_back(JGlobalID_Index0[Trailing_Point]); Xcoord_Airfoil.push_back(Xcoord_Index1[Trailing_Point]); Ycoord_Airfoil.push_back(Ycoord_Index1[Trailing_Point]); Zcoord_Airfoil.push_back(Zcoord_Index1[Trailing_Point]); Variable_Airfoil.push_back(Variable_Index1[Trailing_Point]); IGlobalID_Airfoil.push_back(IGlobalID_Index1[Trailing_Point]); JGlobalID_Airfoil.push_back(JGlobalID_Index1[Trailing_Point]); Xcoord_Index0.erase (Xcoord_Index0.begin() + Trailing_Point); Ycoord_Index0.erase (Ycoord_Index0.begin() + Trailing_Point); Zcoord_Index0.erase (Zcoord_Index0.begin() + Trailing_Point); Variable_Index0.erase (Variable_Index0.begin() + Trailing_Point); IGlobalID_Index0.erase (IGlobalID_Index0.begin() + Trailing_Point); JGlobalID_Index0.erase (JGlobalID_Index0.begin() + Trailing_Point); Xcoord_Index1.erase (Xcoord_Index1.begin() + Trailing_Point); Ycoord_Index1.erase (Ycoord_Index1.begin() + Trailing_Point); Zcoord_Index1.erase (Zcoord_Index1.begin() + Trailing_Point); Variable_Index1.erase (Variable_Index1.begin() + Trailing_Point); IGlobalID_Index1.erase (IGlobalID_Index1.begin() + Trailing_Point); JGlobalID_Index1.erase (JGlobalID_Index1.begin() + Trailing_Point); /*--- Algorithm for adding the rest of the points ---*/ do { /*--- Last added point in the list ---*/ Airfoil_Point = Xcoord_Airfoil.size() - 1; /*--- Find the closest point ---*/ Found_Edge = false; for (iEdge = 0; iEdge < Xcoord_Index0.size(); iEdge++) { if (((IGlobalID_Index0[iEdge] == IGlobalID_Airfoil[Airfoil_Point]) && (JGlobalID_Index0[iEdge] == JGlobalID_Airfoil[Airfoil_Point])) || ((IGlobalID_Index0[iEdge] == JGlobalID_Airfoil[Airfoil_Point]) && (JGlobalID_Index0[iEdge] == IGlobalID_Airfoil[Airfoil_Point]))) { Next_Edge = iEdge; Found_Edge = true; Index = 0; break; } if (((IGlobalID_Index1[iEdge] == IGlobalID_Airfoil[Airfoil_Point]) && (JGlobalID_Index1[iEdge] == JGlobalID_Airfoil[Airfoil_Point])) || ((IGlobalID_Index1[iEdge] == JGlobalID_Airfoil[Airfoil_Point]) && (JGlobalID_Index1[iEdge] == IGlobalID_Airfoil[Airfoil_Point]))) { Next_Edge = iEdge; Found_Edge = true; Index = 1; break; } } /*--- Add and remove the next point to the list and the next point in the edge ---*/ if (Found_Edge) { if (Index == 0) { Xcoord_Airfoil.push_back(Xcoord_Index1[Next_Edge]); Ycoord_Airfoil.push_back(Ycoord_Index1[Next_Edge]); Zcoord_Airfoil.push_back(Zcoord_Index1[Next_Edge]); Variable_Airfoil.push_back(Variable_Index1[Next_Edge]); IGlobalID_Airfoil.push_back(IGlobalID_Index1[Next_Edge]); JGlobalID_Airfoil.push_back(JGlobalID_Index1[Next_Edge]); } if (Index == 1) { Xcoord_Airfoil.push_back(Xcoord_Index0[Next_Edge]); Ycoord_Airfoil.push_back(Ycoord_Index0[Next_Edge]); Zcoord_Airfoil.push_back(Zcoord_Index0[Next_Edge]); Variable_Airfoil.push_back(Variable_Index0[Next_Edge]); IGlobalID_Airfoil.push_back(IGlobalID_Index0[Next_Edge]); JGlobalID_Airfoil.push_back(JGlobalID_Index0[Next_Edge]); } Xcoord_Index0.erase(Xcoord_Index0.begin() + Next_Edge); Ycoord_Index0.erase(Ycoord_Index0.begin() + Next_Edge); Zcoord_Index0.erase(Zcoord_Index0.begin() + Next_Edge); Variable_Index0.erase(Variable_Index0.begin() + Next_Edge); IGlobalID_Index0.erase(IGlobalID_Index0.begin() + Next_Edge); JGlobalID_Index0.erase(JGlobalID_Index0.begin() + Next_Edge); Xcoord_Index1.erase(Xcoord_Index1.begin() + Next_Edge); Ycoord_Index1.erase(Ycoord_Index1.begin() + Next_Edge); Zcoord_Index1.erase(Zcoord_Index1.begin() + Next_Edge); Variable_Index1.erase(Variable_Index1.begin() + Next_Edge); IGlobalID_Index1.erase(IGlobalID_Index1.begin() + Next_Edge); JGlobalID_Index1.erase(JGlobalID_Index1.begin() + Next_Edge); } else { break; } } while (Xcoord_Index0.size() != 0); /*--- Clean the vector before using them again for storing the upper or the lower side ---*/ Xcoord_Index0.clear(); Ycoord_Index0.clear(); Zcoord_Index0.clear(); Variable_Index0.clear(); IGlobalID_Index0.clear(); JGlobalID_Index0.clear(); Xcoord_Index1.clear(); Ycoord_Index1.clear(); Zcoord_Index1.clear(); Variable_Index1.clear(); IGlobalID_Index1.clear(); JGlobalID_Index1.clear(); } } AD::EndPassive(wasActive); } void CGeometry::RegisterCoordinates(CConfig *config) const { unsigned short iDim; unsigned long iPoint; bool input = true; bool push_index = config->GetMultizone_Problem()? false : true; for (iPoint = 0; iPoint < nPoint; iPoint++) { for (iDim = 0; iDim < nDim; iDim++) { AD::RegisterInput(nodes->GetCoord(iPoint)[iDim], push_index); } if(!push_index) { nodes->SetIndex(iPoint, input); } } } void CGeometry::RegisterOutput_Coordinates(CConfig *config) const{ unsigned short iDim; unsigned long iPoint; for (iPoint = 0; iPoint < nPoint; iPoint++){ if(config->GetMultizone_Problem()) { for (iDim = 0; iDim < nDim; iDim++) { AD::RegisterOutput(nodes->GetCoord(iPoint)[iDim]); } } else { for (iDim = 0; iDim < nDim; iDim++) { AD::RegisterOutput(nodes->GetCoord(iPoint)[iDim]); } } } } void CGeometry::UpdateGeometry(CGeometry **geometry_container, CConfig *config) { unsigned short iMesh; geometry_container[MESH_0]->InitiateComms(geometry_container[MESH_0], config, COORDINATES); geometry_container[MESH_0]->CompleteComms(geometry_container[MESH_0], config, COORDINATES); if (config->GetGrid_Movement() || config->GetDynamic_Grid()){ geometry_container[MESH_0]->InitiateComms(geometry_container[MESH_0], config, GRID_VELOCITY); geometry_container[MESH_0]->CompleteComms(geometry_container[MESH_0], config, GRID_VELOCITY); } geometry_container[MESH_0]->SetCoord_CG(); geometry_container[MESH_0]->SetControlVolume(config, UPDATE); geometry_container[MESH_0]->SetBoundControlVolume(config, UPDATE); geometry_container[MESH_0]->SetMaxLength(config); for (iMesh = 1; iMesh <= config->GetnMGLevels(); iMesh++) { /*--- Update the control volume structures ---*/ geometry_container[iMesh]->SetControlVolume(config,geometry_container[iMesh-1], UPDATE); geometry_container[iMesh]->SetBoundControlVolume(config,geometry_container[iMesh-1], UPDATE); geometry_container[iMesh]->SetCoord(geometry_container[iMesh-1]); } } void CGeometry::SetCustomBoundary(CConfig *config) { unsigned short iMarker; unsigned long iVertex; string Marker_Tag; /*--- Initialize quantities for customized boundary conditions. * Custom values are initialized with the default values specified in the config (avoiding non physical values) ---*/ CustomBoundaryTemperature = new su2double*[nMarker]; CustomBoundaryHeatFlux = new su2double*[nMarker]; for(iMarker=0; iMarker < nMarker; iMarker++){ Marker_Tag = config->GetMarker_All_TagBound(iMarker); CustomBoundaryHeatFlux[iMarker] = nullptr; CustomBoundaryTemperature[iMarker] = nullptr; if(config->GetMarker_All_PyCustom(iMarker)){ switch(config->GetMarker_All_KindBC(iMarker)){ case HEAT_FLUX: CustomBoundaryHeatFlux[iMarker] = new su2double[nVertex[iMarker]]; for(iVertex=0; iVertex < nVertex[iMarker]; iVertex++){ CustomBoundaryHeatFlux[iMarker][iVertex] = config->GetWall_HeatFlux(Marker_Tag); } break; case ISOTHERMAL: CustomBoundaryTemperature[iMarker] = new su2double[nVertex[iMarker]]; for(iVertex=0; iVertex < nVertex[iMarker]; iVertex++){ CustomBoundaryTemperature[iMarker][iVertex] = config->GetIsothermal_Temperature(Marker_Tag); } break; case INLET_FLOW: // This case is handled in the solver class. break; default: cout << "WARNING: Marker " << Marker_Tag << " is not customizable. Using default behavior." << endl; break; } } } } void CGeometry::UpdateCustomBoundaryConditions(CGeometry **geometry_container, CConfig *config){ unsigned short iMGfine, iMGlevel, nMGlevel, iMarker; nMGlevel = config->GetnMGLevels(); for (iMGlevel=1; iMGlevel <= nMGlevel; iMGlevel++){ iMGfine = iMGlevel-1; for(iMarker = 0; iMarker< config->GetnMarker_All(); iMarker++){ if(config->GetMarker_All_PyCustom(iMarker)){ switch(config->GetMarker_All_KindBC(iMarker)){ case HEAT_FLUX: geometry_container[iMGlevel]->SetMultiGridWallHeatFlux(geometry_container[iMGfine], iMarker); break; case ISOTHERMAL: geometry_container[iMGlevel]->SetMultiGridWallTemperature(geometry_container[iMGfine], iMarker); break; // Inlet flow handled in solver class. default: break; } } } } } void CGeometry::ComputeSurf_Straightness(CConfig *config, bool print_on_screen) { bool RefUnitNormal_defined; unsigned short iDim, iMarker, iMarker_Global, nMarker_Global = config->GetnMarker_CfgFile(); unsigned long iVertex; constexpr passivedouble epsilon = 1.0e-6; su2double Area; string Local_TagBound, Global_TagBound; vector<su2double> Normal(nDim), UnitNormal(nDim), RefUnitNormal(nDim); /*--- Assume now that this boundary marker is straight. As soon as one AreaElement is found that is not aligend with a Reference then it is certain that the boundary marker is not straight and one can stop searching. Another possibility is that this process doesn't own any nodes of that boundary, in that case we also have to assume the boundary is straight. Any boundary type other than SYMMETRY_PLANE or EULER_WALL gets the value false (or see cases specified in the conditional below) which could be wrong. ---*/ bound_is_straight.resize(nMarker); fill(bound_is_straight.begin(), bound_is_straight.end(), true); /*--- Loop over all local markers ---*/ for (iMarker = 0; iMarker < nMarker; iMarker++) { Local_TagBound = config->GetMarker_All_TagBound(iMarker); /*--- Marker has to be Symmetry or Euler. Additionally marker can't be a moving surface and Grid Movement Elasticity is forbidden as well. All other GridMovements are rigid. ---*/ if ((config->GetMarker_All_KindBC(iMarker) == SYMMETRY_PLANE || config->GetMarker_All_KindBC(iMarker) == EULER_WALL) && config->GetMarker_Moving_Bool(Local_TagBound) == false && config->GetKind_GridMovement() != ELASTICITY) { /*--- Loop over all global markers, and find the local-global pair via matching unique string tags. ---*/ for (iMarker_Global = 0; iMarker_Global < nMarker_Global; iMarker_Global++) { Global_TagBound = config->GetMarker_CfgFile_TagBound(iMarker_Global); if (Local_TagBound == Global_TagBound) { RefUnitNormal_defined = false; iVertex = 0; while(bound_is_straight[iMarker] == true && iVertex < nVertex[iMarker]) { vertex[iMarker][iVertex]->GetNormal(Normal.data()); UnitNormal = Normal; /*--- Compute unit normal. ---*/ Area = 0.0; for (iDim = 0; iDim < nDim; iDim++) Area += Normal[iDim]*Normal[iDim]; Area = sqrt(Area); /*--- Negate for outward convention. ---*/ for (iDim = 0; iDim < nDim; iDim++) UnitNormal[iDim] /= -Area; /*--- Check if unit normal is within tolerance of the Reference unit normal. Reference unit normal = first unit normal found. ---*/ if(RefUnitNormal_defined) { for (iDim = 0; iDim < nDim; iDim++) { if( abs(RefUnitNormal[iDim] - UnitNormal[iDim]) > epsilon ) { bound_is_straight[iMarker] = false; break; } } } else { RefUnitNormal = UnitNormal; //deep copy of values RefUnitNormal_defined = true; } iVertex++; }//while iVertex }//if Local == Global }//for iMarker_Global } else { /*--- Enforce default value: false ---*/ bound_is_straight[iMarker] = false; }//if sym or euler ... }//for iMarker /*--- Communicate results and print on screen. ---*/ if(print_on_screen) { /*--- Additional vector which can later be MPI::Allreduce(d) to pring the results on screen as nMarker (local) can vary across ranks. Default 'true' as it can happen that a local rank does not contain an element of each surface marker. ---*/ vector<bool> bound_is_straight_Global(nMarker_Global, true); /*--- Match local with global tag bound and fill a Global Marker vector. ---*/ for (iMarker = 0; iMarker < nMarker; iMarker++) { Local_TagBound = config->GetMarker_All_TagBound(iMarker); for (iMarker_Global = 0; iMarker_Global < nMarker_Global; iMarker_Global++) { Global_TagBound = config->GetMarker_CfgFile_TagBound(iMarker_Global); if(Local_TagBound == Global_TagBound) bound_is_straight_Global[iMarker_Global] = bound_is_straight[iMarker]; }//for iMarker_Global }//for iMarker vector<int> Buff_Send_isStraight(nMarker_Global), Buff_Recv_isStraight(nMarker_Global); /*--- Cast to int as std::vector<boolean> can be a special construct. MPI handling using <int> is more straight-forward. ---*/ for (iMarker_Global = 0; iMarker_Global < nMarker_Global; iMarker_Global++) Buff_Send_isStraight[iMarker_Global] = static_cast<int> (bound_is_straight_Global[iMarker_Global]); /*--- Product of type <int>(bool) is equivalnt to a 'logical and' ---*/ SU2_MPI::Allreduce(Buff_Send_isStraight.data(), Buff_Recv_isStraight.data(), nMarker_Global, MPI_INT, MPI_PROD, MPI_COMM_WORLD); /*--- Print results on screen. ---*/ if(rank == MASTER_NODE) { for (iMarker_Global = 0; iMarker_Global < nMarker_Global; iMarker_Global++) { if (config->GetMarker_CfgFile_KindBC(config->GetMarker_CfgFile_TagBound(iMarker_Global)) == SYMMETRY_PLANE || config->GetMarker_CfgFile_KindBC(config->GetMarker_CfgFile_TagBound(iMarker_Global)) == EULER_WALL) { cout << "Boundary marker " << config->GetMarker_CfgFile_TagBound(iMarker_Global) << " is"; if(Buff_Recv_isStraight[iMarker_Global] == false) cout << " NOT"; if(nDim == 2) cout << " a single straight." << endl; if(nDim == 3) cout << " a single plane." << endl; }//if sym or euler }//for iMarker_Global }//if rank==MASTER }//if print_on_scren } void CGeometry::ComputeSurf_Curvature(CConfig *config) { unsigned short iMarker, iNeigh_Point, iDim, iNode, iNeighbor_Nodes, Neighbor_Node; unsigned long Neighbor_Point, iVertex, iPoint, jPoint, iElem_Bound, iEdge, nLocalVertex, MaxLocalVertex , *Buffer_Send_nVertex, *Buffer_Receive_nVertex, TotalnPointDomain; vector<unsigned long> Point_NeighborList, Elem_NeighborList, Point_Triangle, Point_Edge, Point_Critical; vector<unsigned long>::iterator it; su2double U[3] = {0.0,0.0,0.0}, V[3] = {0.0,0.0,0.0}, W[3] = {0.0,0.0,0.0}, Length_U, Length_V, Length_W, CosValue, Angle_Value, *K, *Angle_Defect, *Area_Vertex, *Angle_Alpha, *Angle_Beta, **NormalMeanK, MeanK, GaussK, MaxPrinK, cot_alpha, cot_beta, delta, X1, X2, X3, Y1, Y2, Y3, radius, *Buffer_Send_Coord, *Buffer_Receive_Coord, *Coord, Dist, MinDist, MaxK, MinK, SigmaK; bool *Check_Edge; const bool fea = config->GetStructuralProblem(); /*--- Allocate surface curvature ---*/ K = new su2double [nPoint]; for (iPoint = 0; iPoint < nPoint; iPoint++) K[iPoint] = 0.0; if (nDim == 2) { /*--- Loop over all the markers ---*/ for (iMarker = 0; iMarker < nMarker; iMarker++) { if (config->GetMarker_All_KindBC(iMarker) != SEND_RECEIVE) { /*--- Loop through all marker vertices again, this time also finding the neighbors of each node.---*/ for (iVertex = 0; iVertex < nVertex[iMarker]; iVertex++) { iPoint = vertex[iMarker][iVertex]->GetNode(); if (nodes->GetDomain(iPoint)) { /*--- Loop through neighbors. In 2-D, there should be 2 nodes on either side of this vertex that lie on the same surface. ---*/ Point_Edge.clear(); for (iNeigh_Point = 0; iNeigh_Point < nodes->GetnPoint(iPoint); iNeigh_Point++) { Neighbor_Point = nodes->GetPoint(iPoint, iNeigh_Point); /*--- Check if this neighbor lies on the surface. If so, add to the list of neighbors. ---*/ if (nodes->GetPhysicalBoundary(Neighbor_Point)) { Point_Edge.push_back(Neighbor_Point); } } if (Point_Edge.size() == 2) { /*--- Compute the curvature using three points ---*/ X1 = nodes->GetCoord(iPoint, 0); X2 = nodes->GetCoord(Point_Edge[0], 0); X3 = nodes->GetCoord(Point_Edge[1], 0); Y1 = nodes->GetCoord(iPoint, 1); Y2 = nodes->GetCoord(Point_Edge[0], 1); Y3 = nodes->GetCoord(Point_Edge[1], 1); radius = sqrt(((X2-X1)*(X2-X1) + (Y2-Y1)*(Y2-Y1))* ((X2-X3)*(X2-X3) + (Y2-Y3)*(Y2-Y3))* ((X3-X1)*(X3-X1) + (Y3-Y1)*(Y3-Y1)))/ (2.0*fabs(X1*Y2+X2*Y3+X3*Y1-X1*Y3-X2*Y1-X3*Y2)+EPS); K[iPoint] = 1.0/radius; nodes->SetCurvature(iPoint, K[iPoint]); } } } } } } else { Angle_Defect = new su2double [nPoint]; Area_Vertex = new su2double [nPoint]; for (iPoint = 0; iPoint < nPoint; iPoint++) { Angle_Defect[iPoint] = 2*PI_NUMBER; Area_Vertex[iPoint] = 0.0; } Angle_Alpha = new su2double [nEdge]; Angle_Beta = new su2double [nEdge]; Check_Edge = new bool [nEdge]; for (iEdge = 0; iEdge < nEdge; iEdge++) { Angle_Alpha[iEdge] = 0.0; Angle_Beta[iEdge] = 0.0; Check_Edge[iEdge] = true; } NormalMeanK = new su2double *[nPoint]; for (iPoint = 0; iPoint < nPoint; iPoint++) { NormalMeanK[iPoint] = new su2double [nDim]; for (iDim = 0; iDim < nDim; iDim++) { NormalMeanK[iPoint][iDim] = 0.0; } } /*--- Loop over all the markers ---*/ for (iMarker = 0; iMarker < nMarker; iMarker++) { if (config->GetMarker_All_KindBC(iMarker) != SEND_RECEIVE) { /*--- Loop over all the boundary elements ---*/ for (iElem_Bound = 0; iElem_Bound < nElem_Bound[iMarker]; iElem_Bound++) { /*--- Only triangles ---*/ if (bound[iMarker][iElem_Bound]->GetVTK_Type() == TRIANGLE) { /*--- Loop over all the nodes of the boundary element ---*/ for (iNode = 0; iNode < bound[iMarker][iElem_Bound]->GetnNodes(); iNode++) { iPoint = bound[iMarker][iElem_Bound]->GetNode(iNode); Point_Triangle.clear(); for (iNeighbor_Nodes = 0; iNeighbor_Nodes < bound[iMarker][iElem_Bound]->GetnNeighbor_Nodes(iNode); iNeighbor_Nodes++) { Neighbor_Node = bound[iMarker][iElem_Bound]->GetNeighbor_Nodes(iNode, iNeighbor_Nodes); Neighbor_Point = bound[iMarker][iElem_Bound]->GetNode(Neighbor_Node); Point_Triangle.push_back(Neighbor_Point); } iEdge = FindEdge(Point_Triangle[0], Point_Triangle[1]); for (iDim = 0; iDim < nDim; iDim++) { U[iDim] = nodes->GetCoord(Point_Triangle[0], iDim) - nodes->GetCoord(iPoint, iDim); V[iDim] = nodes->GetCoord(Point_Triangle[1], iDim) - nodes->GetCoord(iPoint, iDim); } W[0] = 0.5*(U[1]*V[2]-U[2]*V[1]); W[1] = -0.5*(U[0]*V[2]-U[2]*V[0]); W[2] = 0.5*(U[0]*V[1]-U[1]*V[0]); Length_U = 0.0; Length_V = 0.0; Length_W = 0.0; CosValue = 0.0; for (iDim = 0; iDim < nDim; iDim++) { Length_U += U[iDim]*U[iDim]; Length_V += V[iDim]*V[iDim]; Length_W += W[iDim]*W[iDim]; } Length_U = sqrt(Length_U); Length_V = sqrt(Length_V); Length_W = sqrt(Length_W); for (iDim = 0; iDim < nDim; iDim++) { U[iDim] /= Length_U; V[iDim] /= Length_V; CosValue += U[iDim]*V[iDim]; } if (CosValue >= 1.0) CosValue = 1.0; if (CosValue <= -1.0) CosValue = -1.0; Angle_Value = acos(CosValue); Area_Vertex[iPoint] += Length_W; Angle_Defect[iPoint] -= Angle_Value; if (Angle_Alpha[iEdge] == 0.0) Angle_Alpha[iEdge] = Angle_Value; else Angle_Beta[iEdge] = Angle_Value; } } } } } /*--- Compute mean curvature ---*/ for (iMarker = 0; iMarker < nMarker; iMarker++) { if (config->GetMarker_All_KindBC(iMarker) != SEND_RECEIVE) { for (iElem_Bound = 0; iElem_Bound < nElem_Bound[iMarker]; iElem_Bound++) { if (bound[iMarker][iElem_Bound]->GetVTK_Type() == TRIANGLE) { for (iNode = 0; iNode < bound[iMarker][iElem_Bound]->GetnNodes(); iNode++) { iPoint = bound[iMarker][iElem_Bound]->GetNode(iNode); for (iNeighbor_Nodes = 0; iNeighbor_Nodes < bound[iMarker][iElem_Bound]->GetnNeighbor_Nodes(iNode); iNeighbor_Nodes++) { Neighbor_Node = bound[iMarker][iElem_Bound]->GetNeighbor_Nodes(iNode, iNeighbor_Nodes); jPoint = bound[iMarker][iElem_Bound]->GetNode(Neighbor_Node); iEdge = FindEdge(iPoint, jPoint); if (Check_Edge[iEdge]) { Check_Edge[iEdge] = false; if (tan(Angle_Alpha[iEdge]) != 0.0) cot_alpha = 1.0/tan(Angle_Alpha[iEdge]); else cot_alpha = 0.0; if (tan(Angle_Beta[iEdge]) != 0.0) cot_beta = 1.0/tan(Angle_Beta[iEdge]); else cot_beta = 0.0; /*--- iPoint, and jPoint ---*/ for (iDim = 0; iDim < nDim; iDim++) { if (Area_Vertex[iPoint] != 0.0) NormalMeanK[iPoint][iDim] += 3.0 * (cot_alpha + cot_beta) * (nodes->GetCoord(iPoint, iDim) - nodes->GetCoord(jPoint, iDim)) / Area_Vertex[iPoint]; if (Area_Vertex[jPoint] != 0.0) NormalMeanK[jPoint][iDim] += 3.0 * (cot_alpha + cot_beta) * (nodes->GetCoord(jPoint, iDim) - nodes->GetCoord(iPoint, iDim)) / Area_Vertex[jPoint]; } } } } } } } } /*--- Compute Gauss, mean, max and min principal curvature, and set the list of critical points ---*/ for (iMarker = 0; iMarker < nMarker; iMarker++) { if (config->GetMarker_All_KindBC(iMarker) != SEND_RECEIVE) { for (iVertex = 0; iVertex < nVertex[iMarker]; iVertex++) { iPoint = vertex[iMarker][iVertex]->GetNode(); if (nodes->GetDomain(iPoint)) { if (Area_Vertex[iPoint] != 0.0) GaussK = 3.0*Angle_Defect[iPoint]/Area_Vertex[iPoint]; else GaussK = 0.0; MeanK = 0.0; for (iDim = 0; iDim < nDim; iDim++) MeanK += NormalMeanK[iPoint][iDim]*NormalMeanK[iPoint][iDim]; MeanK = sqrt(MeanK); delta = max((MeanK*MeanK - GaussK), 0.0); MaxPrinK = MeanK + sqrt(delta); /*--- Store the curvature value ---*/ K[iPoint] = MaxPrinK; nodes->SetCurvature(iPoint, K[iPoint]); } } } } delete [] Angle_Defect; delete [] Area_Vertex; delete [] Angle_Alpha; delete [] Angle_Beta; delete [] Check_Edge; for (iPoint = 0; iPoint < nPoint; iPoint++) delete [] NormalMeanK[iPoint]; delete [] NormalMeanK; } /*--- Sharp edge detection is based in the statistical distribution of the curvature ---*/ MaxK = K[0]; MinK = K[0]; MeanK = 0.0; TotalnPointDomain = 0; for (iMarker = 0; iMarker < nMarker; iMarker++) { if (config->GetMarker_All_KindBC(iMarker) != SEND_RECEIVE) { for (iVertex = 0; iVertex < nVertex[iMarker]; iVertex++) { iPoint = vertex[iMarker][iVertex]->GetNode(); if (nodes->GetDomain(iPoint)) { MaxK = max(MaxK, fabs(K[iPoint])); MinK = min(MinK, fabs(K[iPoint])); MeanK += fabs(K[iPoint]); TotalnPointDomain++; } } } } su2double MyMeanK = MeanK; MeanK = 0.0; su2double MyMaxK = MaxK; MaxK = 0.0; unsigned long MynPointDomain = TotalnPointDomain; TotalnPointDomain = 0; SU2_MPI::Allreduce(&MyMeanK, &MeanK, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD); SU2_MPI::Allreduce(&MyMaxK, &MaxK, 1, MPI_DOUBLE, MPI_MAX, MPI_COMM_WORLD); SU2_MPI::Allreduce(&MynPointDomain, &TotalnPointDomain, 1, MPI_UNSIGNED_LONG, MPI_SUM, MPI_COMM_WORLD); /*--- Compute the mean ---*/ MeanK /= su2double(TotalnPointDomain); /*--- Compute the standard deviation ---*/ SigmaK = 0.0; for (iMarker = 0; iMarker < nMarker; iMarker++) { if (config->GetMarker_All_KindBC(iMarker) != SEND_RECEIVE) { for (iVertex = 0; iVertex < nVertex[iMarker]; iVertex++) { iPoint = vertex[iMarker][iVertex]->GetNode(); if (nodes->GetDomain(iPoint)) { SigmaK += (fabs(K[iPoint]) - MeanK) * (fabs(K[iPoint]) - MeanK); } } } } su2double MySigmaK = SigmaK; SigmaK = 0.0; SU2_MPI::Allreduce(&MySigmaK, &SigmaK, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD); SigmaK = sqrt(SigmaK/su2double(TotalnPointDomain)); if ((rank == MASTER_NODE) && (!fea)) cout << "Max K: " << MaxK << ". Mean K: " << MeanK << ". Standard deviation K: " << SigmaK << "." << endl; Point_Critical.clear(); for (iMarker = 0; iMarker < nMarker; iMarker++) { if (config->GetMarker_All_KindBC(iMarker) != SEND_RECEIVE) { for (iVertex = 0; iVertex < nVertex[iMarker]; iVertex++) { iPoint = vertex[iMarker][iVertex]->GetNode(); if (nodes->GetDomain(iPoint)) { if (fabs(K[iPoint]) > MeanK + config->GetRefSharpEdges()*SigmaK) { Point_Critical.push_back(iPoint); } } } } } /*--- Variables and buffers needed for MPI ---*/ Buffer_Send_nVertex = new unsigned long [1]; Buffer_Receive_nVertex = new unsigned long [size]; /*--- Count the total number of critical edge nodes. ---*/ nLocalVertex = Point_Critical.size(); Buffer_Send_nVertex[0] = nLocalVertex; /*--- Communicate to all processors the total number of critical edge nodes. ---*/ MaxLocalVertex = 0; SU2_MPI::Allreduce(&nLocalVertex, &MaxLocalVertex, 1, MPI_UNSIGNED_LONG, MPI_MAX, MPI_COMM_WORLD); SU2_MPI::Allgather(Buffer_Send_nVertex, 1, MPI_UNSIGNED_LONG, Buffer_Receive_nVertex, 1, MPI_UNSIGNED_LONG, MPI_COMM_WORLD); /*--- Create and initialize to zero some buffers to hold the coordinates of the boundary nodes that are communicated from each partition (all-to-all). ---*/ const unsigned long nBuffer = MaxLocalVertex*nDim; Buffer_Send_Coord = new su2double [nBuffer] (); Buffer_Receive_Coord = new su2double [size*nBuffer]; /*--- Retrieve and store the coordinates of the sharp edges boundary nodes on the local partition and broadcast them to all partitions. ---*/ for (iVertex = 0; iVertex < Point_Critical.size(); iVertex++) { iPoint = Point_Critical[iVertex]; for (iDim = 0; iDim < nDim; iDim++) Buffer_Send_Coord[iVertex*nDim+iDim] = nodes->GetCoord(iPoint, iDim); } SU2_MPI::Allgather(Buffer_Send_Coord, nBuffer, MPI_DOUBLE, Buffer_Receive_Coord, nBuffer, MPI_DOUBLE, MPI_COMM_WORLD); /*--- Loop over all interior mesh nodes on the local partition and compute the distances to each of the no-slip boundary nodes in the entire mesh. Store the minimum distance to the wall for each interior mesh node. ---*/ for (iPoint = 0; iPoint < GetnPoint(); iPoint++) { Coord = nodes->GetCoord(iPoint); MinDist = 1E20; for (int iProcessor = 0; iProcessor < size; iProcessor++) { for (iVertex = 0; iVertex < Buffer_Receive_nVertex[iProcessor]; iVertex++) { Dist = 0.0; for (iDim = 0; iDim < nDim; iDim++) { Dist += (Coord[iDim]-Buffer_Receive_Coord[(iProcessor*MaxLocalVertex+iVertex)*nDim+iDim])* (Coord[iDim]-Buffer_Receive_Coord[(iProcessor*MaxLocalVertex+iVertex)*nDim+iDim]); } if (Dist!=0.0) Dist = sqrt(Dist); else Dist = 0.0; if (Dist < MinDist) MinDist = Dist; } } nodes->SetSharpEdge_Distance(iPoint, MinDist); } /*--- Deallocate Max curvature ---*/ delete[] K; /*--- Deallocate the buffers needed for the MPI communication. ---*/ delete[] Buffer_Send_Coord; delete[] Buffer_Receive_Coord; delete[] Buffer_Send_nVertex; delete[] Buffer_Receive_nVertex; } void CGeometry::FilterValuesAtElementCG(const vector<su2double> &filter_radius, const vector<pair<unsigned short,su2double> > &kernels, const unsigned short search_limit, su2double *values) const { /*--- Apply a filter to "input_values". The filter is an averaging process over the neighbourhood of each element, which is a circle in 2D and a sphere in 3D of radius "filter_radius". The filter is characterized by its kernel, i.e. how the weights are computed. Multiple kernels can be specified in which case they are applied sequentially (each one being applied to the output values of the previous filter. ---*/ /*--- Check if we need to do any work. ---*/ if ( kernels.empty() ) return; /*--- FIRST: Gather the adjacency matrix, element centroids, volumes, and values on every processor, this is required because the filter reaches far into adjacent partitions. ---*/ /*--- Adjacency matrix ---*/ vector<unsigned long> neighbour_start; long *neighbour_idx = nullptr; GetGlobalElementAdjacencyMatrix(neighbour_start,neighbour_idx); /*--- Element centroids and volumes. ---*/ su2double *cg_elem = new su2double [Global_nElemDomain*nDim], *vol_elem = new su2double [Global_nElemDomain]; #ifdef HAVE_MPI /*--- Number of subdomain each point is part of. ---*/ vector<char> halo_detect(Global_nElemDomain); #endif /*--- Inputs of a filter stage, like with CG and volumes, each processor needs to see everything. ---*/ su2double *work_values = new su2double [Global_nElemDomain]; /*--- When gathering the neighborhood of each element we use a vector of booleans to indicate whether an element is already added to the list of neighbors (one vector per thread). ---*/ vector<vector<bool> > is_neighbor(omp_get_max_threads()); /*--- Begin OpenMP parallel section, count total number of searches for which the recursion limit is reached and the full neighborhood is not considered. ---*/ unsigned long limited_searches = 0; SU2_OMP_PARALLEL_(reduction(+:limited_searches)) { /*--- Initialize ---*/ SU2_OMP_FOR_STAT(256) for(auto iElem=0ul; iElem<Global_nElemDomain; ++iElem) { for(unsigned short iDim=0; iDim<nDim; ++iDim) cg_elem[nDim*iElem+iDim] = 0.0; vol_elem[iElem] = 0.0; } /*--- Populate ---*/ SU2_OMP_FOR_STAT(256) for(auto iElem=0ul; iElem<nElem; ++iElem) { auto iElem_global = elem[iElem]->GetGlobalIndex(); for(unsigned short iDim=0; iDim<nDim; ++iDim) cg_elem[nDim*iElem_global+iDim] = elem[iElem]->GetCG(iDim); vol_elem[iElem_global] = elem[iElem]->GetVolume(); } #ifdef HAVE_MPI /*--- Account for the duplication introduced by the halo elements and the reduction using MPI_SUM, which is required to maintain differentiabillity. ---*/ SU2_OMP_FOR_STAT(256) for(auto iElem=0ul; iElem<Global_nElemDomain; ++iElem) halo_detect[iElem] = 0; SU2_OMP_FOR_STAT(256) for(auto iElem=0ul; iElem<nElem; ++iElem) halo_detect[elem[iElem]->GetGlobalIndex()] = 1; /*--- Share with all processors ---*/ SU2_OMP_MASTER { su2double* dbl_buffer = new su2double [Global_nElemDomain*nDim]; SU2_MPI::Allreduce(cg_elem,dbl_buffer,Global_nElemDomain*nDim,MPI_DOUBLE,MPI_SUM,MPI_COMM_WORLD); swap(dbl_buffer, cg_elem); delete [] dbl_buffer; dbl_buffer = new su2double [Global_nElemDomain]; SU2_MPI::Allreduce(vol_elem,dbl_buffer,Global_nElemDomain,MPI_DOUBLE,MPI_SUM,MPI_COMM_WORLD); swap(dbl_buffer, vol_elem); delete [] dbl_buffer; vector<char> char_buffer(Global_nElemDomain); MPI_Allreduce(halo_detect.data(),char_buffer.data(),Global_nElemDomain,MPI_CHAR,MPI_SUM,MPI_COMM_WORLD); halo_detect.swap(char_buffer); } SU2_OMP_BARRIER SU2_OMP_FOR_STAT(256) for(auto iElem=0ul; iElem<Global_nElemDomain; ++iElem) { su2double numRepeat = halo_detect[iElem]; for(unsigned short iDim=0; iDim<nDim; ++iDim) cg_elem[nDim*iElem+iDim] /= numRepeat; vol_elem[iElem] /= numRepeat; } #endif /*--- SECOND: Each processor performs the average for its elements. For each element we look for neighbours of neighbours of... until the distance to the closest newly found one is greater than the filter radius. ---*/ is_neighbor[omp_get_thread_num()].resize(Global_nElemDomain,false); for (unsigned long iKernel=0; iKernel<kernels.size(); ++iKernel) { unsigned short kernel_type = kernels[iKernel].first; su2double kernel_param = kernels[iKernel].second; su2double kernel_radius = filter_radius[iKernel]; /*--- Synchronize work values ---*/ /*--- Initialize ---*/ SU2_OMP_FOR_STAT(256) for(auto iElem=0ul; iElem<Global_nElemDomain; ++iElem) work_values[iElem] = 0.0; /*--- Populate ---*/ SU2_OMP_FOR_STAT(256) for(auto iElem=0ul; iElem<nElem; ++iElem) work_values[elem[iElem]->GetGlobalIndex()] = values[iElem]; #ifdef HAVE_MPI /*--- Share with all processors ---*/ SU2_OMP_MASTER { su2double *buffer = new su2double [Global_nElemDomain]; SU2_MPI::Allreduce(work_values,buffer,Global_nElemDomain,MPI_DOUBLE,MPI_SUM,MPI_COMM_WORLD); swap(buffer, work_values); delete [] buffer; } SU2_OMP_BARRIER /*--- Account for duplication ---*/ SU2_OMP_FOR_STAT(256) for(auto iElem=0ul; iElem<Global_nElemDomain; ++iElem) { su2double numRepeat = halo_detect[iElem]; work_values[iElem] /= numRepeat; } #endif /*--- Filter ---*/ SU2_OMP_FOR_DYN(128) for(auto iElem=0ul; iElem<nElem; ++iElem) { int thread = omp_get_thread_num(); /*--- Center of the search ---*/ auto iElem_global = elem[iElem]->GetGlobalIndex(); /*--- Find the neighbours of iElem ---*/ vector<long> neighbours; limited_searches += !GetRadialNeighbourhood(iElem_global, SU2_TYPE::GetValue(kernel_radius), search_limit, neighbour_start, neighbour_idx, cg_elem, neighbours, is_neighbor[thread]); /*--- Apply the kernel ---*/ su2double weight = 0.0, numerator = 0.0, denominator = 0.0; switch ( kernel_type ) { /*--- distance-based kernels (weighted averages) ---*/ case CONSTANT_WEIGHT_FILTER: case CONICAL_WEIGHT_FILTER: case GAUSSIAN_WEIGHT_FILTER: for (auto idx : neighbours) { su2double distance = 0.0; for (unsigned short iDim=0; iDim<nDim; ++iDim) distance += pow(cg_elem[nDim*iElem_global+iDim]-cg_elem[nDim*idx+iDim],2); distance = sqrt(distance); switch ( kernel_type ) { case CONSTANT_WEIGHT_FILTER: weight = 1.0; break; case CONICAL_WEIGHT_FILTER: weight = kernel_radius-distance; break; case GAUSSIAN_WEIGHT_FILTER: weight = exp(-0.5*pow(distance/kernel_param,2)); break; default: break; } weight *= vol_elem[idx]; numerator += weight*work_values[idx]; denominator += weight; } values[iElem] = numerator/denominator; break; /*--- morphology kernels (image processing) ---*/ case DILATE_MORPH_FILTER: case ERODE_MORPH_FILTER: for (auto idx : neighbours) { switch ( kernel_type ) { case DILATE_MORPH_FILTER: numerator += exp(kernel_param*work_values[idx]); break; case ERODE_MORPH_FILTER: numerator += exp(kernel_param*(1.0-work_values[idx])); break; default: break; } denominator += 1.0; } values[iElem] = log(numerator/denominator)/kernel_param; if ( kernel_type==ERODE_MORPH_FILTER ) values[iElem] = 1.0-values[iElem]; break; default: SU2_MPI::Error("Unknown type of filter kernel",CURRENT_FUNCTION); } } } } // end OpenMP parallel section limited_searches /= kernels.size(); unsigned long tmp = limited_searches; SU2_MPI::Reduce(&tmp,&limited_searches,1,MPI_UNSIGNED_LONG,MPI_SUM,MASTER_NODE,MPI_COMM_WORLD); if (rank==MASTER_NODE && limited_searches>0) cout << "Warning: The filter radius was limited for " << limited_searches << " elements (" << limited_searches/(0.01*Global_nElemDomain) << "%).\n"; delete [] neighbour_idx; delete [] cg_elem; delete [] vol_elem; delete [] work_values; } void CGeometry::GetGlobalElementAdjacencyMatrix(vector<unsigned long> &neighbour_start, long *&neighbour_idx) const { if ( neighbour_idx != nullptr ) SU2_MPI::Error("neighbour_idx is expected to be NULL, stopping to avoid a potential memory leak",CURRENT_FUNCTION); /*--- Determine how much space we need for the adjacency matrix by counting the neighbours of each element, i.e. its number of faces---*/ unsigned short *nFaces_elem = new unsigned short [Global_nElemDomain]; SU2_OMP_PARALLEL { SU2_OMP_FOR_STAT(256) for(auto iElem=0ul; iElem<Global_nElemDomain; ++iElem) nFaces_elem[iElem] = 0; SU2_OMP_FOR_STAT(256) for(auto iElem=0ul; iElem<nElem; ++iElem) { auto iElem_global = elem[iElem]->GetGlobalIndex(); nFaces_elem[iElem_global] = elem[iElem]->GetnFaces(); } } #ifdef HAVE_MPI /*--- Share with all processors ---*/ { unsigned short *buffer = new unsigned short [Global_nElemDomain]; MPI_Allreduce(nFaces_elem,buffer,Global_nElemDomain,MPI_UNSIGNED_SHORT,MPI_MAX,MPI_COMM_WORLD); /*--- swap pointers and delete old data to keep the same variable name after reduction ---*/ swap(buffer, nFaces_elem); delete [] buffer; } #endif /*--- Vector with the addresses of the start of the neighbours of a given element. This is generated by a cumulative sum of the neighbour count. ---*/ neighbour_start.resize(Global_nElemDomain+1); neighbour_start[0] = 0; for(auto iElem=0ul; iElem<Global_nElemDomain; ++iElem) { neighbour_start[iElem+1] = neighbour_start[iElem]+nFaces_elem[iElem]; } delete [] nFaces_elem; /*--- Allocate ---*/ unsigned long matrix_size = neighbour_start[Global_nElemDomain]; neighbour_idx = new long [matrix_size]; SU2_OMP_PARALLEL { /*--- Initialize ---*/ SU2_OMP_FOR_STAT(256) for(auto iElem=0ul; iElem<matrix_size; ++iElem) neighbour_idx[iElem] = -1; /*--- Populate ---*/ SU2_OMP_FOR_STAT(128) for(auto iElem=0ul; iElem<nElem; ++iElem) { auto iElem_global = elem[iElem]->GetGlobalIndex(); auto start_pos = neighbour_start[iElem_global]; for(unsigned short iFace=0; iFace<elem[iElem]->GetnFaces(); ++iFace) { long neighbour = elem[iElem]->GetNeighbor_Elements(iFace); if ( neighbour>=0 ) { neighbour_idx[start_pos+iFace] = elem[neighbour]->GetGlobalIndex(); } } } } #ifdef HAVE_MPI /*--- Share with all processors ---*/ { long *buffer = new long [matrix_size]; MPI_Allreduce(neighbour_idx,buffer,matrix_size,MPI_LONG,MPI_MAX,MPI_COMM_WORLD); swap(buffer, neighbour_idx); delete [] buffer; } #endif } bool CGeometry::GetRadialNeighbourhood(const unsigned long iElem_global, const passivedouble radius, size_t search_limit, const vector<unsigned long> &neighbour_start, const long *neighbour_idx, const su2double *cg_elem, vector<long> &neighbours, vector<bool> &is_neighbor) const { /*--- Validate inputs if we are debugging. ---*/ assert(neighbour_start.size() == Global_nElemDomain+1 && neighbour_idx != nullptr && cg_elem != nullptr && is_neighbor.size() == Global_nElemDomain && "invalid inputs"); /*--- 0 search_limit means "unlimited" (it will probably stop once it gathers the entire domain, probably). ---*/ if (!search_limit) search_limit = numeric_limits<size_t>::max(); /*--- Center of the search ---*/ neighbours.clear(); neighbours.push_back(iElem_global); is_neighbor[iElem_global] = true; passivedouble X0[3] = {0.0, 0.0, 0.0}; for (unsigned short iDim=0; iDim<nDim; ++iDim) X0[iDim] = SU2_TYPE::GetValue(cg_elem[nDim*iElem_global+iDim]); /*--- Loop stops when "neighbours" stops changing size, or degree reaches limit. ---*/ bool finished = false; for (size_t degree=0, start=0; degree < search_limit && !finished; ++degree) { /*--- For each element of the last degree added consider its immediate neighbours, that are not already neighbours, as candidates. ---*/ vector<long> candidates; for (auto it = neighbours.begin()+start; it!=neighbours.end(); ++it) { /*--- scan row of the adjacency matrix of element *it ---*/ for (auto i = neighbour_start[*it]; i < neighbour_start[(*it)+1]; ++i) { auto idx = neighbour_idx[i]; if (idx>=0) if (!is_neighbor[idx]) { candidates.push_back(idx); /*--- mark as neighbour for now to avoid duplicate candidates. ---*/ is_neighbor[idx] = true; } } } /*--- update start position to fetch next degree candidates. ---*/ start = neighbours.size(); /*--- Add candidates within "radius" of X0, if none qualifies we are "finished". ---*/ finished = true; for (auto idx : candidates) { /*--- passivedouble as we only need to compare "distance". ---*/ passivedouble distance = 0.0; for (unsigned short iDim=0; iDim<nDim; ++iDim) distance += pow(X0[iDim]-SU2_TYPE::GetValue(cg_elem[nDim*idx+iDim]),2); if(distance < pow(radius,2)) { neighbours.push_back(idx); finished = false; } /*--- not a neighbour in the end. ---*/ else is_neighbor[idx] = false; } } /*--- Restore the state of the working vector for next call. ---*/ for(auto idx : neighbours) is_neighbor[idx] = false; return finished; } void CGeometry::SetElemVolume(CConfig *config) { SU2_OMP_PARALLEL { /*--- Create a bank of elements to avoid instantiating inside loop. ---*/ CElement *elements[4] = {nullptr, nullptr, nullptr, nullptr}; if (nDim==2) { elements[0] = new CTRIA1(); elements[1] = new CQUAD4(); } else { elements[0] = new CTETRA1(); elements[1] = new CPYRAM5(); elements[2] = new CPRISM6(); elements[3] = new CHEXA8(); } /*--- Compute and store the volume of each "elem". ---*/ SU2_OMP_FOR_DYN(128) for (unsigned long iElem=0; iElem<nElem; ++iElem) { /*--- Get the appropriate type of element. ---*/ CElement* element = nullptr; switch (elem[iElem]->GetVTK_Type()) { case TRIANGLE: element = elements[0]; break; case QUADRILATERAL: element = elements[1]; break; case TETRAHEDRON: element = elements[0]; break; case PYRAMID: element = elements[1]; break; case PRISM: element = elements[2]; break; case HEXAHEDRON: element = elements[3]; break; default: SU2_MPI::Error("Cannot compute the area/volume of a 1D element.",CURRENT_FUNCTION); } /*--- Set the nodal coordinates of the element. ---*/ for (unsigned short iNode=0; iNode<elem[iElem]->GetnNodes(); ++iNode) { unsigned long node_idx = elem[iElem]->GetNode(iNode); for (unsigned short iDim=0; iDim<nDim; ++iDim) { su2double coord = nodes->GetCoord(node_idx, iDim); element->SetRef_Coord(iNode, iDim, coord); } } /*--- Compute ---*/ if(nDim==2) elem[iElem]->SetVolume(element->ComputeArea()); else elem[iElem]->SetVolume(element->ComputeVolume()); } delete elements[0]; delete elements[1]; if (nDim==3) { delete elements[2]; delete elements[3]; } } // end SU2_OMP_PARALLEL } void CGeometry::SetGeometryPlanes(CConfig *config) { bool loop_on; unsigned short iMarker = 0; su2double *Face_Normal = nullptr, *Xcoord = nullptr, *Ycoord = nullptr, *Zcoord = nullptr, *FaceArea = nullptr; unsigned long jVertex, iVertex, ixCoord, iPoint, iVertex_Wall, nVertex_Wall = 0; /*--- Compute the total number of points on the near-field ---*/ nVertex_Wall = 0; for (iMarker = 0; iMarker < config->GetnMarker_All(); iMarker++) if ((config->GetMarker_All_KindBC(iMarker) == HEAT_FLUX) || (config->GetMarker_All_KindBC(iMarker) == ISOTHERMAL) || (config->GetMarker_All_KindBC(iMarker) == EULER_WALL) ) nVertex_Wall += nVertex[iMarker]; /*--- Create an array with all the coordinates, points, pressures, face area, equivalent area, and nearfield weight ---*/ Xcoord = new su2double[nVertex_Wall]; Ycoord = new su2double[nVertex_Wall]; if (nDim == 3) Zcoord = new su2double[nVertex_Wall]; FaceArea = new su2double[nVertex_Wall]; /*--- Copy the boundary information to an array ---*/ iVertex_Wall = 0; for (iMarker = 0; iMarker < config->GetnMarker_All(); iMarker++) if ((config->GetMarker_All_KindBC(iMarker) == HEAT_FLUX) || (config->GetMarker_All_KindBC(iMarker) == ISOTHERMAL) || (config->GetMarker_All_KindBC(iMarker) == EULER_WALL) ) for (iVertex = 0; iVertex < nVertex[iMarker]; iVertex++) { iPoint = vertex[iMarker][iVertex]->GetNode(); Xcoord[iVertex_Wall] = nodes->GetCoord(iPoint, 0); Ycoord[iVertex_Wall] = nodes->GetCoord(iPoint, 1); if (nDim==3) Zcoord[iVertex_Wall] = nodes->GetCoord(iPoint, 2); Face_Normal = vertex[iMarker][iVertex]->GetNormal(); FaceArea[iVertex_Wall] = fabs(Face_Normal[nDim-1]); iVertex_Wall ++; } //vector<su2double> XCoordList; vector<su2double>::iterator IterXCoordList; for (iVertex = 0; iVertex < nVertex_Wall; iVertex++) XCoordList.push_back(Xcoord[iVertex]); sort( XCoordList.begin(), XCoordList.end()); IterXCoordList = unique( XCoordList.begin(), XCoordList.end()); XCoordList.resize( IterXCoordList - XCoordList.begin() ); /*--- Create vectors and distribute the values among the different PhiAngle queues ---*/ Xcoord_plane.resize(XCoordList.size()); Ycoord_plane.resize(XCoordList.size()); if (nDim==3) Zcoord_plane.resize(XCoordList.size()); FaceArea_plane.resize(XCoordList.size()); Plane_points.resize(XCoordList.size()); su2double dist_ratio; unsigned long iCoord; /*--- Distribute the values among the different PhiAngles ---*/ for (iPoint = 0; iPoint < nPoint; iPoint++) { if (nodes->GetDomain(iPoint)) { loop_on = true; for (ixCoord = 0; ixCoord < XCoordList.size()-1 && loop_on; ixCoord++) { dist_ratio = (nodes->GetCoord(iPoint, 0) - XCoordList[ixCoord])/(XCoordList[ixCoord+1]- XCoordList[ixCoord]); if (dist_ratio >= 0 && dist_ratio <= 1.0) { if (dist_ratio <= 0.5) iCoord = ixCoord; else iCoord = ixCoord+1; Xcoord_plane[iCoord].push_back(nodes->GetCoord(iPoint, 0) ); Ycoord_plane[iCoord].push_back(nodes->GetCoord(iPoint, 1) ); if (nDim==3) Zcoord_plane[iCoord].push_back(nodes->GetCoord(iPoint, 2) ); FaceArea_plane[iCoord].push_back(nodes->GetVolume(iPoint)); ///// CHECK AREA CALCULATION Plane_points[iCoord].push_back(iPoint ); loop_on = false; } } } } /*--- Order the arrays in ascending values of y ---*/ /// TODO: Depending on the size of the arrays, this may not be a good way of sorting them. for (ixCoord = 0; ixCoord < XCoordList.size(); ixCoord++) for (iVertex = 0; iVertex < Xcoord_plane[ixCoord].size(); iVertex++) for (jVertex = 0; jVertex < Xcoord_plane[ixCoord].size() - 1 - iVertex; jVertex++) if (Ycoord_plane[ixCoord][jVertex] > Ycoord_plane[ixCoord][jVertex+1]) { swap(Xcoord_plane[ixCoord][jVertex], Xcoord_plane[ixCoord][jVertex+1]); swap(Ycoord_plane[ixCoord][jVertex], Ycoord_plane[ixCoord][jVertex+1]); if (nDim==3) swap(Zcoord_plane[ixCoord][jVertex], Zcoord_plane[ixCoord][jVertex+1]); swap(Plane_points[ixCoord][jVertex], Plane_points[ixCoord][jVertex+1]); swap(FaceArea_plane[ixCoord][jVertex], FaceArea_plane[ixCoord][jVertex+1]); } /*--- Delete structures ---*/ delete[] Xcoord; delete[] Ycoord; delete[] Zcoord; delete[] FaceArea; } void CGeometry::SetRotationalVelocity(CConfig *config, bool print) { unsigned long iPoint; unsigned short iDim; su2double RotVel[3] = {0.0,0.0,0.0}, Distance[3] = {0.0,0.0,0.0}, Center[3] = {0.0,0.0,0.0}, Omega[3] = {0.0,0.0,0.0}; /*--- Center of rotation & angular velocity vector from config ---*/ for (iDim = 0; iDim < 3; iDim++) { Center[iDim] = config->GetMotion_Origin(iDim); Omega[iDim] = config->GetRotation_Rate(iDim)/config->GetOmega_Ref(); } su2double L_Ref = config->GetLength_Ref(); /*--- Print some information to the console ---*/ if (rank == MASTER_NODE && print) { cout << " Rotational origin (x, y, z): ( " << Center[0] << ", " << Center[1]; cout << ", " << Center[2] << " )\n"; cout << " Angular velocity about x, y, z axes: ( " << Omega[0] << ", "; cout << Omega[1] << ", " << Omega[2] << " ) rad/s" << endl; } /*--- Loop over all nodes and set the rotational velocity ---*/ for (iPoint = 0; iPoint < nPoint; iPoint++) { /*--- Get the coordinates of the current node ---*/ const su2double* Coord = nodes->GetCoord(iPoint); /*--- Calculate the non-dim. distance from the rotation center ---*/ for (iDim = 0; iDim < nDim; iDim++) Distance[iDim] = (Coord[iDim]-Center[iDim])/L_Ref; /*--- Calculate the angular velocity as omega X r ---*/ RotVel[0] = Omega[1]*(Distance[2]) - Omega[2]*(Distance[1]); RotVel[1] = Omega[2]*(Distance[0]) - Omega[0]*(Distance[2]); RotVel[2] = Omega[0]*(Distance[1]) - Omega[1]*(Distance[0]); /*--- Store the grid velocity at this node ---*/ nodes->SetGridVel(iPoint, RotVel); } } void CGeometry::SetShroudVelocity(CConfig *config) { unsigned long iPoint, iVertex; unsigned short iMarker, iMarkerShroud; su2double RotVel[3] = {0.0,0.0,0.0}; /*--- Loop over all vertex in the shroud marker and set the rotational velocity to 0.0 ---*/ for (iMarker = 0; iMarker < nMarker; iMarker++){ for(iMarkerShroud=0; iMarkerShroud < config->GetnMarker_Shroud(); iMarkerShroud++){ if(config->GetMarker_Shroud(iMarkerShroud) == config->GetMarker_All_TagBound(iMarker)){ for (iVertex = 0; iVertex < nVertex[iMarker]; iVertex++) { iPoint = vertex[iMarker][iVertex]->GetNode(); nodes->SetGridVel(iPoint, RotVel); } } } } } void CGeometry::SetTranslationalVelocity(CConfig *config, bool print) { su2double xDot[3] = {0.0,0.0,0.0}; /*--- Get the translational velocity vector from config ---*/ for (unsigned short iDim = 0; iDim < nDim; iDim++) xDot[iDim] = config->GetTranslation_Rate(iDim)/config->GetVelocity_Ref(); /*--- Print some information to the console ---*/ if (rank == MASTER_NODE && print) { cout << " Non-dim. translational velocity: (" << xDot[0] << ", " << xDot[1] << ", " << xDot[2] << ")." << endl; } /*--- Loop over all nodes and set the translational velocity ---*/ for (unsigned long iPoint = 0; iPoint < nPoint; iPoint++) nodes->SetGridVel(iPoint, xDot); } void CGeometry::SetGridVelocity(CConfig *config, unsigned long iter) { /*--- Get timestep and whether to use 1st or 2nd order backward finite differences ---*/ bool FirstOrder = (config->GetTime_Marching() == DT_STEPPING_1ST); bool SecondOrder = (config->GetTime_Marching() == DT_STEPPING_2ND); su2double TimeStep = config->GetDelta_UnstTimeND(); /*--- Compute the velocity of each node in the volume mesh ---*/ for (unsigned long iPoint = 0; iPoint < nPoint; iPoint++) { /*--- Coordinates of the current point at n+1, n, & n-1 time levels ---*/ const su2double *Coord_nM1 = nodes->GetCoord_n1(iPoint); const su2double *Coord_n = nodes->GetCoord_n(iPoint); const su2double *Coord_nP1 = nodes->GetCoord(iPoint); /*--- Compute and store mesh velocity with 1st or 2nd-order approximation ---*/ for (unsigned short iDim = 0; iDim < nDim; iDim++) { su2double GridVel = 0.0; if (FirstOrder) GridVel = (Coord_nP1[iDim] - Coord_n[iDim]) / TimeStep; if (SecondOrder) GridVel = (1.5*Coord_nP1[iDim] - 2.0*Coord_n[iDim] + 0.5*Coord_nM1[iDim]) / TimeStep; nodes->SetGridVel(iPoint, iDim, GridVel); } } } const CCompressedSparsePatternUL& CGeometry::GetSparsePattern(ConnectivityType type, unsigned long fillLvl) { bool fvm = (type == ConnectivityType::FiniteVolume); CCompressedSparsePatternUL* pattern = nullptr; if (fillLvl == 0) pattern = fvm? &finiteVolumeCSRFill0 : &finiteElementCSRFill0; else pattern = fvm? &finiteVolumeCSRFillN : &finiteElementCSRFillN; if (pattern->empty()) { *pattern = buildCSRPattern(*this, type, fillLvl); pattern->buildDiagPtr(); } return *pattern; } const CEdgeToNonZeroMapUL& CGeometry::GetEdgeToSparsePatternMap(void) { if (edgeToCSRMap.empty()) { if (finiteVolumeCSRFill0.empty()) { finiteVolumeCSRFill0 = buildCSRPattern(*this, ConnectivityType::FiniteVolume, 0ul); } edgeToCSRMap = mapEdgesToSparsePattern(*this, finiteVolumeCSRFill0); } return edgeToCSRMap; } const su2vector<unsigned long>& CGeometry::GetTransposeSparsePatternMap(ConnectivityType type) { /*--- Yes the const cast is weird but it is still better than repeating code. ---*/ auto& pattern = const_cast<CCompressedSparsePatternUL&>(GetSparsePattern(type)); pattern.buildTransposePtr(); return pattern.transposePtr(); } const CCompressedSparsePatternUL& CGeometry::GetEdgeColoring(su2double* efficiency) { /*--- Check for dry run mode with dummy geometry. ---*/ if (nEdge==0) return edgeColoring; /*--- Build if required. ---*/ if (edgeColoring.empty()) { /*--- When not using threading use the natural coloring to reduce overhead. ---*/ if (omp_get_max_threads() == 1) { SetNaturalEdgeColoring(); if (efficiency != nullptr) *efficiency = 1.0; // by definition return edgeColoring; } /*--- Create a temporary sparse pattern from the edges. ---*/ su2vector<unsigned long> outerPtr(nEdge+1); su2vector<unsigned long> innerIdx(nEdge*2); for (unsigned long iEdge = 0; iEdge < nEdge; ++iEdge) { outerPtr(iEdge) = 2*iEdge; innerIdx(iEdge*2+0) = edges->GetNode(iEdge,0); innerIdx(iEdge*2+1) = edges->GetNode(iEdge,1); } outerPtr(nEdge) = 2*nEdge; CCompressedSparsePatternUL pattern(move(outerPtr), move(innerIdx)); /*--- Color the edges. ---*/ constexpr bool balanceColors = true; edgeColoring = colorSparsePattern(pattern, edgeColorGroupSize, balanceColors); /*--- If the coloring fails use the natural coloring. This is a * "soft" failure as this "bad" coloring should be detected * downstream and a fallback strategy put in place. ---*/ if (edgeColoring.empty()) SetNaturalEdgeColoring(); } if (efficiency != nullptr) { *efficiency = coloringEfficiency(edgeColoring, omp_get_max_threads(), edgeColorGroupSize); } return edgeColoring; } void CGeometry::SetNaturalEdgeColoring() { if (nEdge == 0) return; edgeColoring = createNaturalColoring(nEdge); /*--- In parallel, set the group size to nEdge to protect client code. ---*/ if (omp_get_max_threads() > 1) edgeColorGroupSize = nEdge; } const CCompressedSparsePatternUL& CGeometry::GetElementColoring(su2double* efficiency) { /*--- Check for dry run mode with dummy geometry. ---*/ if (nElem==0) return elemColoring; /*--- Build if required. ---*/ if (elemColoring.empty()) { /*--- When not using threading use the natural coloring. ---*/ if (omp_get_max_threads() == 1) { SetNaturalElementColoring(); if (efficiency != nullptr) *efficiency = 1.0; // by definition return elemColoring; } /*--- Create a temporary sparse pattern from the elements. ---*/ vector<unsigned long> outerPtr(nElem+1); vector<unsigned long> innerIdx; innerIdx.reserve(nElem); for (unsigned long iElem = 0; iElem < nElem; ++iElem) { outerPtr[iElem] = innerIdx.size(); for (unsigned short iNode = 0; iNode < elem[iElem]->GetnNodes(); ++iNode) { innerIdx.push_back(elem[iElem]->GetNode(iNode)); } } outerPtr[nElem] = innerIdx.size(); CCompressedSparsePatternUL pattern(outerPtr, innerIdx); /*--- Color the elements. ---*/ constexpr bool balanceColors = true; elemColoring = colorSparsePattern(pattern, elemColorGroupSize, balanceColors); /*--- Same as for the edge coloring. ---*/ if (elemColoring.empty()) SetNaturalElementColoring(); } if (efficiency != nullptr) { *efficiency = coloringEfficiency(elemColoring, omp_get_max_threads(), elemColorGroupSize); } return elemColoring; } void CGeometry::SetNaturalElementColoring() { if (nElem == 0) return; elemColoring = createNaturalColoring(nElem); /*--- In parallel, set the group size to nElem to protect client code. ---*/ if (omp_get_max_threads() > 1) elemColorGroupSize = nElem; } void CGeometry::ComputeWallDistance(const CConfig* const* config_container, CGeometry ****geometry_container){ int nZone = config_container[ZONE_0]->GetnZone(); bool allEmpty = true; vector<bool> wallDistanceNeeded(nZone, false); for (int iInst = 0; iInst < config_container[ZONE_0]->GetnTimeInstances(); iInst++){ for (int iZone = 0; iZone < nZone; iZone++){ /*--- Check if a zone needs the wall distance and store a boolean ---*/ ENUM_MAIN_SOLVER kindSolver = static_cast<ENUM_MAIN_SOLVER>(config_container[iZone]->GetKind_Solver()); if (kindSolver == RANS || kindSolver == INC_RANS || kindSolver == DISC_ADJ_RANS || kindSolver == DISC_ADJ_INC_RANS || kindSolver == FEM_LES || kindSolver == FEM_RANS){ wallDistanceNeeded[iZone] = true; } /*--- Set the wall distances in all zones to the numerical limit. * This is necessary, because before a computed distance is set, it will be checked * whether the new distance is smaller than the currently stored one. ---*/ CGeometry *geometry = geometry_container[iZone][iInst][MESH_0]; if (wallDistanceNeeded[iZone]) geometry->SetWallDistance(numeric_limits<su2double>::max()); } /*--- Loop over all zones and compute the ADT based on the viscous walls in that zone ---*/ for (int iZone = 0; iZone < nZone; iZone++){ CGeometry *geometry = geometry_container[iZone][iInst][MESH_0]; unique_ptr<CADTElemClass> WallADT = geometry->ComputeViscousWallADT(config_container[iZone]); if (WallADT && !WallADT->IsEmpty()){ allEmpty = false; /*--- Inner loop over all zones to update the wall distances. * It might happen that there is a closer viscous wall in zone iZone for points in zone jZone. ---*/ for (int jZone = 0; jZone < nZone; jZone++){ if (wallDistanceNeeded[jZone]) geometry_container[jZone][iInst][MESH_0]->SetWallDistance(config_container[jZone], WallADT.get()); } } } /*--- If there are no viscous walls in the entire domain, set distances to zero ---*/ if (allEmpty){ for (int iZone = 0; iZone < nZone; iZone++){ CGeometry *geometry = geometry_container[iZone][iInst][MESH_0]; geometry->SetWallDistance(0.0); } } } }
37.565773
376
0.637786
Agony5757
95ff7e72f7b11e970e76d2b783dc427a2ee43bc7
2,409
cpp
C++
PrintMatrix.cpp
ChenliangLi205/NowCoder
44e79800b56410d1094f18fbb656fadf724b7b21
[ "MIT" ]
null
null
null
PrintMatrix.cpp
ChenliangLi205/NowCoder
44e79800b56410d1094f18fbb656fadf724b7b21
[ "MIT" ]
null
null
null
PrintMatrix.cpp
ChenliangLi205/NowCoder
44e79800b56410d1094f18fbb656fadf724b7b21
[ "MIT" ]
null
null
null
class Solution { public: vector<int> printMatrix(vector<vector<int> > matrix) { vector<int> res; int rows = matrix.size(); if(rows == 0) return res; int cols = matrix[0].size(); if(rows == 1) res = matrix[0]; else if(cols == 1) { for(vector<int> v : matrix) res.push_back(v[0]); } else { bool right=true,left=false, down=false,up=false; int curR=0, curC=0; int rowLen = cols-1; int colLen = rows-1; int cnt=0; while(res.size() < cols*rows) { res.push_back(matrix[curR][curC]); if(rowLen<=0) { curC++; continue; } if(colLen<=0) { curC++; continue; } if(right) { cnt++; if(cnt==rowLen) { right=false; down=true; cnt = 0; } curC++; continue; } if(down) { cnt++; if(cnt==colLen) { down=false; left=true; cnt=0; } curR++; continue; } if(left) { cnt++; if(cnt==rowLen) { left=false; up = true; cnt=0; } curC--; continue; } if(up) { cnt++; if(cnt==colLen) { up=false; right=true; cnt=0; curC++; colLen -= 2; rowLen -= 2; } else curR--; continue; } } } return res; } };
27.067416
60
0.249896
ChenliangLi205
2509df06c17514df361233d4520819d0ffde9a5d
3,833
cpp
C++
mount_player/mount_player/mount_player/coordinate_computation.cpp
lfyos/MountPlayer
0794bc24e3ff0ba1a85492708c8530b6d5fb70d2
[ "MIT" ]
3
2019-03-09T05:08:53.000Z
2019-04-01T23:37:28.000Z
mount_player/mount_player/mount_player/coordinate_computation.cpp
lfyos/MountPlayer
0794bc24e3ff0ba1a85492708c8530b6d5fb70d2
[ "MIT" ]
null
null
null
mount_player/mount_player/mount_player/coordinate_computation.cpp
lfyos/MountPlayer
0794bc24e3ff0ba1a85492708c8530b6d5fb70d2
[ "MIT" ]
null
null
null
#include "StdAfx.h" #include "coordinate_computation.h" #include "const.h" #include <math.h> coordinate_computation::coordinate_computation(void) { } coordinate_computation::~coordinate_computation(void) { } void coordinate_computation::load_identity_matrix(double a[4][4]) { int i,j; for(i=0;i<4;i++){ for(j=0;j<4;j++) a[i][j]=0; a[i][i]=1; } return; } void coordinate_computation::multiply_array(double a[4][4], double b[4][4], double c[4][4]) { int i,j,k; double my_a[4][4],my_b[4][4]; for(i=0;i<4;i++) for(j=0;j<4;j++){ my_a[i][j]=a[i][j]; my_b[i][j]=b[i][j]; } for(i=0;i<4;i++) for(j=0;j<4;j++) for(c[i][j]=0,k=0;k<4;k++) c[i][j]+=my_a[i][k]*my_b[k][j]; return; } void coordinate_computation::reset_move_array(double a[4][4],double dx,double dy,double dz) { load_identity_matrix(a); a[0][3]=dx; a[1][3]=dy; a[2][3]=dz; } void coordinate_computation::reset_x_rotate_array(double a[4][4],double rx) { load_identity_matrix(a); a[1][1]=cosl(rx*PI/180); a[2][1]=sinl(rx*PI/180); a[1][2]=(-a[2][1]); a[2][2]=a[1][1]; } void coordinate_computation::reset_y_rotate_array(double a[4][4], double ry) { load_identity_matrix(a); a[0][0]=cosl(ry*PI/180); a[0][2]=sinl(ry*PI/180); a[2][0]=(-a[0][2]); a[2][2]=a[0][0]; } void coordinate_computation::reset_z_rotate_array(double a[4][4], double rz) { load_identity_matrix(a); a[0][0]=cosl(rz*PI/180); a[1][0]=sinl(rz*PI/180); a[0][1]=(-a[1][0]); a[1][1]=a[0][0]; } void coordinate_computation::get_array(double a[], double dx , double dy , double dz , double rx , double ry , double rz) { double x[4][4],y[4][4]; load_identity_matrix(y); reset_x_rotate_array(x,rx); multiply_array(x,y,y); reset_y_rotate_array(x,ry); multiply_array(x,y,y); reset_z_rotate_array(x,rz); multiply_array(x,y,y); reset_move_array(x,dx,dy,dz); multiply_array(x,y,y); change_4_4_to_16(y,a); } void coordinate_computation::load_identity_matrix(double a[]) { double b[4][4]; load_identity_matrix(b); change_4_4_to_16(b,a); } void coordinate_computation::change_4_4_to_16(double a[4][4],double b[16]) { b[ 0]=a[ 0][ 0] ; b[ 1]=a[ 1][ 0] ; b[ 2]=a[ 2][ 0] ; b[ 3]=a[ 3][ 0] ; b[ 4]=a[ 0][ 1] ; b[ 5]=a[ 1][ 1] ; b[ 6]=a[ 2][ 1] ; b[ 7]=a[ 3][ 1] ; b[ 8]=a[ 0][ 2] ; b[ 9]=a[ 1][ 2] ; b[10]=a[ 2][ 2] ; b[11]=a[ 3][ 2] ; b[12]=a[ 0][ 3] ; b[13]=a[ 1][ 3] ; b[14]=a[ 2][ 3] ; b[15]=a[ 3][ 3] ; } void coordinate_computation::change_16_to_4_4(double a[16],double b[4][4]) { b[ 0][ 0]=a[ 0]; b[ 1][ 0]=a[ 1]; b[ 2][ 0]=a[ 2]; b[ 3][ 0]=a[ 3]; b[ 0][ 1]=a[ 4]; b[ 1][ 1]=a[ 5]; b[ 2][ 1]=a[ 6]; b[ 3][ 1]=a[ 7]; b[ 0][ 2]=a[ 8]; b[ 1][ 2]=a[ 9]; b[ 2][ 2]=a[10]; b[ 3][ 2]=a[11]; b[ 0][ 3]=a[12]; b[ 1][ 3]=a[13]; b[ 2][ 3]=a[14]; b[ 3][ 3]=a[15]; } void coordinate_computation::caculate_relative_location(double my_parent_location[], double my_location[], double my_relative_location[]) { int i,j,k; double a[4][4],b[4][4],c[4][4],p,x; change_16_to_4_4(my_parent_location,a); change_16_to_4_4(my_location,b); load_identity_matrix(c); for(i=0;i<3;i++){ for(k=i,j=i+1;j<4;j++) if(fabs((float)(a[j][i]))>fabs((float)(a[k][i]))) k=j; for(j=0;j<4;j++){ x=a[i][j]; a[i][j]=a[k][j]; a[k][j]=x; x=c[i][j]; c[i][j]=c[k][j]; c[k][j]=x; } for(j=i+1;j<4;j++){ p=a[j][i]/a[i][i]; for(k=i+1;k<4;k++) a[j][k]-=p*a[i][k]; for(k=0;k<4;k++) c[j][k]-=p*c[i][k]; } } for(i=3;i>0;i--) for(j=0;j<i;j++){ p=a[j][i]/a[i][i]; for(k=0;k<4;k++) c[j][k]-=p*c[i][k]; for(k=i+1;k<4;k++) a[j][k]-=p*a[i][k]; } for(i=0;i<4;i++) for(j=0;j<4;j++) c[i][j]/=a[i][i]; for(i=0;i<4;i++) for(j=0;j<4;j++){ a[i][j]=0; for(k=0;k<4;k++) a[i][j]+=c[i][k]*b[k][j]; } change_4_4_to_16(a,my_relative_location); return; }
19.456853
137
0.55257
lfyos
2513c6bce9ce1265c00e2b3aff8c3ca474f3801d
12,489
cpp
C++
Source/SystemQOR/MSWindows/WinCmpSupQORVC/src/ulldvrm.cpp
mfaithfull/QOR
0fa51789344da482e8c2726309265d56e7271971
[ "BSL-1.0" ]
9
2016-05-27T01:00:39.000Z
2021-04-01T08:54:46.000Z
Source/SystemQOR/MSWindows/WinCmpSupQORVC/src/ulldvrm.cpp
mfaithfull/QOR
0fa51789344da482e8c2726309265d56e7271971
[ "BSL-1.0" ]
1
2016-03-03T22:54:08.000Z
2016-03-03T22:54:08.000Z
Source/SystemQOR/MSWindows/WinCmpSupQORVC/src/ulldvrm.cpp
mfaithfull/QOR
0fa51789344da482e8c2726309265d56e7271971
[ "BSL-1.0" ]
4
2016-05-27T01:00:43.000Z
2018-08-19T08:47:49.000Z
//ulldvrm.cpp // Copyright Querysoft Limited 2013 // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. #include "CompilerQOR.h" #include "CodeQOR/Macros/CodingMacros.h" #include "ArchQOR/Common/Machine.h" #include "ArchQOR/Common/HLAssembler/JITFunctor.h" //To generate assembler function for aulldvrm - unsigned long division with remainder //------------------------------------------------------------------------------ class CJITaulldvrm : public nsArch::CJITFunctor0< int > { public: //------------------------------------------------------------------------------ CJITaulldvrm( nsArch::CHighLevelAssemblerBase* pHLA, byte* pLaunchPad = 0 ) : CJITFunctor0(pHLA, pLaunchPad) { if (m_pLaunchPad != 0) { Generate(); } } protected: //------------------------------------------------------------------------------ virtual FP Generate() { nsArch::nsx86::Cx86HLAIntrinsics& HLA = (*(dynamic_cast< nsArch::nsx86::Cx86HLAIntrinsics* >(m_pHLA))); nsArch::nsx86::CCPU& CPU = *(dynamic_cast< nsArch::nsx86::CCPU* >(HLA.getAssembler())); CPU.clear(); nsArch::nsx86::CLabel Label1 = CPU.newLabel(); nsArch::nsx86::CLabel Label2 = CPU.newLabel(); nsArch::nsx86::CLabel Label3 = CPU.newLabel(); nsArch::nsx86::CLabel Label4 = CPU.newLabel(); nsArch::nsx86::CLabel Label5 = CPU.newLabel(); /* ; Purpose: ; Does a unsigned long divide and remainder of the arguments. Arguments ; are not changed. ; ; Entry: ; Arguments are passed on the stack: ; 1st pushed: divisor (QWORD) ; 2nd pushed: dividend (QWORD) ; ; Exit: ; EDX:EAX contains the quotient (dividend/divisor) ; EBX:ECX contains the remainder (divided % divisor) ; NOTE: this routine removes the parameters from the stack. ; ; Uses: ; ECX */ //push esi CPU.push(CPU.reg_esi()); /* ; Set up the local stack and save the index registers. When this is done ; the stack frame will look as follows (assuming that the expression a/b will ; generate a call to aulldvrm(a, b)): ; ; ----------------- ; | | ; |---------------| ; | | ; |--divisor (b)--| ; | | ; |---------------| ; | | ; |--dividend (a)-| ; | | ; |---------------| ; | return addr** | ; |---------------| ; ESP---->| ESI | ; ----------------- */ //DVND equ [esp + 8] ; stack address of dividend (a) nsArch::nsx86::CMem Dividend(CPU.reg_esp(), 4); //stack address of dividend (a) nsArch::nsx86::CMem HiWordDividend(CPU.reg_esp(), 8); //DVSR equ [esp + 16] ; stack address of divisor (b) nsArch::nsx86::CMem Divisor(CPU.reg_esp(), 12); //stack address of divisor (b) nsArch::nsx86::CMem HiWordDivisor(CPU.reg_esp(), 16); /* ; Now do the divide. First look to see if the divisor is less than 4194304K. ; If so, then we can use a simple algorithm with word divides, otherwise ; things get a little more complex. */ //mov eax,HIWORD(DVSR) ; check to see if divisor < 4194304K CPU.mov(CPU.reg_eax(), HiWordDivisor); //check to see if divisor < 4194304K //or eax,eax CPU.or_(CPU.reg_eax(), CPU.reg_eax()); //jnz short L1 ; nope, gotta do this the hard way CPU.short_jnz(Label1); //nope, gotta do this the hard way //mov ecx,LOWORD(DVSR) ; load divisor CPU.mov(CPU.reg_ecx(), Divisor); //load divisor //mov eax,HIWORD(DVND) ; load high word of dividend CPU.mov(CPU.reg_eax(), HiWordDividend); //load high word of dividend //xor edx,edx CPU.xor_(CPU.reg_edx(), CPU.reg_edx()); //div ecx ; get high order bits of quotient CPU.div(CPU.reg_ecx()); //get high order bits of quotient //mov ebx,eax ; save high bits of quotient CPU.mov(CPU.reg_ebx(), CPU.reg_eax()); //save high bits of quotient //mov eax,LOWORD(DVND) ; edx:eax <- remainder:lo word of dividend CPU.mov(CPU.reg_eax(), Dividend); //edx:eax <- remainder:lo word of dividend //div ecx ; get low order bits of quotient CPU.div(CPU.reg_ecx()); //get low order bits of quotient //mov esi,eax ; ebx:esi <- quotient CPU.mov(CPU.reg_esi(), CPU.reg_eax()); //ebx:esi <- quotient /* ; Now we need to do a multiply so that we can compute the remainder. */ //mov eax,ebx ; set up high word of quotient CPU.mov(CPU.reg_eax(), CPU.reg_ebx()); //set up high word of quotient //mul dword ptr LOWORD(DVSR) ; HIWORD(QUOT) * DVSR CPU.mul(Divisor); //HIWORD(QUOT) * DVSR //mov ecx,eax ; save the result in ecx CPU.mov(CPU.reg_ecx(), CPU.reg_eax()); //save the result in ecx //mov eax,esi ; set up low word of quotient CPU.mov(CPU.reg_eax(), CPU.reg_eax()); //set up low word of quotient //mul dword ptr LOWORD(DVSR) ; LOWORD(QUOT) * DVSR CPU.mul(Divisor); //LOWORD(QUOT) * DVSR //add edx,ecx ; EDX:EAX = QUOT * DVSR CPU.add(CPU.reg_edx(), CPU.reg_ecx()); //EDX:EAX = QUOT * DVSR //jmp short L2 ; complete remainder calculation CPU.short_jmp(Label2); //complete remainder calculation /* ; Here we do it the hard way. Remember, eax contains DVSRHI */ //L1: CPU.bind(Label1); //mov ecx,eax ; ecx:ebx <- divisor CPU.mov(CPU.reg_ecx(), CPU.reg_eax()); //ecx:ebx <- divisor //mov ebx,LOWORD(DVSR) CPU.mov(CPU.reg_ebx(), Divisor); //mov edx,HIWORD(DVND) ; edx:eax <- dividend CPU.mov(CPU.reg_edx(), HiWordDividend); //edx:eax <- dividend //mov eax,LOWORD(DVND) CPU.mov(CPU.reg_eax(), Dividend); //L3: CPU.bind(Label3); //shr ecx,1 ; shift divisor right one bit; hi bit <- 0 CPU.shr(CPU.reg_ecx(), nsArch::nsx86::CImm(1)); //shift divisor right one bit; hi bit <- 0 //rcr ebx,1 CPU.rcr(CPU.reg_ebx(), nsArch::nsx86::CImm(1)); //shr edx,1 ; shift dividend right one bit; hi bit <- 0 CPU.shr(CPU.reg_edx(), nsArch::nsx86::CImm(1)); //shift dividend right one bit; hi bit <- 0 //rcr eax,1 CPU.rcr(CPU.reg_eax(), nsArch::nsx86::CImm(1)); //or ecx,ecx CPU.or_(CPU.reg_ecx(), CPU.reg_ecx()); //jnz short L3 ; loop until divisor < 4194304K CPU.short_jnz(Label3); //loop until divisor < 4194304K //div ebx ; now divide, ignore remainder CPU.div(CPU.reg_ebx()); //now divide, ignore remainder //mov esi,eax ; save quotient CPU.mov(CPU.reg_esi(), CPU.reg_eax()); // save quotient /* ; We may be off by one, so to check, we will multiply the quotient ; by the divisor and check the result against the orignal dividend ; Note that we must also check for overflow, which can occur if the ; dividend is close to 2**64 and the quotient is off by 1. */ //mul dword ptr HIWORD(DVSR) ; QUOT * HIWORD(DVSR) CPU.mul(HiWordDivisor); //QUOT * HIWORD(DVSR) //mov ecx,eax CPU.mov(CPU.reg_ecx(), CPU.reg_eax()); //mov eax,LOWORD(DVSR) CPU.mov(CPU.reg_eax(), Divisor); //mul esi ; QUOT * LOWORD(DVSR) CPU.mul(CPU.reg_esi()); //QUOT * LOWORD(DVSR) //add edx,ecx ; EDX:EAX = QUOT * DVSR CPU.add(CPU.reg_edx(), CPU.reg_ecx()); //EDX:EAX = QUOT * DVSR //jc short L4 ; carry means Quotient is off by 1 CPU.short_jc(Label4); //carry means Quotient is off by 1 /* ; do long compare here between original dividend and the result of the ; multiply in edx:eax. If original is larger or equal, we are ok, otherwise ; subtract one (1) from the quotient. */ //cmp edx, HIWORD(DVND); compare hi words of result and original CPU.cmp(CPU.reg_edx(), HiWordDividend); //compare hi words of result and original //ja short L4; if result > original, do subtract CPU.short_ja(Label4); //if result > original, do subtract //jb short L5; if result < original, we are ok CPU.short_jb(Label5); //if result < original, we are ok //cmp eax, LOWORD(DVND); hi words are equal, compare lo words CPU.cmp(CPU.reg_eax(), Dividend); //hi words are equal, compare lo words //jbe short L5; if less or equal we are ok, else subtract CPU.short_jbe(Label5); //if less or equal we are ok, else subtract //L4: CPU.bind(Label4); //dec esi; subtract 1 from quotient CPU.dec(CPU.reg_esi()); //subtract 1 from quotient //sub eax, LOWORD(DVSR); subtract divisor from result CPU.sub(CPU.reg_eax(), Divisor); //subtract divisor from result //sbb edx, HIWORD(DVSR) CPU.sbb(CPU.reg_edx(), HiWordDivisor); //L5: CPU.bind(Label5); //xor ebx, ebx; ebx:esi < -quotient CPU.xor_(CPU.reg_ebx(), CPU.reg_ebx()); //ebx:esi < -quotient //L2: CPU.bind(Label2); /* ; Calculate remainder by subtracting the result from the original dividend. ; Since the result is already in a register, we will do the subtract in the ; opposite direction and negate the result. */ //sub eax,LOWORD(DVND) ; subtract dividend from result CPU.sub(CPU.reg_eax(), Dividend); //subtract dividend from result //sbb edx,HIWORD(DVND) CPU.sbb(CPU.reg_edx(), HiWordDividend); //neg edx ; otherwise, negate the result CPU.neg(CPU.reg_edx()); //otherwise, negate the result //neg eax CPU.neg(CPU.reg_eax()); //sbb edx,0 CPU.sbb(CPU.reg_edx(), nsArch::nsx86::CImm(0)); /* ; Now we need to get the quotient into edx:eax and the remainder into ebx:ecx. */ //mov ecx,edx CPU.mov(CPU.reg_ecx(), CPU.reg_edx()); //mov edx,ebx CPU.mov(CPU.reg_edx(), CPU.reg_ebx()); //mov ebx,ecx CPU.mov(CPU.reg_ebx(), CPU.reg_ecx()); //mov ecx,eax CPU.mov(CPU.reg_ecx(), CPU.reg_eax()); //mov eax,esi CPU.mov(CPU.reg_eax(), CPU.reg_esi()); /* ; Just the cleanup left to do. edx:eax contains the quotient. ; Restore the saved registers and return. */ //pop esi CPU.pop(CPU.reg_esi()); //ret 16 CPU.ret(nsArch::nsx86::CImm(16)); // Make JIT function. FP fn = reinterpret_cast< FP >(CPU.make()); // Ensure that everything is ok and write the launchpad if (fn) { m_bGenerated = true; if (m_pLaunchPad) { HLA.WriteLaunchPad((byte*)fn, m_pLaunchPad); } } return fn; } }; __QCMP_STARTLINKAGE_C #pragma section( ".jit", execute ) __declspec(allocate(".jit")) byte _aulldvrm[16]; #pragma comment( linker, "/SECTION:.jit,ERW" ) __QCMP_ENDLINKAGE_C CJITaulldvrm aulldvrmJIT( &TheMachine()->HLAssembler(), _aulldvrm );
39.15047
109
0.5906
mfaithfull
2513e990c0a56640bc12914d583c06513f6e380f
446
cpp
C++
Sail/src/Sail/api/Texture.cpp
h3nx/Sail
96c13ee50bf9666c01bb8bb263e0c2dc3ba0eff9
[ "MIT" ]
null
null
null
Sail/src/Sail/api/Texture.cpp
h3nx/Sail
96c13ee50bf9666c01bb8bb263e0c2dc3ba0eff9
[ "MIT" ]
null
null
null
Sail/src/Sail/api/Texture.cpp
h3nx/Sail
96c13ee50bf9666c01bb8bb263e0c2dc3ba0eff9
[ "MIT" ]
null
null
null
#include "pch.h" #include "Texture.h" #include "Sail/Application.h" TextureData& Texture::getTextureData(const std::string& filename) const { // Load the texture file it if is not loaded already if (!Application::getInstance()->getResourceManager().hasTextureData(filename)) { Application::getInstance()->getResourceManager().loadTextureData(filename); } return Application::getInstance()->getResourceManager().getTextureData(filename); }
37.166667
82
0.769058
h3nx
2515be69b299f6f6b98eedf7725a8f640ed4b63a
1,184
hpp
C++
src/sha2.hpp
PaulLaux/X3DH-Key-Exchange
a1ad953dc67f89e7321d790b6ea563baec0b2d7a
[ "BSD-2-Clause" ]
35
2017-03-14T09:39:18.000Z
2021-03-15T09:44:59.000Z
src/sha2.hpp
bernedogit/amber
abfa22a048571e36a68a7c3bbbabbb291a2ceb7d
[ "BSD-2-Clause" ]
null
null
null
src/sha2.hpp
bernedogit/amber
abfa22a048571e36a68a7c3bbbabbb291a2ceb7d
[ "BSD-2-Clause" ]
1
2021-12-09T08:31:07.000Z
2021-12-09T08:31:07.000Z
#ifndef AMBER_SHA2_HPP #define AMBER_SHA2_HPP #include "soname.hpp" #include <stdint.h> #include <stddef.h> namespace amber { namespace AMBER_SONAME { class EXPORTFN Sha256 { enum { blocklen1 = 64 }; size_t tot_len; size_t len; uint8_t block [2 * blocklen1]; uint32_t h[8]; void transform (const uint8_t *message, size_t block_nb); public: enum { blocklen = blocklen1, hashlen = 32 }; Sha256 () { reset(); } void reset (); void update (const void *bytes, size_t nbytes); // Produce a 32 byte digest. void final (uint8_t digest[32]); }; EXPORTFN void sha256 (const void *message, size_t len, uint8_t digest[32]); class EXPORTFN Sha512 { enum { blocklen1 = 128 }; size_t tot_len; size_t len; unsigned char block [2 * blocklen1]; uint64_t h[8]; void transform (const uint8_t *message, size_t block_nb); public: enum { blocklen = blocklen1, hashlen = 64 }; Sha512 () { reset(); } void reset (); void update (const void *bytes, size_t nbytes); // Produce a 64 byte digest. void final (uint8_t digest[64]); }; EXPORTFN void sha512 (const void *message, size_t len, uint8_t digest[64]); }} #endif
17.671642
66
0.663851
PaulLaux
251f732c78a3f0b0a8ddc954d3a45955484a9198
1,579
cpp
C++
code07/counting-sequences.cpp
Feynman1999/Number-Theory-in-Programming-Competition
a7d48c80acb3ff916eca708e82ee7321f98a2d12
[ "MIT" ]
12
2019-09-02T06:18:23.000Z
2022-03-11T14:30:24.000Z
code07/counting-sequences.cpp
Feynman1999/Number-Theory-in-Programming-Competition
a7d48c80acb3ff916eca708e82ee7321f98a2d12
[ "MIT" ]
2
2019-09-03T06:50:53.000Z
2020-07-03T08:38:56.000Z
code07/counting-sequences.cpp
Feynman1999/Number-Theory-in-Programming-Competition
a7d48c80acb3ff916eca708e82ee7321f98a2d12
[ "MIT" ]
1
2020-07-19T11:24:44.000Z
2020-07-19T11:24:44.000Z
const int mod = 1e9+7; ll ans[3010]; ll help[3010]; ll helpni[3010]; stack<int> sta; int up = 3000; int n=3000; ll fast_exp(ll a,ll b,ll c){ ll res=1;a=a%c; while(b) { if(b&1) res=(res*a)%c; b>>=1;a=(a*a)%c; } return res; } void solve(int len) { int len2 = sta.size(); assert(len2>1); int len1 = len-len2; ll res = help[len]*helpni[len1]%mod; stack<int> sta_tp = sta; vector<int> vec; while(!sta_tp.empty()){ vec.push_back(sta_tp.top()); sta_tp.pop(); } vec.push_back(-1); int num=1; for(int i=1;i<vec.size();++i){ if(vec[i]==vec[i-1]) num++; else{ res = res*helpni[num]%mod; num=1; } } ans[len] = (ans[len] + res)%mod; } void dfs(int len, ll sum, ll jie) { ll tp = jie-sum+len;//tp为序列长度 if(tp<=n){ if(tp>=3){ //1的数量: jie-sum >1的数量: len //ans[tp]++; //取当前的sta 然后计算 solve(tp); } else ; } else return; int low; if(sta.empty()) low = 2; else low = sta.top(); for(int i=low;i<=up;++i){ sta.push(i); dfs(len+1, sum+i,jie*i); sta.pop(); } } void init() { help[1] = 1;helpni[1] = 1; for(int i=2;i<=3000;++i){ help[i] = help[i-1]*i%mod; helpni[i] = fast_exp(help[i], mod-2,mod); } } int main() { init(); dfs(0,0,1); int t; cin>>t; while(t--) { int m; cin>>m; if(m==2) cout<<1<<endl; else cout<<ans[m]<<endl; } }
18.576471
49
0.451552
Feynman1999
2524d56db42308ac3715616ea3b73e8cd4be9718
2,010
cpp
C++
image_manager/ImgManager.cpp
jugurthab/opensource-quest
793da3833e0a54c0ab16421e6a4f31ade1dc7b50
[ "MIT" ]
null
null
null
image_manager/ImgManager.cpp
jugurthab/opensource-quest
793da3833e0a54c0ab16421e6a4f31ade1dc7b50
[ "MIT" ]
null
null
null
image_manager/ImgManager.cpp
jugurthab/opensource-quest
793da3833e0a54c0ab16421e6a4f31ade1dc7b50
[ "MIT" ]
null
null
null
#include "ImgManager.h" ImgManager* ImgManager::imgManager = NULL; void ImgManager::loadImage(std::string imgFilename, std::string imageID){ SDL_Surface *tmpImg = NULL; SDL_Texture *ImgTexture = NULL; tmpImg = SDL_LoadBMP(imgFilename.c_str()); if(tmpImg==NULL){ fprintf(stderr, "Cannot Load Image %s\n", SDL_GetError()); exit(-1); } ImgTexture = SDL_CreateTextureFromSurface(SmileGameLogic::Instance()->getRenderer(),tmpImg); if(ImgTexture==NULL){ fprintf(stderr, "Cannot Create Texture from Image %s\n", SDL_GetError()); exit(-1); } SDL_FreeSurface(tmpImg); imgLoaded[imageID] = ImgTexture; } void ImgManager::drawImage(std::string imageID, int imgXPos, int imgYPos, int imgWidth, int imgHeight, SDL_RendererFlip flip){ SDL_Rect srcRect, destRect; srcRect.x = srcRect.y = 0; srcRect.w = destRect.w = imgWidth; srcRect.h = destRect.h = imgHeight; destRect.x = imgXPos; destRect.y = imgYPos; SDL_RenderCopyEx(SmileGameLogic::Instance()->getRenderer(), imgLoaded[imageID], &srcRect, &destRect, 0, 0, flip); } void ImgManager::drawSpriteAnimation(std::string imageID, int imgXPos, int imgYPos, int imgWidth, int imgHeight, int currentFrame, int currentRow, SDL_RendererFlip flip){ SDL_Rect srcRect, destRect; srcRect.x = currentFrame * imgWidth; srcRect.y = currentRow * imgHeight; srcRect.w = destRect.w = imgWidth; srcRect.h = destRect.h = imgHeight; destRect.x = imgXPos; destRect.y = imgYPos; SDL_RenderCopyEx(SmileGameLogic::Instance()->getRenderer(), imgLoaded[imageID], &srcRect, &destRect, 0, 0, flip); } void ImgManager::eraseImg(std::string imageID){ imgLoaded.erase(imageID); } void ImgManager::clearMapTextureObjects(){ for (std::map<std::string, SDL_Texture*>::iterator it = imgLoaded.begin() ; it != imgLoaded.end(); ++it) { SDL_DestroyTexture(it->second); imgLoaded.erase(it->first); } imgLoaded.clear(); }
30
170
0.682587
jugurthab
25276922670d2ce93cd9700599b1f6a544dad8e6
4,893
cpp
C++
mbed-glove-firmware/drivers/dot_star_leds.cpp
apadin1/Team-GLOVE
d5f5134da79d050164dffdfdf87f12504f6b1370
[ "Apache-2.0" ]
null
null
null
mbed-glove-firmware/drivers/dot_star_leds.cpp
apadin1/Team-GLOVE
d5f5134da79d050164dffdfdf87f12504f6b1370
[ "Apache-2.0" ]
null
null
null
mbed-glove-firmware/drivers/dot_star_leds.cpp
apadin1/Team-GLOVE
d5f5134da79d050164dffdfdf87f12504f6b1370
[ "Apache-2.0" ]
1
2019-01-09T05:16:42.000Z
2019-01-09T05:16:42.000Z
/* * Filename: dot_star_leds.cpp * Project: EECS 473 - Team GLOVE * Date: Fall 2016 * Authors: * Nick Bertoldi * Ben Heckathorn * Ryan O’Keefe * Adrian Padin * Tim Schumacher * * Purpose: * Implementation for interface to DotStar LEDs * and some helpful functions * * Copyright (c) 2016 by Nick Bertoldi, Ben Heckathorn, Ryan O'Keefe, * Adrian Padin, Timothy Schumacher * * 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 "dot_star_leds.h" DotStarLEDs::DotStarLEDs(uint8_t num_leds, PinName mosi, PinName miso, PinName sclk) : num_leds(num_leds), spi(mosi, miso, sclk) { // Setup the spi for 8 bit data, high steady state clock, // second edge capture, with a 8MHz clock rate spi.format(8,2); spi.frequency(8000000); // setup the leds buffer // contains the start and stop words // can still index as though it didn't have those leds = new uint32_t[num_leds + 2]; leds[0] = 0x00; leds[num_leds+1] = 0xFFFFFFFF; } void color_to_RGB(DotStarColor color, uint8_t& red, uint8_t& green, uint8_t& blue) { switch(color) { case(Red): red = 255; green = 0; blue = 0; break; case(Green): red = 0; green = 255; blue = 0; break; case(Blue): red = 0; green = 0; blue = 255; break; case(Orange): red = 255; green = 40; blue = 0; break; case(Yellow): red = 255; green = 230; blue = 0; break; case(Maize): red = 255; green = 170; blue = 0; break; case(Purple): red = 180; green = 0; blue = 255; break; case(Cyan): red = 0; green = 200; blue = 200; break; case(Magenta): red = 200; green = 0; blue = 200; break; case(Pink): red = 250; green = 40; blue = 40; break; case(Off): red = 0; green = 0; blue = 0; break; case(White): default: red = 200, green = 200, blue = 200; } } void DotStarLEDs::set_color(uint8_t led, DotStarColor color, uint8_t brightness) { uint8_t red, green, blue; color_to_RGB(color, red, green, blue); set_RGB(led, red, green, blue, brightness); } void DotStarLEDs::set_color_all(DotStarColor color, uint8_t brightness) { uint8_t red, green, blue; color_to_RGB(color, red, green, blue); set_RGB_all(red, green, blue, brightness); } void DotStarLEDs::set_RGB(uint8_t led, uint8_t red, uint8_t green, uint8_t blue, uint8_t brightness) { set_led_rgb(led, red, green, blue, brightness); flush_to_spi(); } void DotStarLEDs::set_RGB_all(uint8_t red, uint8_t green, uint8_t blue, uint8_t brightness) { for (uint8_t led = 0; led < num_leds; ++led) { set_led_rgb(led, red, green, blue, brightness); } flush_to_spi(); } void DotStarLEDs::set_led_rgb(uint8_t led, uint8_t red, uint8_t green, uint8_t blue, uint8_t brightness) { uint32_t new_led_val = ((0xE0 | brightness) << 24) | (blue << 16) | (green << 8) | red; if (leds[led+1] != new_led_val) { leds[led+1] = new_led_val; clean = false; } } void DotStarLEDs::flush_to_spi() { if (clean) { return; } clean = true; // for every 4-byte word in the buffer, write it uint32_t word; for (uint8_t i = 0; i < num_leds+2; ++i) { word = leds[i]; spi.write((word >> 24) & 0x000000FF); spi.write((word >> 16) & 0x000000FF); spi.write((word >> 8) & 0x000000FF); spi.write((word) & 0x000000FF); } } float map_unsigned_analog_to_percent(uint16_t min_, uint16_t max_, uint16_t val) { return (val - min_) / float(max_ - min_); } float map_float_analog_to_percent(float min_, float max_, float val) { return (val - min_) / float(max_ - min_); }
32.838926
91
0.631719
apadin1
2528847f7bc62f3a20fddbfd3a7c403817b85348
2,644
cpp
C++
test/bitmap_font_test.cpp
razielgn/leaf-green
b37252c9167f0a4661050c835a8b6a1863fb0cd3
[ "MIT" ]
2
2015-03-02T21:50:25.000Z
2016-05-28T00:18:47.000Z
test/bitmap_font_test.cpp
razielgn/leaf-green
b37252c9167f0a4661050c835a8b6a1863fb0cd3
[ "MIT" ]
null
null
null
test/bitmap_font_test.cpp
razielgn/leaf-green
b37252c9167f0a4661050c835a8b6a1863fb0cd3
[ "MIT" ]
null
null
null
#include "bitmap_font.hpp" #include "gmock/gmock.h" #include "graphics_mock.hpp" #include "texture_mock.hpp" namespace green_leaf { using namespace ::testing; class BitmapFontTest : public Test { protected: BitmapFontTest() { } std::unique_ptr<TextureMock> texture_ = std::make_unique<TextureMock>(Vector2(0, 0)); GraphicsMock graphics_; BitmapFont font_ = BitmapFont(std::move(texture_)); }; TEST_F(BitmapFontTest, DrawString) { EXPECT_CALL(graphics_, drawTexture(_, Vector2( 2, 2), Rectangle(106, 42, 6, 14))); // H EXPECT_CALL(graphics_, drawTexture(_, Vector2( 8, 2), Rectangle( 24, 56, 6, 14))); // e EXPECT_CALL(graphics_, drawTexture(_, Vector2(14, 2), Rectangle( 62, 56, 5, 14))); // l EXPECT_CALL(graphics_, drawTexture(_, Vector2(19, 2), Rectangle( 47, 56, 4, 14))); // i EXPECT_CALL(graphics_, drawTexture(_, Vector2(23, 2), Rectangle(144, 28, 4, 14))); // . EXPECT_CALL(graphics_, drawTexture(_, Vector2(33, 2), Rectangle(126, 28, 6, 14))); // 9 EXPECT_CALL(graphics_, drawTexture(_, Vector2(39, 2), Rectangle(132, 28, 6, 14))); // ! EXPECT_CALL(graphics_, drawTexture(_, Vector2(51, 2), Rectangle(112, 42, 6, 14))); // I EXPECT_CALL(graphics_, drawTexture(_, Vector2(57, 2), Rectangle(106, 56, 5, 14))); // t EXPECT_CALL(graphics_, drawTexture(_, Vector2(62, 2), Rectangle( 45, 51, 3, 10))); // ' EXPECT_CALL(graphics_, drawTexture(_, Vector2(65, 2), Rectangle(101, 56, 5, 14))); // s EXPECT_CALL(graphics_, drawTexture(_, Vector2(76, 2), Rectangle( 35, 56, 6, 14))); // g EXPECT_CALL(graphics_, drawTexture(_, Vector2(82, 2), Rectangle( 78, 56, 6, 14))); // o EXPECT_CALL(graphics_, drawTexture(_, Vector2(88, 2), Rectangle( 44, 42, 4, 14))); // , EXPECT_CALL(graphics_, drawTexture(_, Vector2(92, 2), Rectangle(111, 56, 6, 14))); // u EXPECT_EQ(98u, font_.drawString(graphics_, Vector2(2, 2), "Heli. 9! It's go,u")); } TEST_F(BitmapFontTest, DrawUtf8) { EXPECT_CALL(graphics_, drawTexture(_, Vector2(0, 0), Rectangle(183, 0, 6, 14))); // é EXPECT_CALL(graphics_, drawTexture(_, Vector2(6, 0), Rectangle( 0, 42, 6, 14))); // … EXPECT_EQ(12u, font_.drawString(graphics_, Vector2(0, 0), "é…")); } TEST_F(BitmapFontTest, DrawUtf8WithZeroChars) { EXPECT_CALL(graphics_, drawTexture(_, A<Vector2>(), _)).Times(0); EXPECT_EQ(0u, font_.drawString(graphics_, Vector2(0, 0), "é…", 0)); } TEST_F(BitmapFontTest, DrawUtf8WithOneChar) { EXPECT_CALL(graphics_, drawTexture(_, Vector2(0, 0), Rectangle(183, 0, 6, 14))); // é EXPECT_EQ(6u, font_.drawString(graphics_, Vector2(0, 0), "é…", 1)); } }
43.344262
91
0.658472
razielgn
252b108f0466b90e07918f9c9b6ca055376243dc
822
cpp
C++
CS Academy/Reversed Number/Accepted.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
1
2022-02-11T16:55:36.000Z
2022-02-11T16:55:36.000Z
CS Academy/Reversed Number/Accepted.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
null
null
null
CS Academy/Reversed Number/Accepted.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
null
null
null
/**************************************************************************************** * @author: kzvd4729 created: * solution_verdict: Accepted language: C++ * run_time: 8 ms memory_used: 656 KB * problem: ****************************************************************************************/ #include<bits/stdc++.h> #define log long long using namespace std; long n,nn,r; int main() { ios_base::sync_with_stdio(0); cin.tie(0); cin>>n; nn=n; long sum=0; while(n) { r=n%10; sum=sum*10+r; n/=10; } if(nn<sum)cout<<1<<endl; else cout<<0<<endl; return 0; }
30.444444
111
0.312652
kzvd4729
252d0cbecbb3d7735adcab81ad4002672be3606f
1,309
cpp
C++
GHJKL.cpp
taareek/c-plus-plus
b9d04f710e9b2e65786618f8bbced4a56c149444
[ "Unlicense" ]
null
null
null
GHJKL.cpp
taareek/c-plus-plus
b9d04f710e9b2e65786618f8bbced4a56c149444
[ "Unlicense" ]
null
null
null
GHJKL.cpp
taareek/c-plus-plus
b9d04f710e9b2e65786618f8bbced4a56c149444
[ "Unlicense" ]
null
null
null
/* Binary tree - Level Order Traversal */ #include<iostream> #include<queue> using namespace std; struct Node { int data; Node *left; Node *right; }; // Function to print Nodes in a binary tree in Level order void LevelOrder(Node *root) { if(root == NULL) return; queue<Node*> Q; Q.push(root); //while there is at least one discovered node while(!Q.empty()) { Node* current = Q.front(); Q.pop(); // removing the element at front cout<<current->data<<" "; if(current->left != NULL) Q.push(current->left); if(current->right != NULL) Q.push(current->right); } } // Function to Insert Node in a Binary Search Tree Node* Insert(Node *root,int data) { if(root == NULL) { root = new Node(); root->data = data; root->left = root->right = NULL; } else if(data <= root->data) root->left = Insert(root->left,data); else root->right = Insert(root->right,data); return root; } int main() { /*Code To Test the logic Creating an example tree M / \ B Q / \ \ A C Z */ Node* root = NULL; root = Insert(root,1); root = Insert(root,2); root = Insert(root,11); root = Insert(root,8); root = Insert(root,5); root = Insert(root,3); //Print Nodes in Level Order. LevelOrder(root); }
23.8
67
0.595875
taareek
252d983a052e75302efb7b30b8f9c996c220fffd
529
cpp
C++
343#integer-break/solution.cpp
llwwns/leetcode_solutions
e352c9bf6399ab3ee0f23889e70361c9f2a3bd33
[ "MIT" ]
null
null
null
343#integer-break/solution.cpp
llwwns/leetcode_solutions
e352c9bf6399ab3ee0f23889e70361c9f2a3bd33
[ "MIT" ]
null
null
null
343#integer-break/solution.cpp
llwwns/leetcode_solutions
e352c9bf6399ab3ee0f23889e70361c9f2a3bd33
[ "MIT" ]
null
null
null
class Solution { public: int pow (int a, int b) { int r = 1; while (b > 0) { if (b & 1) { r *= a; } a *= a; b >>= 1; } return r; } int integerBreak(int n) { if (n <= 3) return n - 1; switch (n % 3) { case 0: return pow(3, n / 3); case 1: return pow(3, n / 3 - 1) * 4; default: return pow(3, n / 3) * 2; } } };
21.16
42
0.296786
llwwns
25373e47020a4a0caf7b50957f0d8373fd03d441
2,048
cpp
C++
test/functional/gfal_test_stat.cpp
dynamic-entropy/gfal2
90bc0a58587b986a0d7335f244fd4cfe3079b72f
[ "Apache-2.0" ]
6
2018-08-28T15:20:24.000Z
2021-09-14T13:03:15.000Z
test/functional/gfal_test_stat.cpp
dynamic-entropy/gfal2
90bc0a58587b986a0d7335f244fd4cfe3079b72f
[ "Apache-2.0" ]
10
2020-06-16T09:21:04.000Z
2022-03-04T13:41:00.000Z
test/functional/gfal_test_stat.cpp
dynamic-entropy/gfal2
90bc0a58587b986a0d7335f244fd4cfe3079b72f
[ "Apache-2.0" ]
6
2020-06-13T18:06:41.000Z
2022-02-21T09:47:56.000Z
/* * Copyright (c) CERN 2013-2017 * * Copyright (c) Members of the EMI Collaboration. 2010-2013 * See http://www.eu-emi.eu/partners for details on the copyright * holders. * * 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 <gfal_api.h> #include <utils/exceptions/gerror_to_cpp.h> #include <common/gfal_gtest_asserts.h> class StatTest: public testing::Test { public: static const char* root; gfal2_context_t context; StatTest() { GError *error = NULL; context = gfal2_context_new(&error); Gfal::gerror_to_cpp(&error); } virtual ~StatTest() { gfal2_context_free(context); } }; const char* StatTest::root; TEST_F(StatTest, SimpleStat) { GError *error = NULL; struct stat statbuf; int ret; ret = gfal2_stat(context, root, &statbuf, &error); EXPECT_PRED_FORMAT2(AssertGfalSuccess, ret, error); std::cout << "stat successful" << std::endl; std::cout << "mode = " << std::oct << statbuf.st_mode << std::dec << std::endl; std::cout << "nlink = " << statbuf.st_nlink << std::endl; std::cout << "uid = " << statbuf.st_uid << std::endl; std::cout << "gid = " << statbuf.st_gid << std::endl; std::cout << "size = " << statbuf.st_size << std::endl; } int main(int argc, char **argv) { testing::InitGoogleTest(&argc, argv); if (argc < 1) { printf("Missing base url\n"); printf("\t%s [options] srm://host/base/path/\n", argv[0]); return 1; } StatTest::root = argv[1]; return RUN_ALL_TESTS(); }
26.25641
83
0.660156
dynamic-entropy
253d3dcdf1593d9217a69b9337de9505341d8796
46
hpp
C++
src/boost_type_traits_is_reference.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
10
2018-03-17T00:58:42.000Z
2021-07-06T02:48:49.000Z
src/boost_type_traits_is_reference.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
2
2021-03-26T15:17:35.000Z
2021-05-20T23:55:08.000Z
src/boost_type_traits_is_reference.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
4
2019-05-28T21:06:37.000Z
2021-07-06T03:06:52.000Z
#include <boost/type_traits/is_reference.hpp>
23
45
0.826087
miathedev
253e748aa6fc54859c97451abba22d03e6db42fb
88
hpp
C++
include/SplayLibrary/SplayLibrary.hpp
Reiex/SplayLibrary
94b68f371ea4c662c84dfe2dd0a6d1625b60fb04
[ "MIT" ]
1
2021-12-14T21:36:39.000Z
2021-12-14T21:36:39.000Z
include/SplayLibrary/SplayLibrary.hpp
Reiex/SplayLibrary
94b68f371ea4c662c84dfe2dd0a6d1625b60fb04
[ "MIT" ]
null
null
null
include/SplayLibrary/SplayLibrary.hpp
Reiex/SplayLibrary
94b68f371ea4c662c84dfe2dd0a6d1625b60fb04
[ "MIT" ]
null
null
null
#pragma once #include <SplayLibrary/Core/Core.hpp> #include <SplayLibrary/3D/3D.hpp>
22
38
0.75
Reiex
2543e29cb75e56e598be004776fef44a836d1d3d
275
cpp
C++
src/modules/osgManipulator/generated_code/_osgManipulator_global_variables.pypp.cpp
cmbruns/osgpyplusplus
f8bfca2cf841e15f6ddb41c958f3ad0d0b9e4b75
[ "BSD-3-Clause" ]
3
2017-04-20T09:11:47.000Z
2021-04-29T19:24:03.000Z
src/modules/osgManipulator/generated_code/_osgManipulator_global_variables.pypp.cpp
cmbruns/osgpyplusplus
f8bfca2cf841e15f6ddb41c958f3ad0d0b9e4b75
[ "BSD-3-Clause" ]
null
null
null
src/modules/osgManipulator/generated_code/_osgManipulator_global_variables.pypp.cpp
cmbruns/osgpyplusplus
f8bfca2cf841e15f6ddb41c958f3ad0d0b9e4b75
[ "BSD-3-Clause" ]
null
null
null
// This file has been generated by Py++. #include "boost/python.hpp" #include "wrap_osgManipulator.h" #include "_osgManipulator_global_variables.pypp.hpp" namespace bp = boost::python; void register_global_variables(){ bp::scope().attr("HANDLE_ALL") = HANDLE_ALL; }
19.642857
52
0.741818
cmbruns
8585f5fb5590400408832eab47e7e524d33a076c
1,625
cc
C++
gb/commands/relation.cc
kaladron/galactic-bloodshed
651676152d2f21b380ef1c3e109edc0d33e622df
[ "Apache-2.0" ]
5
2015-10-05T14:05:34.000Z
2020-01-21T18:52:11.000Z
gb/commands/relation.cc
kaladron/galactic-bloodshed
651676152d2f21b380ef1c3e109edc0d33e622df
[ "Apache-2.0" ]
3
2019-09-05T13:16:58.000Z
2019-09-05T13:32:42.000Z
gb/commands/relation.cc
kaladron/galactic-bloodshed
651676152d2f21b380ef1c3e109edc0d33e622df
[ "Apache-2.0" ]
1
2015-10-05T14:05:16.000Z
2015-10-05T14:05:16.000Z
// Copyright 2014 The Galactic Bloodshed Authors. All rights reserved. // Use of this source code is governed by a license that can be // found in the COPYING file. /* relation.c -- state relations among players */ import gblib; import std; #include "gb/commands/relation.h" #include "gb/GB_server.h" #include "gb/buffers.h" #include "gb/races.h" #include "gb/shlmisc.h" #include "gb/vars.h" static auto allied(const Race &r, const player_t p) { if (isset(r.atwar, p)) return "WAR"; if (isset(r.allied, p)) return "ALLIED"; return "neutral"; } void relation(const command_t &argv, GameObj &g) { const player_t Playernum = g.player; const governor_t Governor = g.governor; player_t q; if (argv.size() == 1) { q = Playernum; } else { if (!(q = get_player(argv[1]))) { g.out << "No such player.\n"; return; } } auto &race = races[q - 1]; sprintf(buf, "\n Racial Relations Report for %s\n\n", race.name); notify(Playernum, Governor, buf); g.out << " # know Race name Yours Theirs\n"; g.out << " - ---- --------- ----- ------\n"; for (auto r : races) { if (r.Playernum == race.Playernum) continue; sprintf(buf, "%2u %s (%3d%%) %20.20s : %10s %10s\n", r.Playernum, ((race.God || (race.translate[r.Playernum - 1] > 30)) && r.Metamorph && (Playernum == q)) ? "Morph" : " ", race.translate[r.Playernum - 1], r.name, allied(race, r.Playernum), allied(r, q)); notify(Playernum, Governor, buf); } }
29.545455
80
0.56
kaladron
858b56c7d4eb686b99abbd2b8130a8ec4961c7d8
2,251
hpp
C++
src/Cpp/Learning_Cpp/Meta_Programming/Example_IV/ATM_Version_Two.hpp
Ahmopasa/TheCodes
560ed94190fd0da8cc12285e9b4b5e27b19010a5
[ "MIT" ]
null
null
null
src/Cpp/Learning_Cpp/Meta_Programming/Example_IV/ATM_Version_Two.hpp
Ahmopasa/TheCodes
560ed94190fd0da8cc12285e9b4b5e27b19010a5
[ "MIT" ]
null
null
null
src/Cpp/Learning_Cpp/Meta_Programming/Example_IV/ATM_Version_Two.hpp
Ahmopasa/TheCodes
560ed94190fd0da8cc12285e9b4b5e27b19010a5
[ "MIT" ]
null
null
null
#ifndef ATM_VERSION_TWO_HPP #define ATM_VERSION_TWO_HPP #include <iostream> #include <string> #include <memory> #include <type_traits> namespace versionTwo{ class ATM { private: std::string m_identifier{"AhmetKandemirPehlivanli"}; int m_CashAmount{100000}; public: void showMembers(void) { std::cout << "Identifier => " << m_identifier << std::endl; std::cout << "CashAmount => " << m_CashAmount << std::endl; } void setIdentifier(const std::string& tempIdentifier) { this->m_identifier = tempIdentifier; } void setIntValue(const int& cashAmount) { this->m_CashAmount = cashAmount; } std::string& getIdentifier(void) { return this->m_identifier; } int& getCashAmount(void) { return this->m_CashAmount; } }; class ATM_Program { private: int m_totalATMAmount{}; ATM m_ATMMachine{}; public: void showMembers(void) { std::cout << "Total ATM Amount => " << m_totalATMAmount << std::endl; std::cout << "ATM Identifier;" << std::endl; m_ATMMachine.showMembers(); } void setIdentifier(const ATM& tempATMObj) { this->m_ATMMachine = tempATMObj; } void setIntValue(const int& tempATMAmount) { this->m_totalATMAmount = tempATMAmount; } ATM& getIdentifier(void) { return this->m_ATMMachine; } int& getCashAmount(void) { return this->m_totalATMAmount; } }; template<class T> void showMembers(T& tempClassRef) { tempClassRef.showMembers(); } template<class T> void changeIntValues(T& tempClassRef) { if(std::is_same<T, ATM>::value) { tempClassRef.setIntValue(2'000'000); } else if(std::is_same<T, ATM_Program>::value) { tempClassRef.setIntValue(5); } else { std::cout << "THE TYPE IS NOT SUPPORTED, YET" << std::endl; } } } #endif
23.946809
81
0.52821
Ahmopasa